three.core.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '185dev';
  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( 'THREE.MathUtils: 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( 'THREE.MathUtils: 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( 'THREE.Vector2: 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( 'THREE.Vector2: 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( 'THREE.Vector3: 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( 'THREE.Vector3: 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. * Whether the texture should use one of the 16 bit integer formats which are normalized
  5912. * to [0, 1] or [-1, 1] (depending on signed/unsigned) when sampled.
  5913. *
  5914. * @type {boolean}
  5915. * @default false
  5916. */
  5917. this.normalized = false;
  5918. }
  5919. /**
  5920. * The width of the texture in pixels.
  5921. */
  5922. get width() {
  5923. return this.source.getSize( _tempVec3 ).x;
  5924. }
  5925. /**
  5926. * The height of the texture in pixels.
  5927. */
  5928. get height() {
  5929. return this.source.getSize( _tempVec3 ).y;
  5930. }
  5931. /**
  5932. * The depth of the texture in pixels.
  5933. */
  5934. get depth() {
  5935. return this.source.getSize( _tempVec3 ).z;
  5936. }
  5937. /**
  5938. * The image object holding the texture data.
  5939. *
  5940. * @type {?Object}
  5941. */
  5942. get image() {
  5943. return this.source.data;
  5944. }
  5945. set image( value ) {
  5946. this.source.data = value;
  5947. }
  5948. /**
  5949. * Updates the texture transformation matrix from the properties {@link Texture#offset},
  5950. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5951. */
  5952. updateMatrix() {
  5953. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5954. }
  5955. /**
  5956. * Adds a range of data in the data texture to be updated on the GPU.
  5957. *
  5958. * @param {number} start - Position at which to start update.
  5959. * @param {number} count - The number of components to update.
  5960. */
  5961. addUpdateRange( start, count ) {
  5962. this.updateRanges.push( { start, count } );
  5963. }
  5964. /**
  5965. * Clears the update ranges.
  5966. */
  5967. clearUpdateRanges() {
  5968. this.updateRanges.length = 0;
  5969. }
  5970. /**
  5971. * Returns a new texture with copied values from this instance.
  5972. *
  5973. * @return {Texture} A clone of this instance.
  5974. */
  5975. clone() {
  5976. return new this.constructor().copy( this );
  5977. }
  5978. /**
  5979. * Copies the values of the given texture to this instance.
  5980. *
  5981. * @param {Texture} source - The texture to copy.
  5982. * @return {Texture} A reference to this instance.
  5983. */
  5984. copy( source ) {
  5985. this.name = source.name;
  5986. this.source = source.source;
  5987. this.mipmaps = source.mipmaps.slice( 0 );
  5988. this.mapping = source.mapping;
  5989. this.channel = source.channel;
  5990. this.wrapS = source.wrapS;
  5991. this.wrapT = source.wrapT;
  5992. this.magFilter = source.magFilter;
  5993. this.minFilter = source.minFilter;
  5994. this.anisotropy = source.anisotropy;
  5995. this.format = source.format;
  5996. this.internalFormat = source.internalFormat;
  5997. this.type = source.type;
  5998. this.normalized = source.normalized;
  5999. this.offset.copy( source.offset );
  6000. this.repeat.copy( source.repeat );
  6001. this.center.copy( source.center );
  6002. this.rotation = source.rotation;
  6003. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6004. this.matrix.copy( source.matrix );
  6005. this.generateMipmaps = source.generateMipmaps;
  6006. this.premultiplyAlpha = source.premultiplyAlpha;
  6007. this.flipY = source.flipY;
  6008. this.unpackAlignment = source.unpackAlignment;
  6009. this.colorSpace = source.colorSpace;
  6010. this.renderTarget = source.renderTarget;
  6011. this.isRenderTargetTexture = source.isRenderTargetTexture;
  6012. this.isArrayTexture = source.isArrayTexture;
  6013. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6014. this.needsUpdate = true;
  6015. return this;
  6016. }
  6017. /**
  6018. * Sets this texture's properties based on `values`.
  6019. * @param {Object} values - A container with texture parameters.
  6020. */
  6021. setValues( values ) {
  6022. for ( const key in values ) {
  6023. const newValue = values[ key ];
  6024. if ( newValue === undefined ) {
  6025. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  6026. continue;
  6027. }
  6028. const currentValue = this[ key ];
  6029. if ( currentValue === undefined ) {
  6030. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  6031. continue;
  6032. }
  6033. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  6034. currentValue.copy( newValue );
  6035. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  6036. currentValue.copy( newValue );
  6037. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  6038. currentValue.copy( newValue );
  6039. } else {
  6040. this[ key ] = newValue;
  6041. }
  6042. }
  6043. }
  6044. /**
  6045. * Serializes the texture into JSON.
  6046. *
  6047. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  6048. * @return {Object} A JSON object representing the serialized texture.
  6049. * @see {@link ObjectLoader#parse}
  6050. */
  6051. toJSON( meta ) {
  6052. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  6053. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6054. return meta.textures[ this.uuid ];
  6055. }
  6056. const output = {
  6057. metadata: {
  6058. version: 4.7,
  6059. type: 'Texture',
  6060. generator: 'Texture.toJSON'
  6061. },
  6062. uuid: this.uuid,
  6063. name: this.name,
  6064. image: this.source.toJSON( meta ).uuid,
  6065. mapping: this.mapping,
  6066. channel: this.channel,
  6067. repeat: [ this.repeat.x, this.repeat.y ],
  6068. offset: [ this.offset.x, this.offset.y ],
  6069. center: [ this.center.x, this.center.y ],
  6070. rotation: this.rotation,
  6071. wrap: [ this.wrapS, this.wrapT ],
  6072. format: this.format,
  6073. internalFormat: this.internalFormat,
  6074. type: this.type,
  6075. normalized: this.normalized,
  6076. colorSpace: this.colorSpace,
  6077. minFilter: this.minFilter,
  6078. magFilter: this.magFilter,
  6079. anisotropy: this.anisotropy,
  6080. flipY: this.flipY,
  6081. generateMipmaps: this.generateMipmaps,
  6082. premultiplyAlpha: this.premultiplyAlpha,
  6083. unpackAlignment: this.unpackAlignment
  6084. };
  6085. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6086. if ( ! isRootObject ) {
  6087. meta.textures[ this.uuid ] = output;
  6088. }
  6089. return output;
  6090. }
  6091. /**
  6092. * Frees the GPU-related resources allocated by this instance. Call this
  6093. * method whenever this instance is no longer used in your app.
  6094. *
  6095. * @fires Texture#dispose
  6096. */
  6097. dispose() {
  6098. /**
  6099. * Fires when the texture has been disposed of.
  6100. *
  6101. * @event Texture#dispose
  6102. * @type {Object}
  6103. */
  6104. this.dispatchEvent( { type: 'dispose' } );
  6105. }
  6106. /**
  6107. * Transforms the given uv vector with the textures uv transformation matrix.
  6108. *
  6109. * @param {Vector2} uv - The uv vector.
  6110. * @return {Vector2} The transformed uv vector.
  6111. */
  6112. transformUv( uv ) {
  6113. if ( this.mapping !== UVMapping ) return uv;
  6114. uv.applyMatrix3( this.matrix );
  6115. if ( uv.x < 0 || uv.x > 1 ) {
  6116. switch ( this.wrapS ) {
  6117. case RepeatWrapping:
  6118. uv.x = uv.x - Math.floor( uv.x );
  6119. break;
  6120. case ClampToEdgeWrapping:
  6121. uv.x = uv.x < 0 ? 0 : 1;
  6122. break;
  6123. case MirroredRepeatWrapping:
  6124. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6125. uv.x = Math.ceil( uv.x ) - uv.x;
  6126. } else {
  6127. uv.x = uv.x - Math.floor( uv.x );
  6128. }
  6129. break;
  6130. }
  6131. }
  6132. if ( uv.y < 0 || uv.y > 1 ) {
  6133. switch ( this.wrapT ) {
  6134. case RepeatWrapping:
  6135. uv.y = uv.y - Math.floor( uv.y );
  6136. break;
  6137. case ClampToEdgeWrapping:
  6138. uv.y = uv.y < 0 ? 0 : 1;
  6139. break;
  6140. case MirroredRepeatWrapping:
  6141. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6142. uv.y = Math.ceil( uv.y ) - uv.y;
  6143. } else {
  6144. uv.y = uv.y - Math.floor( uv.y );
  6145. }
  6146. break;
  6147. }
  6148. }
  6149. if ( this.flipY ) {
  6150. uv.y = 1 - uv.y;
  6151. }
  6152. return uv;
  6153. }
  6154. /**
  6155. * Setting this property to `true` indicates the engine the texture
  6156. * must be updated in the next render. This triggers a texture upload
  6157. * to the GPU and ensures correct texture parameter configuration.
  6158. *
  6159. * @type {boolean}
  6160. * @default false
  6161. * @param {boolean} value
  6162. */
  6163. set needsUpdate( value ) {
  6164. if ( value === true ) {
  6165. this.version ++;
  6166. this.source.needsUpdate = true;
  6167. }
  6168. }
  6169. /**
  6170. * Setting this property to `true` indicates the engine the PMREM
  6171. * must be regenerated.
  6172. *
  6173. * @type {boolean}
  6174. * @default false
  6175. * @param {boolean} value
  6176. */
  6177. set needsPMREMUpdate( value ) {
  6178. if ( value === true ) {
  6179. this.pmremVersion ++;
  6180. }
  6181. }
  6182. }
  6183. /**
  6184. * The default image for all textures.
  6185. *
  6186. * @static
  6187. * @type {?Image}
  6188. * @default null
  6189. */
  6190. Texture.DEFAULT_IMAGE = null;
  6191. /**
  6192. * The default mapping for all textures.
  6193. *
  6194. * @static
  6195. * @type {number}
  6196. * @default UVMapping
  6197. */
  6198. Texture.DEFAULT_MAPPING = UVMapping;
  6199. /**
  6200. * The default anisotropy value for all textures.
  6201. *
  6202. * @static
  6203. * @type {number}
  6204. * @default 1
  6205. */
  6206. Texture.DEFAULT_ANISOTROPY = 1;
  6207. /**
  6208. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6209. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6210. *
  6211. * - A point in 4D space.
  6212. * - A direction and length in 4D space. In three.js the length will
  6213. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6214. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6215. * - Any arbitrary ordered quadruplet of numbers.
  6216. *
  6217. * There are other things a 4D vector can be used to represent, however these
  6218. * are the most common uses in *three.js*.
  6219. *
  6220. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6221. * the corresponding order.
  6222. * ```js
  6223. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6224. *
  6225. * //no arguments; will be initialised to (0, 0, 0, 1)
  6226. * const b = new THREE.Vector4( );
  6227. *
  6228. * const d = a.dot( b );
  6229. * ```
  6230. */
  6231. class Vector4 {
  6232. static {
  6233. /**
  6234. * This flag can be used for type testing.
  6235. *
  6236. * @type {boolean}
  6237. * @readonly
  6238. * @default true
  6239. */
  6240. Vector4.prototype.isVector4 = true;
  6241. }
  6242. /**
  6243. * Constructs a new 4D vector.
  6244. *
  6245. * @param {number} [x=0] - The x value of this vector.
  6246. * @param {number} [y=0] - The y value of this vector.
  6247. * @param {number} [z=0] - The z value of this vector.
  6248. * @param {number} [w=1] - The w value of this vector.
  6249. */
  6250. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6251. /**
  6252. * The x value of this vector.
  6253. *
  6254. * @type {number}
  6255. */
  6256. this.x = x;
  6257. /**
  6258. * The y value of this vector.
  6259. *
  6260. * @type {number}
  6261. */
  6262. this.y = y;
  6263. /**
  6264. * The z value of this vector.
  6265. *
  6266. * @type {number}
  6267. */
  6268. this.z = z;
  6269. /**
  6270. * The w value of this vector.
  6271. *
  6272. * @type {number}
  6273. */
  6274. this.w = w;
  6275. }
  6276. /**
  6277. * Alias for {@link Vector4#z}.
  6278. *
  6279. * @type {number}
  6280. */
  6281. get width() {
  6282. return this.z;
  6283. }
  6284. set width( value ) {
  6285. this.z = value;
  6286. }
  6287. /**
  6288. * Alias for {@link Vector4#w}.
  6289. *
  6290. * @type {number}
  6291. */
  6292. get height() {
  6293. return this.w;
  6294. }
  6295. set height( value ) {
  6296. this.w = value;
  6297. }
  6298. /**
  6299. * Sets the vector components.
  6300. *
  6301. * @param {number} x - The value of the x component.
  6302. * @param {number} y - The value of the y component.
  6303. * @param {number} z - The value of the z component.
  6304. * @param {number} w - The value of the w component.
  6305. * @return {Vector4} A reference to this vector.
  6306. */
  6307. set( x, y, z, w ) {
  6308. this.x = x;
  6309. this.y = y;
  6310. this.z = z;
  6311. this.w = w;
  6312. return this;
  6313. }
  6314. /**
  6315. * Sets the vector components to the same value.
  6316. *
  6317. * @param {number} scalar - The value to set for all vector components.
  6318. * @return {Vector4} A reference to this vector.
  6319. */
  6320. setScalar( scalar ) {
  6321. this.x = scalar;
  6322. this.y = scalar;
  6323. this.z = scalar;
  6324. this.w = scalar;
  6325. return this;
  6326. }
  6327. /**
  6328. * Sets the vector's x component to the given value
  6329. *
  6330. * @param {number} x - The value to set.
  6331. * @return {Vector4} A reference to this vector.
  6332. */
  6333. setX( x ) {
  6334. this.x = x;
  6335. return this;
  6336. }
  6337. /**
  6338. * Sets the vector's y component to the given value
  6339. *
  6340. * @param {number} y - The value to set.
  6341. * @return {Vector4} A reference to this vector.
  6342. */
  6343. setY( y ) {
  6344. this.y = y;
  6345. return this;
  6346. }
  6347. /**
  6348. * Sets the vector's z component to the given value
  6349. *
  6350. * @param {number} z - The value to set.
  6351. * @return {Vector4} A reference to this vector.
  6352. */
  6353. setZ( z ) {
  6354. this.z = z;
  6355. return this;
  6356. }
  6357. /**
  6358. * Sets the vector's w component to the given value
  6359. *
  6360. * @param {number} w - The value to set.
  6361. * @return {Vector4} A reference to this vector.
  6362. */
  6363. setW( w ) {
  6364. this.w = w;
  6365. return this;
  6366. }
  6367. /**
  6368. * Allows to set a vector component with an index.
  6369. *
  6370. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6371. * `2` equals to z, `3` equals to w.
  6372. * @param {number} value - The value to set.
  6373. * @return {Vector4} A reference to this vector.
  6374. */
  6375. setComponent( index, value ) {
  6376. switch ( index ) {
  6377. case 0: this.x = value; break;
  6378. case 1: this.y = value; break;
  6379. case 2: this.z = value; break;
  6380. case 3: this.w = value; break;
  6381. default: throw new Error( 'THREE.Vector4: index is out of range: ' + index );
  6382. }
  6383. return this;
  6384. }
  6385. /**
  6386. * Returns the value of the vector component which matches the given index.
  6387. *
  6388. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6389. * `2` equals to z, `3` equals to w.
  6390. * @return {number} A vector component value.
  6391. */
  6392. getComponent( index ) {
  6393. switch ( index ) {
  6394. case 0: return this.x;
  6395. case 1: return this.y;
  6396. case 2: return this.z;
  6397. case 3: return this.w;
  6398. default: throw new Error( 'THREE.Vector4: index is out of range: ' + index );
  6399. }
  6400. }
  6401. /**
  6402. * Returns a new vector with copied values from this instance.
  6403. *
  6404. * @return {Vector4} A clone of this instance.
  6405. */
  6406. clone() {
  6407. return new this.constructor( this.x, this.y, this.z, this.w );
  6408. }
  6409. /**
  6410. * Copies the values of the given vector to this instance.
  6411. *
  6412. * @param {Vector3|Vector4} v - The vector to copy.
  6413. * @return {Vector4} A reference to this vector.
  6414. */
  6415. copy( v ) {
  6416. this.x = v.x;
  6417. this.y = v.y;
  6418. this.z = v.z;
  6419. this.w = ( v.w !== undefined ) ? v.w : 1;
  6420. return this;
  6421. }
  6422. /**
  6423. * Adds the given vector to this instance.
  6424. *
  6425. * @param {Vector4} v - The vector to add.
  6426. * @return {Vector4} A reference to this vector.
  6427. */
  6428. add( v ) {
  6429. this.x += v.x;
  6430. this.y += v.y;
  6431. this.z += v.z;
  6432. this.w += v.w;
  6433. return this;
  6434. }
  6435. /**
  6436. * Adds the given scalar value to all components of this instance.
  6437. *
  6438. * @param {number} s - The scalar to add.
  6439. * @return {Vector4} A reference to this vector.
  6440. */
  6441. addScalar( s ) {
  6442. this.x += s;
  6443. this.y += s;
  6444. this.z += s;
  6445. this.w += s;
  6446. return this;
  6447. }
  6448. /**
  6449. * Adds the given vectors and stores the result in this instance.
  6450. *
  6451. * @param {Vector4} a - The first vector.
  6452. * @param {Vector4} b - The second vector.
  6453. * @return {Vector4} A reference to this vector.
  6454. */
  6455. addVectors( a, b ) {
  6456. this.x = a.x + b.x;
  6457. this.y = a.y + b.y;
  6458. this.z = a.z + b.z;
  6459. this.w = a.w + b.w;
  6460. return this;
  6461. }
  6462. /**
  6463. * Adds the given vector scaled by the given factor to this instance.
  6464. *
  6465. * @param {Vector4} v - The vector.
  6466. * @param {number} s - The factor that scales `v`.
  6467. * @return {Vector4} A reference to this vector.
  6468. */
  6469. addScaledVector( v, s ) {
  6470. this.x += v.x * s;
  6471. this.y += v.y * s;
  6472. this.z += v.z * s;
  6473. this.w += v.w * s;
  6474. return this;
  6475. }
  6476. /**
  6477. * Subtracts the given vector from this instance.
  6478. *
  6479. * @param {Vector4} v - The vector to subtract.
  6480. * @return {Vector4} A reference to this vector.
  6481. */
  6482. sub( v ) {
  6483. this.x -= v.x;
  6484. this.y -= v.y;
  6485. this.z -= v.z;
  6486. this.w -= v.w;
  6487. return this;
  6488. }
  6489. /**
  6490. * Subtracts the given scalar value from all components of this instance.
  6491. *
  6492. * @param {number} s - The scalar to subtract.
  6493. * @return {Vector4} A reference to this vector.
  6494. */
  6495. subScalar( s ) {
  6496. this.x -= s;
  6497. this.y -= s;
  6498. this.z -= s;
  6499. this.w -= s;
  6500. return this;
  6501. }
  6502. /**
  6503. * Subtracts the given vectors and stores the result in this instance.
  6504. *
  6505. * @param {Vector4} a - The first vector.
  6506. * @param {Vector4} b - The second vector.
  6507. * @return {Vector4} A reference to this vector.
  6508. */
  6509. subVectors( a, b ) {
  6510. this.x = a.x - b.x;
  6511. this.y = a.y - b.y;
  6512. this.z = a.z - b.z;
  6513. this.w = a.w - b.w;
  6514. return this;
  6515. }
  6516. /**
  6517. * Multiplies the given vector with this instance.
  6518. *
  6519. * @param {Vector4} v - The vector to multiply.
  6520. * @return {Vector4} A reference to this vector.
  6521. */
  6522. multiply( v ) {
  6523. this.x *= v.x;
  6524. this.y *= v.y;
  6525. this.z *= v.z;
  6526. this.w *= v.w;
  6527. return this;
  6528. }
  6529. /**
  6530. * Multiplies the given scalar value with all components of this instance.
  6531. *
  6532. * @param {number} scalar - The scalar to multiply.
  6533. * @return {Vector4} A reference to this vector.
  6534. */
  6535. multiplyScalar( scalar ) {
  6536. this.x *= scalar;
  6537. this.y *= scalar;
  6538. this.z *= scalar;
  6539. this.w *= scalar;
  6540. return this;
  6541. }
  6542. /**
  6543. * Multiplies this vector with the given 4x4 matrix.
  6544. *
  6545. * @param {Matrix4} m - The 4x4 matrix.
  6546. * @return {Vector4} A reference to this vector.
  6547. */
  6548. applyMatrix4( m ) {
  6549. const x = this.x, y = this.y, z = this.z, w = this.w;
  6550. const e = m.elements;
  6551. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6552. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6553. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6554. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6555. return this;
  6556. }
  6557. /**
  6558. * Divides this instance by the given vector.
  6559. *
  6560. * @param {Vector4} v - The vector to divide.
  6561. * @return {Vector4} A reference to this vector.
  6562. */
  6563. divide( v ) {
  6564. this.x /= v.x;
  6565. this.y /= v.y;
  6566. this.z /= v.z;
  6567. this.w /= v.w;
  6568. return this;
  6569. }
  6570. /**
  6571. * Divides this vector by the given scalar.
  6572. *
  6573. * @param {number} scalar - The scalar to divide.
  6574. * @return {Vector4} A reference to this vector.
  6575. */
  6576. divideScalar( scalar ) {
  6577. return this.multiplyScalar( 1 / scalar );
  6578. }
  6579. /**
  6580. * Sets the x, y and z components of this
  6581. * vector to the quaternion's axis and w to the angle.
  6582. *
  6583. * @param {Quaternion} q - The Quaternion to set.
  6584. * @return {Vector4} A reference to this vector.
  6585. */
  6586. setAxisAngleFromQuaternion( q ) {
  6587. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6588. // q is assumed to be normalized
  6589. this.w = 2 * Math.acos( q.w );
  6590. const s = Math.sqrt( 1 - q.w * q.w );
  6591. if ( s < 0.0001 ) {
  6592. this.x = 1;
  6593. this.y = 0;
  6594. this.z = 0;
  6595. } else {
  6596. this.x = q.x / s;
  6597. this.y = q.y / s;
  6598. this.z = q.z / s;
  6599. }
  6600. return this;
  6601. }
  6602. /**
  6603. * Sets the x, y and z components of this
  6604. * vector to the axis of rotation and w to the angle.
  6605. *
  6606. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6607. * @return {Vector4} A reference to this vector.
  6608. */
  6609. setAxisAngleFromRotationMatrix( m ) {
  6610. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6611. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6612. let angle, x, y, z; // variables for result
  6613. const epsilon = 0.01, // margin to allow for rounding errors
  6614. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6615. te = m.elements,
  6616. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6617. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6618. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6619. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6620. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6621. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6622. // singularity found
  6623. // first check for identity matrix which must have +1 for all terms
  6624. // in leading diagonal and zero in other terms
  6625. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6626. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6627. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6628. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6629. // this singularity is identity matrix so angle = 0
  6630. this.set( 1, 0, 0, 0 );
  6631. return this; // zero angle, arbitrary axis
  6632. }
  6633. // otherwise this singularity is angle = 180
  6634. angle = Math.PI;
  6635. const xx = ( m11 + 1 ) / 2;
  6636. const yy = ( m22 + 1 ) / 2;
  6637. const zz = ( m33 + 1 ) / 2;
  6638. const xy = ( m12 + m21 ) / 4;
  6639. const xz = ( m13 + m31 ) / 4;
  6640. const yz = ( m23 + m32 ) / 4;
  6641. if ( ( xx > yy ) && ( xx > zz ) ) {
  6642. // m11 is the largest diagonal term
  6643. if ( xx < epsilon ) {
  6644. x = 0;
  6645. y = 0.707106781;
  6646. z = 0.707106781;
  6647. } else {
  6648. x = Math.sqrt( xx );
  6649. y = xy / x;
  6650. z = xz / x;
  6651. }
  6652. } else if ( yy > zz ) {
  6653. // m22 is the largest diagonal term
  6654. if ( yy < epsilon ) {
  6655. x = 0.707106781;
  6656. y = 0;
  6657. z = 0.707106781;
  6658. } else {
  6659. y = Math.sqrt( yy );
  6660. x = xy / y;
  6661. z = yz / y;
  6662. }
  6663. } else {
  6664. // m33 is the largest diagonal term so base result on this
  6665. if ( zz < epsilon ) {
  6666. x = 0.707106781;
  6667. y = 0.707106781;
  6668. z = 0;
  6669. } else {
  6670. z = Math.sqrt( zz );
  6671. x = xz / z;
  6672. y = yz / z;
  6673. }
  6674. }
  6675. this.set( x, y, z, angle );
  6676. return this; // return 180 deg rotation
  6677. }
  6678. // as we have reached here there are no singularities so we can handle normally
  6679. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6680. ( m13 - m31 ) * ( m13 - m31 ) +
  6681. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6682. if ( Math.abs( s ) < 0.001 ) s = 1;
  6683. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6684. // caught by singularity test above, but I've left it in just in case
  6685. this.x = ( m32 - m23 ) / s;
  6686. this.y = ( m13 - m31 ) / s;
  6687. this.z = ( m21 - m12 ) / s;
  6688. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6689. return this;
  6690. }
  6691. /**
  6692. * Sets the vector components to the position elements of the
  6693. * given transformation matrix.
  6694. *
  6695. * @param {Matrix4} m - The 4x4 matrix.
  6696. * @return {Vector4} A reference to this vector.
  6697. */
  6698. setFromMatrixPosition( m ) {
  6699. const e = m.elements;
  6700. this.x = e[ 12 ];
  6701. this.y = e[ 13 ];
  6702. this.z = e[ 14 ];
  6703. this.w = e[ 15 ];
  6704. return this;
  6705. }
  6706. /**
  6707. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6708. * value, replace that value with the corresponding min value.
  6709. *
  6710. * @param {Vector4} v - The vector.
  6711. * @return {Vector4} A reference to this vector.
  6712. */
  6713. min( v ) {
  6714. this.x = Math.min( this.x, v.x );
  6715. this.y = Math.min( this.y, v.y );
  6716. this.z = Math.min( this.z, v.z );
  6717. this.w = Math.min( this.w, v.w );
  6718. return this;
  6719. }
  6720. /**
  6721. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6722. * value, replace that value with the corresponding max value.
  6723. *
  6724. * @param {Vector4} v - The vector.
  6725. * @return {Vector4} A reference to this vector.
  6726. */
  6727. max( v ) {
  6728. this.x = Math.max( this.x, v.x );
  6729. this.y = Math.max( this.y, v.y );
  6730. this.z = Math.max( this.z, v.z );
  6731. this.w = Math.max( this.w, v.w );
  6732. return this;
  6733. }
  6734. /**
  6735. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6736. * value, it is replaced by the corresponding value.
  6737. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6738. * it is replaced by the corresponding value.
  6739. *
  6740. * @param {Vector4} min - The minimum x, y and z values.
  6741. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6742. * @return {Vector4} A reference to this vector.
  6743. */
  6744. clamp( min, max ) {
  6745. // assumes min < max, componentwise
  6746. this.x = clamp( this.x, min.x, max.x );
  6747. this.y = clamp( this.y, min.y, max.y );
  6748. this.z = clamp( this.z, min.z, max.z );
  6749. this.w = clamp( this.w, min.w, max.w );
  6750. return this;
  6751. }
  6752. /**
  6753. * If this vector's x, y, z or w values are greater than the max value, they are
  6754. * replaced by the max value.
  6755. * If this vector's x, y, z or w values are less than the min value, they are
  6756. * replaced by the min value.
  6757. *
  6758. * @param {number} minVal - The minimum value the components will be clamped to.
  6759. * @param {number} maxVal - The maximum value the components will be clamped to.
  6760. * @return {Vector4} A reference to this vector.
  6761. */
  6762. clampScalar( minVal, maxVal ) {
  6763. this.x = clamp( this.x, minVal, maxVal );
  6764. this.y = clamp( this.y, minVal, maxVal );
  6765. this.z = clamp( this.z, minVal, maxVal );
  6766. this.w = clamp( this.w, minVal, maxVal );
  6767. return this;
  6768. }
  6769. /**
  6770. * If this vector's length is greater than the max value, it is replaced by
  6771. * the max value.
  6772. * If this vector's length is less than the min value, it is replaced by the
  6773. * min value.
  6774. *
  6775. * @param {number} min - The minimum value the vector length will be clamped to.
  6776. * @param {number} max - The maximum value the vector length will be clamped to.
  6777. * @return {Vector4} A reference to this vector.
  6778. */
  6779. clampLength( min, max ) {
  6780. const length = this.length();
  6781. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6782. }
  6783. /**
  6784. * The components of this vector are rounded down to the nearest integer value.
  6785. *
  6786. * @return {Vector4} A reference to this vector.
  6787. */
  6788. floor() {
  6789. this.x = Math.floor( this.x );
  6790. this.y = Math.floor( this.y );
  6791. this.z = Math.floor( this.z );
  6792. this.w = Math.floor( this.w );
  6793. return this;
  6794. }
  6795. /**
  6796. * The components of this vector are rounded up to the nearest integer value.
  6797. *
  6798. * @return {Vector4} A reference to this vector.
  6799. */
  6800. ceil() {
  6801. this.x = Math.ceil( this.x );
  6802. this.y = Math.ceil( this.y );
  6803. this.z = Math.ceil( this.z );
  6804. this.w = Math.ceil( this.w );
  6805. return this;
  6806. }
  6807. /**
  6808. * The components of this vector are rounded to the nearest integer value
  6809. *
  6810. * @return {Vector4} A reference to this vector.
  6811. */
  6812. round() {
  6813. this.x = Math.round( this.x );
  6814. this.y = Math.round( this.y );
  6815. this.z = Math.round( this.z );
  6816. this.w = Math.round( this.w );
  6817. return this;
  6818. }
  6819. /**
  6820. * The components of this vector are rounded towards zero (up if negative,
  6821. * down if positive) to an integer value.
  6822. *
  6823. * @return {Vector4} A reference to this vector.
  6824. */
  6825. roundToZero() {
  6826. this.x = Math.trunc( this.x );
  6827. this.y = Math.trunc( this.y );
  6828. this.z = Math.trunc( this.z );
  6829. this.w = Math.trunc( this.w );
  6830. return this;
  6831. }
  6832. /**
  6833. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6834. *
  6835. * @return {Vector4} A reference to this vector.
  6836. */
  6837. negate() {
  6838. this.x = - this.x;
  6839. this.y = - this.y;
  6840. this.z = - this.z;
  6841. this.w = - this.w;
  6842. return this;
  6843. }
  6844. /**
  6845. * Calculates the dot product of the given vector with this instance.
  6846. *
  6847. * @param {Vector4} v - The vector to compute the dot product with.
  6848. * @return {number} The result of the dot product.
  6849. */
  6850. dot( v ) {
  6851. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6852. }
  6853. /**
  6854. * Computes the square of the Euclidean length (straight-line length) from
  6855. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6856. * compare the length squared instead as it is slightly more efficient to calculate.
  6857. *
  6858. * @return {number} The square length of this vector.
  6859. */
  6860. lengthSq() {
  6861. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6862. }
  6863. /**
  6864. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6865. *
  6866. * @return {number} The length of this vector.
  6867. */
  6868. length() {
  6869. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6870. }
  6871. /**
  6872. * Computes the Manhattan length of this vector.
  6873. *
  6874. * @return {number} The length of this vector.
  6875. */
  6876. manhattanLength() {
  6877. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6878. }
  6879. /**
  6880. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6881. * with the same direction as this one, but with a vector length of `1`.
  6882. *
  6883. * @return {Vector4} A reference to this vector.
  6884. */
  6885. normalize() {
  6886. return this.divideScalar( this.length() || 1 );
  6887. }
  6888. /**
  6889. * Sets this vector to a vector with the same direction as this one, but
  6890. * with the specified length.
  6891. *
  6892. * @param {number} length - The new length of this vector.
  6893. * @return {Vector4} A reference to this vector.
  6894. */
  6895. setLength( length ) {
  6896. return this.normalize().multiplyScalar( length );
  6897. }
  6898. /**
  6899. * Linearly interpolates between the given vector and this instance, where
  6900. * alpha is the percent distance along the line - alpha = 0 will be this
  6901. * vector, and alpha = 1 will be the given one.
  6902. *
  6903. * @param {Vector4} v - The vector to interpolate towards.
  6904. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6905. * @return {Vector4} A reference to this vector.
  6906. */
  6907. lerp( v, alpha ) {
  6908. this.x += ( v.x - this.x ) * alpha;
  6909. this.y += ( v.y - this.y ) * alpha;
  6910. this.z += ( v.z - this.z ) * alpha;
  6911. this.w += ( v.w - this.w ) * alpha;
  6912. return this;
  6913. }
  6914. /**
  6915. * Linearly interpolates between the given vectors, where alpha is the percent
  6916. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6917. * be the second one. The result is stored in this instance.
  6918. *
  6919. * @param {Vector4} v1 - The first vector.
  6920. * @param {Vector4} v2 - The second vector.
  6921. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6922. * @return {Vector4} A reference to this vector.
  6923. */
  6924. lerpVectors( v1, v2, alpha ) {
  6925. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6926. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6927. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6928. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6929. return this;
  6930. }
  6931. /**
  6932. * Returns `true` if this vector is equal with the given one.
  6933. *
  6934. * @param {Vector4} v - The vector to test for equality.
  6935. * @return {boolean} Whether this vector is equal with the given one.
  6936. */
  6937. equals( v ) {
  6938. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6939. }
  6940. /**
  6941. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6942. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6943. *
  6944. * @param {Array<number>} array - An array holding the vector component values.
  6945. * @param {number} [offset=0] - The offset into the array.
  6946. * @return {Vector4} A reference to this vector.
  6947. */
  6948. fromArray( array, offset = 0 ) {
  6949. this.x = array[ offset ];
  6950. this.y = array[ offset + 1 ];
  6951. this.z = array[ offset + 2 ];
  6952. this.w = array[ offset + 3 ];
  6953. return this;
  6954. }
  6955. /**
  6956. * Writes the components of this vector to the given array. If no array is provided,
  6957. * the method returns a new instance.
  6958. *
  6959. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6960. * @param {number} [offset=0] - Index of the first element in the array.
  6961. * @return {Array<number>} The vector components.
  6962. */
  6963. toArray( array = [], offset = 0 ) {
  6964. array[ offset ] = this.x;
  6965. array[ offset + 1 ] = this.y;
  6966. array[ offset + 2 ] = this.z;
  6967. array[ offset + 3 ] = this.w;
  6968. return array;
  6969. }
  6970. /**
  6971. * Sets the components of this vector from the given buffer attribute.
  6972. *
  6973. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6974. * @param {number} index - The index into the attribute.
  6975. * @return {Vector4} A reference to this vector.
  6976. */
  6977. fromBufferAttribute( attribute, index ) {
  6978. this.x = attribute.getX( index );
  6979. this.y = attribute.getY( index );
  6980. this.z = attribute.getZ( index );
  6981. this.w = attribute.getW( index );
  6982. return this;
  6983. }
  6984. /**
  6985. * Sets each component of this vector to a pseudo-random value between `0` and
  6986. * `1`, excluding `1`.
  6987. *
  6988. * @return {Vector4} A reference to this vector.
  6989. */
  6990. random() {
  6991. this.x = Math.random();
  6992. this.y = Math.random();
  6993. this.z = Math.random();
  6994. this.w = Math.random();
  6995. return this;
  6996. }
  6997. *[ Symbol.iterator ]() {
  6998. yield this.x;
  6999. yield this.y;
  7000. yield this.z;
  7001. yield this.w;
  7002. }
  7003. }
  7004. /**
  7005. * A render target is a buffer where the video card draws pixels for a scene
  7006. * that is being rendered in the background. It is used in different effects,
  7007. * such as applying postprocessing to a rendered image before displaying it
  7008. * on the screen.
  7009. *
  7010. * @augments EventDispatcher
  7011. */
  7012. class RenderTarget extends EventDispatcher {
  7013. /**
  7014. * Render target options.
  7015. *
  7016. * @typedef {Object} RenderTarget~Options
  7017. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  7018. * @property {number} [magFilter=LinearFilter] - The mag filter.
  7019. * @property {number} [minFilter=LinearFilter] - The min filter.
  7020. * @property {number} [format=RGBAFormat] - The texture format.
  7021. * @property {number} [type=UnsignedByteType] - The texture type.
  7022. * @property {?string} [internalFormat=null] - The texture's internal format.
  7023. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7024. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  7025. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  7026. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  7027. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  7028. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  7029. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  7030. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  7031. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  7032. * @property {number} [samples=0] - The MSAA samples count.
  7033. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  7034. * @property {number} [depth=1] - The texture depth.
  7035. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering (WebGL OVR_multiview2 extension).
  7036. * @property {boolean} [useArrayDepthTexture=false] - Whether to create the depth texture as an array texture for per-layer depth testing. This is separate from multiview so layered render targets can use array depth without the multiview extension.
  7037. */
  7038. /**
  7039. * Constructs a new render target.
  7040. *
  7041. * @param {number} [width=1] - The width of the render target.
  7042. * @param {number} [height=1] - The height of the render target.
  7043. * @param {RenderTarget~Options} [options] - The configuration object.
  7044. */
  7045. constructor( width = 1, height = 1, options = {} ) {
  7046. super();
  7047. options = Object.assign( {
  7048. generateMipmaps: false,
  7049. internalFormat: null,
  7050. minFilter: LinearFilter,
  7051. depthBuffer: true,
  7052. stencilBuffer: false,
  7053. resolveDepthBuffer: true,
  7054. resolveStencilBuffer: true,
  7055. depthTexture: null,
  7056. samples: 0,
  7057. count: 1,
  7058. depth: 1,
  7059. multiview: false,
  7060. useArrayDepthTexture: false
  7061. }, options );
  7062. /**
  7063. * This flag can be used for type testing.
  7064. *
  7065. * @type {boolean}
  7066. * @readonly
  7067. * @default true
  7068. */
  7069. this.isRenderTarget = true;
  7070. /**
  7071. * The width of the render target.
  7072. *
  7073. * @type {number}
  7074. * @default 1
  7075. */
  7076. this.width = width;
  7077. /**
  7078. * The height of the render target.
  7079. *
  7080. * @type {number}
  7081. * @default 1
  7082. */
  7083. this.height = height;
  7084. /**
  7085. * The depth of the render target.
  7086. *
  7087. * @type {number}
  7088. * @default 1
  7089. */
  7090. this.depth = options.depth;
  7091. /**
  7092. * A rectangular area inside the render target's viewport. Fragments that are
  7093. * outside the area will be discarded.
  7094. *
  7095. * @type {Vector4}
  7096. * @default (0,0,width,height)
  7097. */
  7098. this.scissor = new Vector4( 0, 0, width, height );
  7099. /**
  7100. * Indicates whether the scissor test should be enabled when rendering into
  7101. * this render target or not.
  7102. *
  7103. * @type {boolean}
  7104. * @default false
  7105. */
  7106. this.scissorTest = false;
  7107. /**
  7108. * A rectangular area representing the render target's viewport.
  7109. *
  7110. * @type {Vector4}
  7111. * @default (0,0,width,height)
  7112. */
  7113. this.viewport = new Vector4( 0, 0, width, height );
  7114. /**
  7115. * An array of textures. Each color attachment is represented as a separate texture.
  7116. * Has at least a single entry for the default color attachment.
  7117. *
  7118. * @type {Array<Texture>}
  7119. */
  7120. this.textures = [];
  7121. const image = { width: width, height: height, depth: options.depth };
  7122. const texture = new Texture( image );
  7123. const count = options.count;
  7124. for ( let i = 0; i < count; i ++ ) {
  7125. this.textures[ i ] = texture.clone();
  7126. this.textures[ i ].isRenderTargetTexture = true;
  7127. this.textures[ i ].renderTarget = this;
  7128. }
  7129. this._setTextureOptions( options );
  7130. /**
  7131. * Whether to allocate a depth buffer or not.
  7132. *
  7133. * @type {boolean}
  7134. * @default true
  7135. */
  7136. this.depthBuffer = options.depthBuffer;
  7137. /**
  7138. * Whether to allocate a stencil buffer or not.
  7139. *
  7140. * @type {boolean}
  7141. * @default false
  7142. */
  7143. this.stencilBuffer = options.stencilBuffer;
  7144. /**
  7145. * Whether to resolve the depth buffer or not.
  7146. *
  7147. * @type {boolean}
  7148. * @default true
  7149. */
  7150. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7151. /**
  7152. * Whether to resolve the stencil buffer or not.
  7153. *
  7154. * @type {boolean}
  7155. * @default true
  7156. */
  7157. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7158. this._depthTexture = null;
  7159. this.depthTexture = options.depthTexture;
  7160. /**
  7161. * The number of MSAA samples.
  7162. *
  7163. * A value of `0` disables MSAA.
  7164. *
  7165. * @type {number}
  7166. * @default 0
  7167. */
  7168. this.samples = options.samples;
  7169. /**
  7170. * Whether to this target is used in multiview rendering.
  7171. *
  7172. * @type {boolean}
  7173. * @default false
  7174. */
  7175. this.multiview = options.multiview;
  7176. /**
  7177. * Whether to create the depth texture as an array texture for per-layer depth testing.
  7178. * This is separate from multiview so layered render targets can use array depth without
  7179. * the multiview extension.
  7180. *
  7181. * @type {boolean}
  7182. * @default false
  7183. */
  7184. this.useArrayDepthTexture = options.useArrayDepthTexture;
  7185. }
  7186. _setTextureOptions( options = {} ) {
  7187. const values = {
  7188. minFilter: LinearFilter,
  7189. generateMipmaps: false,
  7190. flipY: false,
  7191. internalFormat: null
  7192. };
  7193. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7194. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7195. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7196. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7197. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7198. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7199. if ( options.format !== undefined ) values.format = options.format;
  7200. if ( options.type !== undefined ) values.type = options.type;
  7201. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7202. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7203. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7204. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7205. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7206. for ( let i = 0; i < this.textures.length; i ++ ) {
  7207. const texture = this.textures[ i ];
  7208. texture.setValues( values );
  7209. }
  7210. }
  7211. /**
  7212. * The texture representing the default color attachment.
  7213. *
  7214. * @type {Texture}
  7215. */
  7216. get texture() {
  7217. return this.textures[ 0 ];
  7218. }
  7219. set texture( value ) {
  7220. this.textures[ 0 ] = value;
  7221. }
  7222. set depthTexture( current ) {
  7223. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7224. if ( current !== null ) current.renderTarget = this;
  7225. this._depthTexture = current;
  7226. }
  7227. /**
  7228. * Instead of saving the depth in a renderbuffer, a texture
  7229. * can be used instead which is useful for further processing
  7230. * e.g. in context of post-processing.
  7231. *
  7232. * @type {?DepthTexture}
  7233. * @default null
  7234. */
  7235. get depthTexture() {
  7236. return this._depthTexture;
  7237. }
  7238. /**
  7239. * Sets the size of this render target.
  7240. *
  7241. * @param {number} width - The width.
  7242. * @param {number} height - The height.
  7243. * @param {number} [depth=1] - The depth.
  7244. */
  7245. setSize( width, height, depth = 1 ) {
  7246. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7247. this.width = width;
  7248. this.height = height;
  7249. this.depth = depth;
  7250. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7251. this.textures[ i ].image.width = width;
  7252. this.textures[ i ].image.height = height;
  7253. this.textures[ i ].image.depth = depth;
  7254. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7255. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7256. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7257. // both are evaluated on each call?
  7258. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7259. }
  7260. }
  7261. this.dispose();
  7262. }
  7263. this.viewport.set( 0, 0, width, height );
  7264. this.scissor.set( 0, 0, width, height );
  7265. }
  7266. /**
  7267. * Returns a new render target with copied values from this instance.
  7268. *
  7269. * @return {RenderTarget} A clone of this instance.
  7270. */
  7271. clone() {
  7272. return new this.constructor().copy( this );
  7273. }
  7274. /**
  7275. * Copies the settings of the given render target. This is a structural copy so
  7276. * no resources are shared between render targets after the copy. That includes
  7277. * all MRT textures and the depth texture.
  7278. *
  7279. * @param {RenderTarget} source - The render target to copy.
  7280. * @return {RenderTarget} A reference to this instance.
  7281. */
  7282. copy( source ) {
  7283. this.width = source.width;
  7284. this.height = source.height;
  7285. this.depth = source.depth;
  7286. this.scissor.copy( source.scissor );
  7287. this.scissorTest = source.scissorTest;
  7288. this.viewport.copy( source.viewport );
  7289. this.textures.length = 0;
  7290. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7291. this.textures[ i ] = source.textures[ i ].clone();
  7292. this.textures[ i ].isRenderTargetTexture = true;
  7293. this.textures[ i ].renderTarget = this;
  7294. // ensure image object is not shared, see #20328
  7295. const image = Object.assign( {}, source.textures[ i ].image );
  7296. this.textures[ i ].source = new Source( image );
  7297. }
  7298. this.depthBuffer = source.depthBuffer;
  7299. this.stencilBuffer = source.stencilBuffer;
  7300. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7301. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7302. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7303. this.samples = source.samples;
  7304. this.multiview = source.multiview;
  7305. this.useArrayDepthTexture = source.useArrayDepthTexture;
  7306. return this;
  7307. }
  7308. /**
  7309. * Frees the GPU-related resources allocated by this instance. Call this
  7310. * method whenever this instance is no longer used in your app.
  7311. *
  7312. * @fires RenderTarget#dispose
  7313. */
  7314. dispose() {
  7315. this.dispatchEvent( { type: 'dispose' } );
  7316. }
  7317. }
  7318. /**
  7319. * A render target used in context of {@link WebGLRenderer}.
  7320. *
  7321. * @augments RenderTarget
  7322. */
  7323. class WebGLRenderTarget extends RenderTarget {
  7324. /**
  7325. * Constructs a new 3D render target.
  7326. *
  7327. * @param {number} [width=1] - The width of the render target.
  7328. * @param {number} [height=1] - The height of the render target.
  7329. * @param {RenderTarget~Options} [options] - The configuration object.
  7330. */
  7331. constructor( width = 1, height = 1, options = {} ) {
  7332. super( width, height, options );
  7333. /**
  7334. * This flag can be used for type testing.
  7335. *
  7336. * @type {boolean}
  7337. * @readonly
  7338. * @default true
  7339. */
  7340. this.isWebGLRenderTarget = true;
  7341. }
  7342. }
  7343. /**
  7344. * Creates an array of textures directly from raw buffer data.
  7345. *
  7346. * @augments Texture
  7347. */
  7348. class DataArrayTexture extends Texture {
  7349. /**
  7350. * Constructs a new data array texture.
  7351. *
  7352. * @param {?TypedArray} [data=null] - The buffer data.
  7353. * @param {number} [width=1] - The width of the texture.
  7354. * @param {number} [height=1] - The height of the texture.
  7355. * @param {number} [depth=1] - The depth of the texture.
  7356. */
  7357. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7358. super( null );
  7359. /**
  7360. * This flag can be used for type testing.
  7361. *
  7362. * @type {boolean}
  7363. * @readonly
  7364. * @default true
  7365. */
  7366. this.isDataArrayTexture = true;
  7367. /**
  7368. * The image definition of a data texture.
  7369. *
  7370. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7371. */
  7372. this.image = { data, width, height, depth };
  7373. /**
  7374. * How the texture is sampled when a texel covers more than one pixel.
  7375. *
  7376. * Overwritten and set to `NearestFilter` by default.
  7377. *
  7378. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7379. * @default NearestFilter
  7380. */
  7381. this.magFilter = NearestFilter;
  7382. /**
  7383. * How the texture is sampled when a texel covers less than one pixel.
  7384. *
  7385. * Overwritten and set to `NearestFilter` by default.
  7386. *
  7387. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7388. * @default NearestFilter
  7389. */
  7390. this.minFilter = NearestFilter;
  7391. /**
  7392. * This defines how the texture is wrapped in the depth and corresponds to
  7393. * *W* in UVW mapping.
  7394. *
  7395. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7396. * @default ClampToEdgeWrapping
  7397. */
  7398. this.wrapR = ClampToEdgeWrapping;
  7399. /**
  7400. * Whether to generate mipmaps (if possible) for a texture.
  7401. *
  7402. * Overwritten and set to `false` by default.
  7403. *
  7404. * @type {boolean}
  7405. * @default false
  7406. */
  7407. this.generateMipmaps = false;
  7408. /**
  7409. * If set to `true`, the texture is flipped along the vertical axis when
  7410. * uploaded to the GPU.
  7411. *
  7412. * Overwritten and set to `false` by default.
  7413. *
  7414. * @type {boolean}
  7415. * @default false
  7416. */
  7417. this.flipY = false;
  7418. /**
  7419. * Specifies the alignment requirements for the start of each pixel row in memory.
  7420. *
  7421. * Overwritten and set to `1` by default.
  7422. *
  7423. * @type {boolean}
  7424. * @default 1
  7425. */
  7426. this.unpackAlignment = 1;
  7427. /**
  7428. * A set of all layers which need to be updated in the texture.
  7429. *
  7430. * @type {Set<number>}
  7431. */
  7432. this.layerUpdates = new Set();
  7433. }
  7434. /**
  7435. * Describes that a specific layer of the texture needs to be updated.
  7436. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7437. * entire data texture array is sent to the GPU. Marking specific
  7438. * layers will only transmit subsets of all mipmaps associated with a
  7439. * specific depth in the array which is often much more performant.
  7440. *
  7441. * @param {number} layerIndex - The layer index that should be updated.
  7442. */
  7443. addLayerUpdate( layerIndex ) {
  7444. this.layerUpdates.add( layerIndex );
  7445. }
  7446. /**
  7447. * Resets the layer updates registry.
  7448. */
  7449. clearLayerUpdates() {
  7450. this.layerUpdates.clear();
  7451. }
  7452. }
  7453. /**
  7454. * An array render target used in context of {@link WebGLRenderer}.
  7455. *
  7456. * @augments WebGLRenderTarget
  7457. */
  7458. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7459. /**
  7460. * Constructs a new array render target.
  7461. *
  7462. * @param {number} [width=1] - The width of the render target.
  7463. * @param {number} [height=1] - The height of the render target.
  7464. * @param {number} [depth=1] - The height of the render target.
  7465. * @param {RenderTarget~Options} [options] - The configuration object.
  7466. */
  7467. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7468. super( width, height, options );
  7469. /**
  7470. * This flag can be used for type testing.
  7471. *
  7472. * @type {boolean}
  7473. * @readonly
  7474. * @default true
  7475. */
  7476. this.isWebGLArrayRenderTarget = true;
  7477. this.depth = depth;
  7478. /**
  7479. * Overwritten with a different texture type.
  7480. *
  7481. * @type {DataArrayTexture}
  7482. */
  7483. this.texture = new DataArrayTexture( null, width, height, depth );
  7484. this._setTextureOptions( options );
  7485. this.texture.isRenderTargetTexture = true;
  7486. }
  7487. }
  7488. /**
  7489. * Creates a three-dimensional texture from raw data, with parameters to
  7490. * divide it into width, height, and depth.
  7491. *
  7492. * @augments Texture
  7493. */
  7494. class Data3DTexture extends Texture {
  7495. /**
  7496. * Constructs a new data array texture.
  7497. *
  7498. * @param {?TypedArray} [data=null] - The buffer data.
  7499. * @param {number} [width=1] - The width of the texture.
  7500. * @param {number} [height=1] - The height of the texture.
  7501. * @param {number} [depth=1] - The depth of the texture.
  7502. */
  7503. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7504. // We're going to add .setXXX() methods for setting properties later.
  7505. // Users can still set in Data3DTexture directly.
  7506. //
  7507. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7508. // texture.anisotropy = 16;
  7509. //
  7510. // See #14839
  7511. super( null );
  7512. /**
  7513. * This flag can be used for type testing.
  7514. *
  7515. * @type {boolean}
  7516. * @readonly
  7517. * @default true
  7518. */
  7519. this.isData3DTexture = true;
  7520. /**
  7521. * The image definition of a data texture.
  7522. *
  7523. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7524. */
  7525. this.image = { data, width, height, depth };
  7526. /**
  7527. * How the texture is sampled when a texel covers more than one pixel.
  7528. *
  7529. * Overwritten and set to `NearestFilter` by default.
  7530. *
  7531. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7532. * @default NearestFilter
  7533. */
  7534. this.magFilter = NearestFilter;
  7535. /**
  7536. * How the texture is sampled when a texel covers less than one pixel.
  7537. *
  7538. * Overwritten and set to `NearestFilter` by default.
  7539. *
  7540. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7541. * @default NearestFilter
  7542. */
  7543. this.minFilter = NearestFilter;
  7544. /**
  7545. * This defines how the texture is wrapped in the depth and corresponds to
  7546. * *W* in UVW mapping.
  7547. *
  7548. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7549. * @default ClampToEdgeWrapping
  7550. */
  7551. this.wrapR = ClampToEdgeWrapping;
  7552. /**
  7553. * Whether to generate mipmaps (if possible) for a texture.
  7554. *
  7555. * Overwritten and set to `false` by default.
  7556. *
  7557. * @type {boolean}
  7558. * @default false
  7559. */
  7560. this.generateMipmaps = false;
  7561. /**
  7562. * If set to `true`, the texture is flipped along the vertical axis when
  7563. * uploaded to the GPU.
  7564. *
  7565. * Overwritten and set to `false` by default.
  7566. *
  7567. * @type {boolean}
  7568. * @default false
  7569. */
  7570. this.flipY = false;
  7571. /**
  7572. * Specifies the alignment requirements for the start of each pixel row in memory.
  7573. *
  7574. * Overwritten and set to `1` by default.
  7575. *
  7576. * @type {boolean}
  7577. * @default 1
  7578. */
  7579. this.unpackAlignment = 1;
  7580. }
  7581. }
  7582. /**
  7583. * A 3D render target used in context of {@link WebGLRenderer}.
  7584. *
  7585. * @augments WebGLRenderTarget
  7586. */
  7587. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7588. /**
  7589. * Constructs a new 3D render target.
  7590. *
  7591. * @param {number} [width=1] - The width of the render target.
  7592. * @param {number} [height=1] - The height of the render target.
  7593. * @param {number} [depth=1] - The height of the render target.
  7594. * @param {RenderTarget~Options} [options] - The configuration object.
  7595. */
  7596. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7597. super( width, height, options );
  7598. /**
  7599. * This flag can be used for type testing.
  7600. *
  7601. * @type {boolean}
  7602. * @readonly
  7603. * @default true
  7604. */
  7605. this.isWebGL3DRenderTarget = true;
  7606. this.depth = depth;
  7607. /**
  7608. * Overwritten with a different texture type.
  7609. *
  7610. * @type {Data3DTexture}
  7611. */
  7612. this.texture = new Data3DTexture( null, width, height, depth );
  7613. this._setTextureOptions( options );
  7614. this.texture.isRenderTargetTexture = true;
  7615. }
  7616. }
  7617. /**
  7618. * Represents a 4x4 matrix.
  7619. *
  7620. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  7621. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  7622. *
  7623. * This allows a 3D vector representing a point in 3D space to undergo
  7624. * transformations such as translation, rotation, shear, scale, reflection,
  7625. * orthogonal or perspective projection and so on, by being multiplied by the
  7626. * matrix. This is known as `applying` the matrix to the vector.
  7627. *
  7628. * A Note on Row-Major and Column-Major Ordering:
  7629. *
  7630. * The constructor and {@link Matrix3#set} method take arguments in
  7631. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  7632. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  7633. * This means that calling:
  7634. * ```js
  7635. * const m = new THREE.Matrix4();
  7636. * m.set( 11, 12, 13, 14,
  7637. * 21, 22, 23, 24,
  7638. * 31, 32, 33, 34,
  7639. * 41, 42, 43, 44 );
  7640. * ```
  7641. * will result in the elements array containing:
  7642. * ```js
  7643. * m.elements = [ 11, 21, 31, 41,
  7644. * 12, 22, 32, 42,
  7645. * 13, 23, 33, 43,
  7646. * 14, 24, 34, 44 ];
  7647. * ```
  7648. * and internally all calculations are performed using column-major ordering.
  7649. * However, as the actual ordering makes no difference mathematically and
  7650. * most people are used to thinking about matrices in row-major order, the
  7651. * three.js documentation shows matrices in row-major order. Just bear in
  7652. * mind that if you are reading the source code, you'll have to take the
  7653. * transpose of any matrices outlined here to make sense of the calculations.
  7654. */
  7655. class Matrix4 {
  7656. static {
  7657. /**
  7658. * This flag can be used for type testing.
  7659. *
  7660. * @type {boolean}
  7661. * @readonly
  7662. * @default true
  7663. */
  7664. Matrix4.prototype.isMatrix4 = true;
  7665. }
  7666. /**
  7667. * Constructs a new 4x4 matrix. The arguments are supposed to be
  7668. * in row-major order. If no arguments are provided, the constructor
  7669. * initializes the matrix as an identity matrix.
  7670. *
  7671. * @param {number} [n11] - 1-1 matrix element.
  7672. * @param {number} [n12] - 1-2 matrix element.
  7673. * @param {number} [n13] - 1-3 matrix element.
  7674. * @param {number} [n14] - 1-4 matrix element.
  7675. * @param {number} [n21] - 2-1 matrix element.
  7676. * @param {number} [n22] - 2-2 matrix element.
  7677. * @param {number} [n23] - 2-3 matrix element.
  7678. * @param {number} [n24] - 2-4 matrix element.
  7679. * @param {number} [n31] - 3-1 matrix element.
  7680. * @param {number} [n32] - 3-2 matrix element.
  7681. * @param {number} [n33] - 3-3 matrix element.
  7682. * @param {number} [n34] - 3-4 matrix element.
  7683. * @param {number} [n41] - 4-1 matrix element.
  7684. * @param {number} [n42] - 4-2 matrix element.
  7685. * @param {number} [n43] - 4-3 matrix element.
  7686. * @param {number} [n44] - 4-4 matrix element.
  7687. */
  7688. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7689. /**
  7690. * A column-major list of matrix values.
  7691. *
  7692. * @type {Array<number>}
  7693. */
  7694. this.elements = [
  7695. 1, 0, 0, 0,
  7696. 0, 1, 0, 0,
  7697. 0, 0, 1, 0,
  7698. 0, 0, 0, 1
  7699. ];
  7700. if ( n11 !== undefined ) {
  7701. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  7702. }
  7703. }
  7704. /**
  7705. * Sets the elements of the matrix.The arguments are supposed to be
  7706. * in row-major order.
  7707. *
  7708. * @param {number} [n11] - 1-1 matrix element.
  7709. * @param {number} [n12] - 1-2 matrix element.
  7710. * @param {number} [n13] - 1-3 matrix element.
  7711. * @param {number} [n14] - 1-4 matrix element.
  7712. * @param {number} [n21] - 2-1 matrix element.
  7713. * @param {number} [n22] - 2-2 matrix element.
  7714. * @param {number} [n23] - 2-3 matrix element.
  7715. * @param {number} [n24] - 2-4 matrix element.
  7716. * @param {number} [n31] - 3-1 matrix element.
  7717. * @param {number} [n32] - 3-2 matrix element.
  7718. * @param {number} [n33] - 3-3 matrix element.
  7719. * @param {number} [n34] - 3-4 matrix element.
  7720. * @param {number} [n41] - 4-1 matrix element.
  7721. * @param {number} [n42] - 4-2 matrix element.
  7722. * @param {number} [n43] - 4-3 matrix element.
  7723. * @param {number} [n44] - 4-4 matrix element.
  7724. * @return {Matrix4} A reference to this matrix.
  7725. */
  7726. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  7727. const te = this.elements;
  7728. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  7729. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  7730. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  7731. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  7732. return this;
  7733. }
  7734. /**
  7735. * Sets this matrix to the 4x4 identity matrix.
  7736. *
  7737. * @return {Matrix4} A reference to this matrix.
  7738. */
  7739. identity() {
  7740. this.set(
  7741. 1, 0, 0, 0,
  7742. 0, 1, 0, 0,
  7743. 0, 0, 1, 0,
  7744. 0, 0, 0, 1
  7745. );
  7746. return this;
  7747. }
  7748. /**
  7749. * Returns a matrix with copied values from this instance.
  7750. *
  7751. * @return {Matrix4} A clone of this instance.
  7752. */
  7753. clone() {
  7754. return new Matrix4().fromArray( this.elements );
  7755. }
  7756. /**
  7757. * Copies the values of the given matrix to this instance.
  7758. *
  7759. * @param {Matrix4} m - The matrix to copy.
  7760. * @return {Matrix4} A reference to this matrix.
  7761. */
  7762. copy( m ) {
  7763. const te = this.elements;
  7764. const me = m.elements;
  7765. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  7766. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  7767. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  7768. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  7769. return this;
  7770. }
  7771. /**
  7772. * Copies the translation component of the given matrix
  7773. * into this matrix's translation component.
  7774. *
  7775. * @param {Matrix4} m - The matrix to copy the translation component.
  7776. * @return {Matrix4} A reference to this matrix.
  7777. */
  7778. copyPosition( m ) {
  7779. const te = this.elements, me = m.elements;
  7780. te[ 12 ] = me[ 12 ];
  7781. te[ 13 ] = me[ 13 ];
  7782. te[ 14 ] = me[ 14 ];
  7783. return this;
  7784. }
  7785. /**
  7786. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  7787. *
  7788. * @param {Matrix3} m - The 3x3 matrix.
  7789. * @return {Matrix4} A reference to this matrix.
  7790. */
  7791. setFromMatrix3( m ) {
  7792. const me = m.elements;
  7793. this.set(
  7794. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  7795. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  7796. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  7797. 0, 0, 0, 1
  7798. );
  7799. return this;
  7800. }
  7801. /**
  7802. * Extracts the basis of this matrix into the three axis vectors provided.
  7803. *
  7804. * @param {Vector3} xAxis - The basis's x axis.
  7805. * @param {Vector3} yAxis - The basis's y axis.
  7806. * @param {Vector3} zAxis - The basis's z axis.
  7807. * @return {Matrix4} A reference to this matrix.
  7808. */
  7809. extractBasis( xAxis, yAxis, zAxis ) {
  7810. if ( this.determinant() === 0 ) {
  7811. xAxis.set( 1, 0, 0 );
  7812. yAxis.set( 0, 1, 0 );
  7813. zAxis.set( 0, 0, 1 );
  7814. return this;
  7815. }
  7816. xAxis.setFromMatrixColumn( this, 0 );
  7817. yAxis.setFromMatrixColumn( this, 1 );
  7818. zAxis.setFromMatrixColumn( this, 2 );
  7819. return this;
  7820. }
  7821. /**
  7822. * Sets the given basis vectors to this matrix.
  7823. *
  7824. * @param {Vector3} xAxis - The basis's x axis.
  7825. * @param {Vector3} yAxis - The basis's y axis.
  7826. * @param {Vector3} zAxis - The basis's z axis.
  7827. * @return {Matrix4} A reference to this matrix.
  7828. */
  7829. makeBasis( xAxis, yAxis, zAxis ) {
  7830. this.set(
  7831. xAxis.x, yAxis.x, zAxis.x, 0,
  7832. xAxis.y, yAxis.y, zAxis.y, 0,
  7833. xAxis.z, yAxis.z, zAxis.z, 0,
  7834. 0, 0, 0, 1
  7835. );
  7836. return this;
  7837. }
  7838. /**
  7839. * Extracts the rotation component of the given matrix
  7840. * into this matrix's rotation component.
  7841. *
  7842. * Note: This method does not support reflection matrices.
  7843. *
  7844. * @param {Matrix4} m - The matrix.
  7845. * @return {Matrix4} A reference to this matrix.
  7846. */
  7847. extractRotation( m ) {
  7848. if ( m.determinant() === 0 ) {
  7849. return this.identity();
  7850. }
  7851. const te = this.elements;
  7852. const me = m.elements;
  7853. const scaleX = 1 / _v1$7.setFromMatrixColumn( m, 0 ).length();
  7854. const scaleY = 1 / _v1$7.setFromMatrixColumn( m, 1 ).length();
  7855. const scaleZ = 1 / _v1$7.setFromMatrixColumn( m, 2 ).length();
  7856. te[ 0 ] = me[ 0 ] * scaleX;
  7857. te[ 1 ] = me[ 1 ] * scaleX;
  7858. te[ 2 ] = me[ 2 ] * scaleX;
  7859. te[ 3 ] = 0;
  7860. te[ 4 ] = me[ 4 ] * scaleY;
  7861. te[ 5 ] = me[ 5 ] * scaleY;
  7862. te[ 6 ] = me[ 6 ] * scaleY;
  7863. te[ 7 ] = 0;
  7864. te[ 8 ] = me[ 8 ] * scaleZ;
  7865. te[ 9 ] = me[ 9 ] * scaleZ;
  7866. te[ 10 ] = me[ 10 ] * scaleZ;
  7867. te[ 11 ] = 0;
  7868. te[ 12 ] = 0;
  7869. te[ 13 ] = 0;
  7870. te[ 14 ] = 0;
  7871. te[ 15 ] = 1;
  7872. return this;
  7873. }
  7874. /**
  7875. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  7876. * the rotation specified by the given Euler angles. The rest of
  7877. * the matrix is set to the identity. Depending on the {@link Euler#order},
  7878. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  7879. * for a complete list.
  7880. *
  7881. * @param {Euler} euler - The Euler angles.
  7882. * @return {Matrix4} A reference to this matrix.
  7883. */
  7884. makeRotationFromEuler( euler ) {
  7885. const te = this.elements;
  7886. const x = euler.x, y = euler.y, z = euler.z;
  7887. const a = Math.cos( x ), b = Math.sin( x );
  7888. const c = Math.cos( y ), d = Math.sin( y );
  7889. const e = Math.cos( z ), f = Math.sin( z );
  7890. if ( euler.order === 'XYZ' ) {
  7891. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7892. te[ 0 ] = c * e;
  7893. te[ 4 ] = - c * f;
  7894. te[ 8 ] = d;
  7895. te[ 1 ] = af + be * d;
  7896. te[ 5 ] = ae - bf * d;
  7897. te[ 9 ] = - b * c;
  7898. te[ 2 ] = bf - ae * d;
  7899. te[ 6 ] = be + af * d;
  7900. te[ 10 ] = a * c;
  7901. } else if ( euler.order === 'YXZ' ) {
  7902. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7903. te[ 0 ] = ce + df * b;
  7904. te[ 4 ] = de * b - cf;
  7905. te[ 8 ] = a * d;
  7906. te[ 1 ] = a * f;
  7907. te[ 5 ] = a * e;
  7908. te[ 9 ] = - b;
  7909. te[ 2 ] = cf * b - de;
  7910. te[ 6 ] = df + ce * b;
  7911. te[ 10 ] = a * c;
  7912. } else if ( euler.order === 'ZXY' ) {
  7913. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  7914. te[ 0 ] = ce - df * b;
  7915. te[ 4 ] = - a * f;
  7916. te[ 8 ] = de + cf * b;
  7917. te[ 1 ] = cf + de * b;
  7918. te[ 5 ] = a * e;
  7919. te[ 9 ] = df - ce * b;
  7920. te[ 2 ] = - a * d;
  7921. te[ 6 ] = b;
  7922. te[ 10 ] = a * c;
  7923. } else if ( euler.order === 'ZYX' ) {
  7924. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  7925. te[ 0 ] = c * e;
  7926. te[ 4 ] = be * d - af;
  7927. te[ 8 ] = ae * d + bf;
  7928. te[ 1 ] = c * f;
  7929. te[ 5 ] = bf * d + ae;
  7930. te[ 9 ] = af * d - be;
  7931. te[ 2 ] = - d;
  7932. te[ 6 ] = b * c;
  7933. te[ 10 ] = a * c;
  7934. } else if ( euler.order === 'YZX' ) {
  7935. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7936. te[ 0 ] = c * e;
  7937. te[ 4 ] = bd - ac * f;
  7938. te[ 8 ] = bc * f + ad;
  7939. te[ 1 ] = f;
  7940. te[ 5 ] = a * e;
  7941. te[ 9 ] = - b * e;
  7942. te[ 2 ] = - d * e;
  7943. te[ 6 ] = ad * f + bc;
  7944. te[ 10 ] = ac - bd * f;
  7945. } else if ( euler.order === 'XZY' ) {
  7946. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  7947. te[ 0 ] = c * e;
  7948. te[ 4 ] = - f;
  7949. te[ 8 ] = d * e;
  7950. te[ 1 ] = ac * f + bd;
  7951. te[ 5 ] = a * e;
  7952. te[ 9 ] = ad * f - bc;
  7953. te[ 2 ] = bc * f - ad;
  7954. te[ 6 ] = b * e;
  7955. te[ 10 ] = bd * f + ac;
  7956. }
  7957. // bottom row
  7958. te[ 3 ] = 0;
  7959. te[ 7 ] = 0;
  7960. te[ 11 ] = 0;
  7961. // last column
  7962. te[ 12 ] = 0;
  7963. te[ 13 ] = 0;
  7964. te[ 14 ] = 0;
  7965. te[ 15 ] = 1;
  7966. return this;
  7967. }
  7968. /**
  7969. * Sets the rotation component of this matrix to the rotation specified by
  7970. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  7971. * The rest of the matrix is set to the identity.
  7972. *
  7973. * @param {Quaternion} q - The Quaternion.
  7974. * @return {Matrix4} A reference to this matrix.
  7975. */
  7976. makeRotationFromQuaternion( q ) {
  7977. return this.compose( _zero, q, _one );
  7978. }
  7979. /**
  7980. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  7981. * `target`, and oriented by the up-direction.
  7982. *
  7983. * @param {Vector3} eye - The eye vector.
  7984. * @param {Vector3} target - The target vector.
  7985. * @param {Vector3} up - The up vector.
  7986. * @return {Matrix4} A reference to this matrix.
  7987. */
  7988. lookAt( eye, target, up ) {
  7989. const te = this.elements;
  7990. _z.subVectors( eye, target );
  7991. if ( _z.lengthSq() === 0 ) {
  7992. // eye and target are in the same position
  7993. _z.z = 1;
  7994. }
  7995. _z.normalize();
  7996. _x.crossVectors( up, _z );
  7997. if ( _x.lengthSq() === 0 ) {
  7998. // up and z are parallel
  7999. if ( Math.abs( up.z ) === 1 ) {
  8000. _z.x += 0.0001;
  8001. } else {
  8002. _z.z += 0.0001;
  8003. }
  8004. _z.normalize();
  8005. _x.crossVectors( up, _z );
  8006. }
  8007. _x.normalize();
  8008. _y.crossVectors( _z, _x );
  8009. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8010. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8011. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8012. return this;
  8013. }
  8014. /**
  8015. * Post-multiplies this matrix by the given 4x4 matrix.
  8016. *
  8017. * @param {Matrix4} m - The matrix to multiply with.
  8018. * @return {Matrix4} A reference to this matrix.
  8019. */
  8020. multiply( m ) {
  8021. return this.multiplyMatrices( this, m );
  8022. }
  8023. /**
  8024. * Pre-multiplies this matrix by the given 4x4 matrix.
  8025. *
  8026. * @param {Matrix4} m - The matrix to multiply with.
  8027. * @return {Matrix4} A reference to this matrix.
  8028. */
  8029. premultiply( m ) {
  8030. return this.multiplyMatrices( m, this );
  8031. }
  8032. /**
  8033. * Multiples the given 4x4 matrices and stores the result
  8034. * in this matrix.
  8035. *
  8036. * @param {Matrix4} a - The first matrix.
  8037. * @param {Matrix4} b - The second matrix.
  8038. * @return {Matrix4} A reference to this matrix.
  8039. */
  8040. multiplyMatrices( a, b ) {
  8041. const ae = a.elements;
  8042. const be = b.elements;
  8043. const te = this.elements;
  8044. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  8045. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  8046. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  8047. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  8048. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  8049. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  8050. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  8051. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  8052. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  8053. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  8054. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  8055. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  8056. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  8057. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  8058. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  8059. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  8060. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  8061. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  8062. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  8063. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  8064. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  8065. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  8066. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  8067. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  8068. return this;
  8069. }
  8070. /**
  8071. * Multiplies every component of the matrix by the given scalar.
  8072. *
  8073. * @param {number} s - The scalar.
  8074. * @return {Matrix4} A reference to this matrix.
  8075. */
  8076. multiplyScalar( s ) {
  8077. const te = this.elements;
  8078. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  8079. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  8080. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  8081. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  8082. return this;
  8083. }
  8084. /**
  8085. * Computes and returns the determinant of this matrix.
  8086. *
  8087. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  8088. *
  8089. * @return {number} The determinant.
  8090. */
  8091. determinant() {
  8092. const te = this.elements;
  8093. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  8094. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  8095. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  8096. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  8097. const t11 = n23 * n34 - n24 * n33;
  8098. const t12 = n22 * n34 - n24 * n32;
  8099. const t13 = n22 * n33 - n23 * n32;
  8100. const t21 = n21 * n34 - n24 * n31;
  8101. const t22 = n21 * n33 - n23 * n31;
  8102. const t23 = n21 * n32 - n22 * n31;
  8103. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  8104. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  8105. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  8106. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  8107. }
  8108. /**
  8109. * Transposes this matrix in place.
  8110. *
  8111. * @return {Matrix4} A reference to this matrix.
  8112. */
  8113. transpose() {
  8114. const te = this.elements;
  8115. let tmp;
  8116. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  8117. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  8118. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  8119. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  8120. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  8121. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  8122. return this;
  8123. }
  8124. /**
  8125. * Sets the position component for this matrix from the given vector,
  8126. * without affecting the rest of the matrix.
  8127. *
  8128. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  8129. * @param {number} y - The y component of the vector.
  8130. * @param {number} z - The z component of the vector.
  8131. * @return {Matrix4} A reference to this matrix.
  8132. */
  8133. setPosition( x, y, z ) {
  8134. const te = this.elements;
  8135. if ( x.isVector3 ) {
  8136. te[ 12 ] = x.x;
  8137. te[ 13 ] = x.y;
  8138. te[ 14 ] = x.z;
  8139. } else {
  8140. te[ 12 ] = x;
  8141. te[ 13 ] = y;
  8142. te[ 14 ] = z;
  8143. }
  8144. return this;
  8145. }
  8146. /**
  8147. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  8148. * You can not invert with a determinant of zero. If you attempt this, the method produces
  8149. * a zero matrix instead.
  8150. *
  8151. * @return {Matrix4} A reference to this matrix.
  8152. */
  8153. invert() {
  8154. // based on https://github.com/toji/gl-matrix
  8155. const te = this.elements,
  8156. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  8157. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  8158. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  8159. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  8160. t1 = n11 * n22 - n21 * n12,
  8161. t2 = n11 * n32 - n31 * n12,
  8162. t3 = n11 * n42 - n41 * n12,
  8163. t4 = n21 * n32 - n31 * n22,
  8164. t5 = n21 * n42 - n41 * n22,
  8165. t6 = n31 * n42 - n41 * n32,
  8166. t7 = n13 * n24 - n23 * n14,
  8167. t8 = n13 * n34 - n33 * n14,
  8168. t9 = n13 * n44 - n43 * n14,
  8169. t10 = n23 * n34 - n33 * n24,
  8170. t11 = n23 * n44 - n43 * n24,
  8171. t12 = n33 * n44 - n43 * n34;
  8172. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  8173. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  8174. const detInv = 1 / det;
  8175. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  8176. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  8177. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  8178. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  8179. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  8180. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  8181. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  8182. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  8183. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  8184. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  8185. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  8186. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  8187. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  8188. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  8189. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  8190. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  8191. return this;
  8192. }
  8193. /**
  8194. * Multiplies the columns of this matrix by the given vector.
  8195. *
  8196. * @param {Vector3} v - The scale vector.
  8197. * @return {Matrix4} A reference to this matrix.
  8198. */
  8199. scale( v ) {
  8200. const te = this.elements;
  8201. const x = v.x, y = v.y, z = v.z;
  8202. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  8203. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  8204. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  8205. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  8206. return this;
  8207. }
  8208. /**
  8209. * Gets the maximum scale value of the three axes.
  8210. *
  8211. * @return {number} The maximum scale.
  8212. */
  8213. getMaxScaleOnAxis() {
  8214. const te = this.elements;
  8215. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  8216. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  8217. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  8218. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  8219. }
  8220. /**
  8221. * Sets this matrix as a translation transform from the given vector.
  8222. *
  8223. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  8224. * @param {number} y - The amount to translate in the Y axis.
  8225. * @param {number} z - The amount to translate in the z axis.
  8226. * @return {Matrix4} A reference to this matrix.
  8227. */
  8228. makeTranslation( x, y, z ) {
  8229. if ( x.isVector3 ) {
  8230. this.set(
  8231. 1, 0, 0, x.x,
  8232. 0, 1, 0, x.y,
  8233. 0, 0, 1, x.z,
  8234. 0, 0, 0, 1
  8235. );
  8236. } else {
  8237. this.set(
  8238. 1, 0, 0, x,
  8239. 0, 1, 0, y,
  8240. 0, 0, 1, z,
  8241. 0, 0, 0, 1
  8242. );
  8243. }
  8244. return this;
  8245. }
  8246. /**
  8247. * Sets this matrix as a rotational transformation around the X axis by
  8248. * the given angle.
  8249. *
  8250. * @param {number} theta - The rotation in radians.
  8251. * @return {Matrix4} A reference to this matrix.
  8252. */
  8253. makeRotationX( theta ) {
  8254. const c = Math.cos( theta ), s = Math.sin( theta );
  8255. this.set(
  8256. 1, 0, 0, 0,
  8257. 0, c, - s, 0,
  8258. 0, s, c, 0,
  8259. 0, 0, 0, 1
  8260. );
  8261. return this;
  8262. }
  8263. /**
  8264. * Sets this matrix as a rotational transformation around the Y axis by
  8265. * the given angle.
  8266. *
  8267. * @param {number} theta - The rotation in radians.
  8268. * @return {Matrix4} A reference to this matrix.
  8269. */
  8270. makeRotationY( theta ) {
  8271. const c = Math.cos( theta ), s = Math.sin( theta );
  8272. this.set(
  8273. c, 0, s, 0,
  8274. 0, 1, 0, 0,
  8275. - s, 0, c, 0,
  8276. 0, 0, 0, 1
  8277. );
  8278. return this;
  8279. }
  8280. /**
  8281. * Sets this matrix as a rotational transformation around the Z axis by
  8282. * the given angle.
  8283. *
  8284. * @param {number} theta - The rotation in radians.
  8285. * @return {Matrix4} A reference to this matrix.
  8286. */
  8287. makeRotationZ( theta ) {
  8288. const c = Math.cos( theta ), s = Math.sin( theta );
  8289. this.set(
  8290. c, - s, 0, 0,
  8291. s, c, 0, 0,
  8292. 0, 0, 1, 0,
  8293. 0, 0, 0, 1
  8294. );
  8295. return this;
  8296. }
  8297. /**
  8298. * Sets this matrix as a rotational transformation around the given axis by
  8299. * the given angle.
  8300. *
  8301. * This is a somewhat controversial but mathematically sound alternative to
  8302. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  8303. *
  8304. * @param {Vector3} axis - The normalized rotation axis.
  8305. * @param {number} angle - The rotation in radians.
  8306. * @return {Matrix4} A reference to this matrix.
  8307. */
  8308. makeRotationAxis( axis, angle ) {
  8309. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  8310. const c = Math.cos( angle );
  8311. const s = Math.sin( angle );
  8312. const t = 1 - c;
  8313. const x = axis.x, y = axis.y, z = axis.z;
  8314. const tx = t * x, ty = t * y;
  8315. this.set(
  8316. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  8317. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  8318. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  8319. 0, 0, 0, 1
  8320. );
  8321. return this;
  8322. }
  8323. /**
  8324. * Sets this matrix as a scale transformation.
  8325. *
  8326. * @param {number} x - The amount to scale in the X axis.
  8327. * @param {number} y - The amount to scale in the Y axis.
  8328. * @param {number} z - The amount to scale in the Z axis.
  8329. * @return {Matrix4} A reference to this matrix.
  8330. */
  8331. makeScale( x, y, z ) {
  8332. this.set(
  8333. x, 0, 0, 0,
  8334. 0, y, 0, 0,
  8335. 0, 0, z, 0,
  8336. 0, 0, 0, 1
  8337. );
  8338. return this;
  8339. }
  8340. /**
  8341. * Sets this matrix as a shear transformation.
  8342. *
  8343. * @param {number} xy - The amount to shear X by Y.
  8344. * @param {number} xz - The amount to shear X by Z.
  8345. * @param {number} yx - The amount to shear Y by X.
  8346. * @param {number} yz - The amount to shear Y by Z.
  8347. * @param {number} zx - The amount to shear Z by X.
  8348. * @param {number} zy - The amount to shear Z by Y.
  8349. * @return {Matrix4} A reference to this matrix.
  8350. */
  8351. makeShear( xy, xz, yx, yz, zx, zy ) {
  8352. this.set(
  8353. 1, yx, zx, 0,
  8354. xy, 1, zy, 0,
  8355. xz, yz, 1, 0,
  8356. 0, 0, 0, 1
  8357. );
  8358. return this;
  8359. }
  8360. /**
  8361. * Sets this matrix to the transformation composed of the given position,
  8362. * rotation (Quaternion) and scale.
  8363. *
  8364. * @param {Vector3} position - The position vector.
  8365. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8366. * @param {Vector3} scale - The scale vector.
  8367. * @return {Matrix4} A reference to this matrix.
  8368. */
  8369. compose( position, quaternion, scale ) {
  8370. const te = this.elements;
  8371. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  8372. const x2 = x + x, y2 = y + y, z2 = z + z;
  8373. const xx = x * x2, xy = x * y2, xz = x * z2;
  8374. const yy = y * y2, yz = y * z2, zz = z * z2;
  8375. const wx = w * x2, wy = w * y2, wz = w * z2;
  8376. const sx = scale.x, sy = scale.y, sz = scale.z;
  8377. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  8378. te[ 1 ] = ( xy + wz ) * sx;
  8379. te[ 2 ] = ( xz - wy ) * sx;
  8380. te[ 3 ] = 0;
  8381. te[ 4 ] = ( xy - wz ) * sy;
  8382. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  8383. te[ 6 ] = ( yz + wx ) * sy;
  8384. te[ 7 ] = 0;
  8385. te[ 8 ] = ( xz + wy ) * sz;
  8386. te[ 9 ] = ( yz - wx ) * sz;
  8387. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  8388. te[ 11 ] = 0;
  8389. te[ 12 ] = position.x;
  8390. te[ 13 ] = position.y;
  8391. te[ 14 ] = position.z;
  8392. te[ 15 ] = 1;
  8393. return this;
  8394. }
  8395. /**
  8396. * Decomposes this matrix into its position, rotation and scale components
  8397. * and provides the result in the given objects.
  8398. *
  8399. * Note: Not all matrices are decomposable in this way. For example, if an
  8400. * object has a non-uniformly scaled parent, then the object's world matrix
  8401. * may not be decomposable, and this method may not be appropriate.
  8402. *
  8403. * @param {Vector3} position - The position vector.
  8404. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  8405. * @param {Vector3} scale - The scale vector.
  8406. * @return {Matrix4} A reference to this matrix.
  8407. */
  8408. decompose( position, quaternion, scale ) {
  8409. const te = this.elements;
  8410. position.x = te[ 12 ];
  8411. position.y = te[ 13 ];
  8412. position.z = te[ 14 ];
  8413. const det = this.determinant();
  8414. if ( det === 0 ) {
  8415. scale.set( 1, 1, 1 );
  8416. quaternion.identity();
  8417. return this;
  8418. }
  8419. let sx = _v1$7.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  8420. const sy = _v1$7.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  8421. const sz = _v1$7.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  8422. // if determinant is negative, we need to invert one scale
  8423. if ( det < 0 ) sx = - sx;
  8424. // scale the rotation part
  8425. _m1$2.copy( this );
  8426. const invSX = 1 / sx;
  8427. const invSY = 1 / sy;
  8428. const invSZ = 1 / sz;
  8429. _m1$2.elements[ 0 ] *= invSX;
  8430. _m1$2.elements[ 1 ] *= invSX;
  8431. _m1$2.elements[ 2 ] *= invSX;
  8432. _m1$2.elements[ 4 ] *= invSY;
  8433. _m1$2.elements[ 5 ] *= invSY;
  8434. _m1$2.elements[ 6 ] *= invSY;
  8435. _m1$2.elements[ 8 ] *= invSZ;
  8436. _m1$2.elements[ 9 ] *= invSZ;
  8437. _m1$2.elements[ 10 ] *= invSZ;
  8438. quaternion.setFromRotationMatrix( _m1$2 );
  8439. scale.x = sx;
  8440. scale.y = sy;
  8441. scale.z = sz;
  8442. return this;
  8443. }
  8444. /**
  8445. * Creates a perspective projection matrix. This is used internally by
  8446. * {@link PerspectiveCamera#updateProjectionMatrix}.
  8447. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8448. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8449. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8450. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8451. * @param {number} near - The distance from the camera to the near plane.
  8452. * @param {number} far - The distance from the camera to the far plane.
  8453. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8454. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8455. * @return {Matrix4} A reference to this matrix.
  8456. */
  8457. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8458. const te = this.elements;
  8459. const x = 2 * near / ( right - left );
  8460. const y = 2 * near / ( top - bottom );
  8461. const a = ( right + left ) / ( right - left );
  8462. const b = ( top + bottom ) / ( top - bottom );
  8463. let c, d;
  8464. if ( reversedDepth ) {
  8465. c = near / ( far - near );
  8466. d = ( far * near ) / ( far - near );
  8467. } else {
  8468. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8469. c = - ( far + near ) / ( far - near );
  8470. d = ( -2 * far * near ) / ( far - near );
  8471. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8472. c = - far / ( far - near );
  8473. d = ( - far * near ) / ( far - near );
  8474. } else {
  8475. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  8476. }
  8477. }
  8478. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  8479. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  8480. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8481. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  8482. return this;
  8483. }
  8484. /**
  8485. * Creates a orthographic projection matrix. This is used internally by
  8486. * {@link OrthographicCamera#updateProjectionMatrix}.
  8487. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  8488. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  8489. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  8490. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  8491. * @param {number} near - The distance from the camera to the near plane.
  8492. * @param {number} far - The distance from the camera to the far plane.
  8493. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  8494. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  8495. * @return {Matrix4} A reference to this matrix.
  8496. */
  8497. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  8498. const te = this.elements;
  8499. const x = 2 / ( right - left );
  8500. const y = 2 / ( top - bottom );
  8501. const a = - ( right + left ) / ( right - left );
  8502. const b = - ( top + bottom ) / ( top - bottom );
  8503. let c, d;
  8504. if ( reversedDepth ) {
  8505. c = 1 / ( far - near );
  8506. d = far / ( far - near );
  8507. } else {
  8508. if ( coordinateSystem === WebGLCoordinateSystem ) {
  8509. c = -2 / ( far - near );
  8510. d = - ( far + near ) / ( far - near );
  8511. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  8512. c = -1 / ( far - near );
  8513. d = - near / ( far - near );
  8514. } else {
  8515. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  8516. }
  8517. }
  8518. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  8519. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  8520. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  8521. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  8522. return this;
  8523. }
  8524. /**
  8525. * Returns `true` if this matrix is equal with the given one.
  8526. *
  8527. * @param {Matrix4} matrix - The matrix to test for equality.
  8528. * @return {boolean} Whether this matrix is equal with the given one.
  8529. */
  8530. equals( matrix ) {
  8531. const te = this.elements;
  8532. const me = matrix.elements;
  8533. for ( let i = 0; i < 16; i ++ ) {
  8534. if ( te[ i ] !== me[ i ] ) return false;
  8535. }
  8536. return true;
  8537. }
  8538. /**
  8539. * Sets the elements of the matrix from the given array.
  8540. *
  8541. * @param {Array<number>} array - The matrix elements in column-major order.
  8542. * @param {number} [offset=0] - Index of the first element in the array.
  8543. * @return {Matrix4} A reference to this matrix.
  8544. */
  8545. fromArray( array, offset = 0 ) {
  8546. for ( let i = 0; i < 16; i ++ ) {
  8547. this.elements[ i ] = array[ i + offset ];
  8548. }
  8549. return this;
  8550. }
  8551. /**
  8552. * Writes the elements of this matrix to the given array. If no array is provided,
  8553. * the method returns a new instance.
  8554. *
  8555. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  8556. * @param {number} [offset=0] - Index of the first element in the array.
  8557. * @return {Array<number>} The matrix elements in column-major order.
  8558. */
  8559. toArray( array = [], offset = 0 ) {
  8560. const te = this.elements;
  8561. array[ offset ] = te[ 0 ];
  8562. array[ offset + 1 ] = te[ 1 ];
  8563. array[ offset + 2 ] = te[ 2 ];
  8564. array[ offset + 3 ] = te[ 3 ];
  8565. array[ offset + 4 ] = te[ 4 ];
  8566. array[ offset + 5 ] = te[ 5 ];
  8567. array[ offset + 6 ] = te[ 6 ];
  8568. array[ offset + 7 ] = te[ 7 ];
  8569. array[ offset + 8 ] = te[ 8 ];
  8570. array[ offset + 9 ] = te[ 9 ];
  8571. array[ offset + 10 ] = te[ 10 ];
  8572. array[ offset + 11 ] = te[ 11 ];
  8573. array[ offset + 12 ] = te[ 12 ];
  8574. array[ offset + 13 ] = te[ 13 ];
  8575. array[ offset + 14 ] = te[ 14 ];
  8576. array[ offset + 15 ] = te[ 15 ];
  8577. return array;
  8578. }
  8579. }
  8580. const _v1$7 = /*@__PURE__*/ new Vector3();
  8581. const _m1$2 = /*@__PURE__*/ new Matrix4();
  8582. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  8583. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  8584. const _x = /*@__PURE__*/ new Vector3();
  8585. const _y = /*@__PURE__*/ new Vector3();
  8586. const _z = /*@__PURE__*/ new Vector3();
  8587. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  8588. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  8589. /**
  8590. * A class representing Euler angles.
  8591. *
  8592. * Euler angles describe a rotational transformation by rotating an object on
  8593. * its various axes in specified amounts per axis, and a specified axis
  8594. * order.
  8595. *
  8596. * Iterating through an instance will yield its components (x, y, z,
  8597. * order) in the corresponding order.
  8598. *
  8599. * ```js
  8600. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  8601. * const b = new THREE.Vector3( 1, 0, 1 );
  8602. * b.applyEuler(a);
  8603. * ```
  8604. */
  8605. class Euler {
  8606. /**
  8607. * Constructs a new euler instance.
  8608. *
  8609. * @param {number} [x=0] - The angle of the x axis in radians.
  8610. * @param {number} [y=0] - The angle of the y axis in radians.
  8611. * @param {number} [z=0] - The angle of the z axis in radians.
  8612. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  8613. */
  8614. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  8615. /**
  8616. * This flag can be used for type testing.
  8617. *
  8618. * @type {boolean}
  8619. * @readonly
  8620. * @default true
  8621. */
  8622. this.isEuler = true;
  8623. this._x = x;
  8624. this._y = y;
  8625. this._z = z;
  8626. this._order = order;
  8627. }
  8628. /**
  8629. * The angle of the x axis in radians.
  8630. *
  8631. * @type {number}
  8632. * @default 0
  8633. */
  8634. get x() {
  8635. return this._x;
  8636. }
  8637. set x( value ) {
  8638. this._x = value;
  8639. this._onChangeCallback();
  8640. }
  8641. /**
  8642. * The angle of the y axis in radians.
  8643. *
  8644. * @type {number}
  8645. * @default 0
  8646. */
  8647. get y() {
  8648. return this._y;
  8649. }
  8650. set y( value ) {
  8651. this._y = value;
  8652. this._onChangeCallback();
  8653. }
  8654. /**
  8655. * The angle of the z axis in radians.
  8656. *
  8657. * @type {number}
  8658. * @default 0
  8659. */
  8660. get z() {
  8661. return this._z;
  8662. }
  8663. set z( value ) {
  8664. this._z = value;
  8665. this._onChangeCallback();
  8666. }
  8667. /**
  8668. * A string representing the order that the rotations are applied.
  8669. *
  8670. * @type {string}
  8671. * @default 'XYZ'
  8672. */
  8673. get order() {
  8674. return this._order;
  8675. }
  8676. set order( value ) {
  8677. this._order = value;
  8678. this._onChangeCallback();
  8679. }
  8680. /**
  8681. * Sets the Euler components.
  8682. *
  8683. * @param {number} x - The angle of the x axis in radians.
  8684. * @param {number} y - The angle of the y axis in radians.
  8685. * @param {number} z - The angle of the z axis in radians.
  8686. * @param {string} [order] - A string representing the order that the rotations are applied.
  8687. * @return {Euler} A reference to this Euler instance.
  8688. */
  8689. set( x, y, z, order = this._order ) {
  8690. this._x = x;
  8691. this._y = y;
  8692. this._z = z;
  8693. this._order = order;
  8694. this._onChangeCallback();
  8695. return this;
  8696. }
  8697. /**
  8698. * Returns a new Euler instance with copied values from this instance.
  8699. *
  8700. * @return {Euler} A clone of this instance.
  8701. */
  8702. clone() {
  8703. return new this.constructor( this._x, this._y, this._z, this._order );
  8704. }
  8705. /**
  8706. * Copies the values of the given Euler instance to this instance.
  8707. *
  8708. * @param {Euler} euler - The Euler instance to copy.
  8709. * @return {Euler} A reference to this Euler instance.
  8710. */
  8711. copy( euler ) {
  8712. this._x = euler._x;
  8713. this._y = euler._y;
  8714. this._z = euler._z;
  8715. this._order = euler._order;
  8716. this._onChangeCallback();
  8717. return this;
  8718. }
  8719. /**
  8720. * Sets the angles of this Euler instance from a pure rotation matrix.
  8721. *
  8722. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  8723. * @param {string} [order] - A string representing the order that the rotations are applied.
  8724. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8725. * @return {Euler} A reference to this Euler instance.
  8726. */
  8727. setFromRotationMatrix( m, order = this._order, update = true ) {
  8728. const te = m.elements;
  8729. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  8730. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  8731. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  8732. switch ( order ) {
  8733. case 'XYZ':
  8734. this._y = Math.asin( clamp( m13, -1, 1 ) );
  8735. if ( Math.abs( m13 ) < 0.9999999 ) {
  8736. this._x = Math.atan2( - m23, m33 );
  8737. this._z = Math.atan2( - m12, m11 );
  8738. } else {
  8739. this._x = Math.atan2( m32, m22 );
  8740. this._z = 0;
  8741. }
  8742. break;
  8743. case 'YXZ':
  8744. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  8745. if ( Math.abs( m23 ) < 0.9999999 ) {
  8746. this._y = Math.atan2( m13, m33 );
  8747. this._z = Math.atan2( m21, m22 );
  8748. } else {
  8749. this._y = Math.atan2( - m31, m11 );
  8750. this._z = 0;
  8751. }
  8752. break;
  8753. case 'ZXY':
  8754. this._x = Math.asin( clamp( m32, -1, 1 ) );
  8755. if ( Math.abs( m32 ) < 0.9999999 ) {
  8756. this._y = Math.atan2( - m31, m33 );
  8757. this._z = Math.atan2( - m12, m22 );
  8758. } else {
  8759. this._y = 0;
  8760. this._z = Math.atan2( m21, m11 );
  8761. }
  8762. break;
  8763. case 'ZYX':
  8764. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  8765. if ( Math.abs( m31 ) < 0.9999999 ) {
  8766. this._x = Math.atan2( m32, m33 );
  8767. this._z = Math.atan2( m21, m11 );
  8768. } else {
  8769. this._x = 0;
  8770. this._z = Math.atan2( - m12, m22 );
  8771. }
  8772. break;
  8773. case 'YZX':
  8774. this._z = Math.asin( clamp( m21, -1, 1 ) );
  8775. if ( Math.abs( m21 ) < 0.9999999 ) {
  8776. this._x = Math.atan2( - m23, m22 );
  8777. this._y = Math.atan2( - m31, m11 );
  8778. } else {
  8779. this._x = 0;
  8780. this._y = Math.atan2( m13, m33 );
  8781. }
  8782. break;
  8783. case 'XZY':
  8784. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  8785. if ( Math.abs( m12 ) < 0.9999999 ) {
  8786. this._x = Math.atan2( m32, m22 );
  8787. this._y = Math.atan2( m13, m11 );
  8788. } else {
  8789. this._x = Math.atan2( - m23, m33 );
  8790. this._y = 0;
  8791. }
  8792. break;
  8793. default:
  8794. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  8795. }
  8796. this._order = order;
  8797. if ( update === true ) this._onChangeCallback();
  8798. return this;
  8799. }
  8800. /**
  8801. * Sets the angles of this Euler instance from a normalized quaternion.
  8802. *
  8803. * @param {Quaternion} q - A normalized Quaternion.
  8804. * @param {string} [order] - A string representing the order that the rotations are applied.
  8805. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  8806. * @return {Euler} A reference to this Euler instance.
  8807. */
  8808. setFromQuaternion( q, order, update ) {
  8809. _matrix$2.makeRotationFromQuaternion( q );
  8810. return this.setFromRotationMatrix( _matrix$2, order, update );
  8811. }
  8812. /**
  8813. * Sets the angles of this Euler instance from the given vector.
  8814. *
  8815. * @param {Vector3} v - The vector.
  8816. * @param {string} [order] - A string representing the order that the rotations are applied.
  8817. * @return {Euler} A reference to this Euler instance.
  8818. */
  8819. setFromVector3( v, order = this._order ) {
  8820. return this.set( v.x, v.y, v.z, order );
  8821. }
  8822. /**
  8823. * Resets the euler angle with a new order by creating a quaternion from this
  8824. * euler angle and then setting this euler angle with the quaternion and the
  8825. * new order.
  8826. *
  8827. * Warning: This discards revolution information.
  8828. *
  8829. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  8830. * @return {Euler} A reference to this Euler instance.
  8831. */
  8832. reorder( newOrder ) {
  8833. _quaternion$4.setFromEuler( this );
  8834. return this.setFromQuaternion( _quaternion$4, newOrder );
  8835. }
  8836. /**
  8837. * Returns `true` if this Euler instance is equal with the given one.
  8838. *
  8839. * @param {Euler} euler - The Euler instance to test for equality.
  8840. * @return {boolean} Whether this Euler instance is equal with the given one.
  8841. */
  8842. equals( euler ) {
  8843. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  8844. }
  8845. /**
  8846. * Sets this Euler instance's components to values from the given array. The first three
  8847. * entries of the array are assign to the x,y and z components. An optional fourth entry
  8848. * defines the Euler order.
  8849. *
  8850. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  8851. * @return {Euler} A reference to this Euler instance.
  8852. */
  8853. fromArray( array ) {
  8854. this._x = array[ 0 ];
  8855. this._y = array[ 1 ];
  8856. this._z = array[ 2 ];
  8857. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  8858. this._onChangeCallback();
  8859. return this;
  8860. }
  8861. /**
  8862. * Writes the components of this Euler instance to the given array. If no array is provided,
  8863. * the method returns a new instance.
  8864. *
  8865. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  8866. * @param {number} [offset=0] - Index of the first element in the array.
  8867. * @return {Array<number,number,number,string>} The Euler components.
  8868. */
  8869. toArray( array = [], offset = 0 ) {
  8870. array[ offset ] = this._x;
  8871. array[ offset + 1 ] = this._y;
  8872. array[ offset + 2 ] = this._z;
  8873. array[ offset + 3 ] = this._order;
  8874. return array;
  8875. }
  8876. _onChange( callback ) {
  8877. this._onChangeCallback = callback;
  8878. return this;
  8879. }
  8880. _onChangeCallback() {}
  8881. *[ Symbol.iterator ]() {
  8882. yield this._x;
  8883. yield this._y;
  8884. yield this._z;
  8885. yield this._order;
  8886. }
  8887. }
  8888. /**
  8889. * The default Euler angle order.
  8890. *
  8891. * @static
  8892. * @type {string}
  8893. * @default 'XYZ'
  8894. */
  8895. Euler.DEFAULT_ORDER = 'XYZ';
  8896. /**
  8897. * A layers object assigns an 3D object to 1 or more of 32
  8898. * layers numbered `0` to `31` - internally the layers are stored as a
  8899. * bit mask], and by default all 3D objects are a member of layer `0`.
  8900. *
  8901. * This can be used to control visibility - an object must share a layer with
  8902. * a camera to be visible when that camera's view is
  8903. * rendered.
  8904. *
  8905. * All classes that inherit from {@link Object3D} have an `layers` property which
  8906. * is an instance of this class.
  8907. */
  8908. class Layers {
  8909. /**
  8910. * Constructs a new layers instance, with membership
  8911. * initially set to layer `0`.
  8912. */
  8913. constructor() {
  8914. /**
  8915. * A bit mask storing which of the 32 layers this layers object is currently
  8916. * a member of.
  8917. *
  8918. * @type {number}
  8919. */
  8920. this.mask = 1 | 0;
  8921. }
  8922. /**
  8923. * Sets membership to the given layer, and remove membership all other layers.
  8924. *
  8925. * @param {number} layer - The layer to set.
  8926. */
  8927. set( layer ) {
  8928. this.mask = ( 1 << layer | 0 ) >>> 0;
  8929. }
  8930. /**
  8931. * Adds membership of the given layer.
  8932. *
  8933. * @param {number} layer - The layer to enable.
  8934. */
  8935. enable( layer ) {
  8936. this.mask |= 1 << layer | 0;
  8937. }
  8938. /**
  8939. * Adds membership to all layers.
  8940. */
  8941. enableAll() {
  8942. this.mask = 0xffffffff | 0;
  8943. }
  8944. /**
  8945. * Toggles the membership of the given layer.
  8946. *
  8947. * @param {number} layer - The layer to toggle.
  8948. */
  8949. toggle( layer ) {
  8950. this.mask ^= 1 << layer | 0;
  8951. }
  8952. /**
  8953. * Removes membership of the given layer.
  8954. *
  8955. * @param {number} layer - The layer to enable.
  8956. */
  8957. disable( layer ) {
  8958. this.mask &= ~ ( 1 << layer | 0 );
  8959. }
  8960. /**
  8961. * Removes the membership from all layers.
  8962. */
  8963. disableAll() {
  8964. this.mask = 0;
  8965. }
  8966. /**
  8967. * Returns `true` if this and the given layers object have at least one
  8968. * layer in common.
  8969. *
  8970. * @param {Layers} layers - The layers to test.
  8971. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  8972. */
  8973. test( layers ) {
  8974. return ( this.mask & layers.mask ) !== 0;
  8975. }
  8976. /**
  8977. * Returns `true` if the given layer is enabled.
  8978. *
  8979. * @param {number} layer - The layer to test.
  8980. * @return {boolean } Whether the given layer is enabled or not.
  8981. */
  8982. isEnabled( layer ) {
  8983. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  8984. }
  8985. }
  8986. let _object3DId = 0;
  8987. const _v1$6 = /*@__PURE__*/ new Vector3();
  8988. const _q1 = /*@__PURE__*/ new Quaternion();
  8989. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8990. const _target = /*@__PURE__*/ new Vector3();
  8991. const _position$4 = /*@__PURE__*/ new Vector3();
  8992. const _scale$3 = /*@__PURE__*/ new Vector3();
  8993. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  8994. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  8995. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8996. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  8997. /**
  8998. * Fires when the object has been added to its parent object.
  8999. *
  9000. * @event Object3D#added
  9001. * @type {Object}
  9002. */
  9003. const _addedEvent = { type: 'added' };
  9004. /**
  9005. * Fires when the object has been removed from its parent object.
  9006. *
  9007. * @event Object3D#removed
  9008. * @type {Object}
  9009. */
  9010. const _removedEvent = { type: 'removed' };
  9011. /**
  9012. * Fires when a new child object has been added.
  9013. *
  9014. * @event Object3D#childadded
  9015. * @type {Object}
  9016. */
  9017. const _childaddedEvent = { type: 'childadded', child: null };
  9018. /**
  9019. * Fires when a child object has been removed.
  9020. *
  9021. * @event Object3D#childremoved
  9022. * @type {Object}
  9023. */
  9024. const _childremovedEvent = { type: 'childremoved', child: null };
  9025. /**
  9026. * This is the base class for most objects in three.js and provides a set of
  9027. * properties and methods for manipulating objects in 3D space.
  9028. *
  9029. * @augments EventDispatcher
  9030. */
  9031. class Object3D extends EventDispatcher {
  9032. /**
  9033. * Constructs a new 3D object.
  9034. */
  9035. constructor() {
  9036. super();
  9037. /**
  9038. * This flag can be used for type testing.
  9039. *
  9040. * @type {boolean}
  9041. * @readonly
  9042. * @default true
  9043. */
  9044. this.isObject3D = true;
  9045. /**
  9046. * The ID of the 3D object.
  9047. *
  9048. * @name Object3D#id
  9049. * @type {number}
  9050. * @readonly
  9051. */
  9052. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  9053. /**
  9054. * The UUID of the 3D object.
  9055. *
  9056. * @type {string}
  9057. * @readonly
  9058. */
  9059. this.uuid = generateUUID();
  9060. /**
  9061. * The name of the 3D object.
  9062. *
  9063. * @type {string}
  9064. */
  9065. this.name = '';
  9066. /**
  9067. * The type property is used for detecting the object type
  9068. * in context of serialization/deserialization.
  9069. *
  9070. * @type {string}
  9071. * @readonly
  9072. */
  9073. this.type = 'Object3D';
  9074. /**
  9075. * A reference to the parent object.
  9076. *
  9077. * @type {?Object3D}
  9078. * @default null
  9079. */
  9080. this.parent = null;
  9081. /**
  9082. * An array holding the child 3D objects of this instance.
  9083. *
  9084. * @type {Array<Object3D>}
  9085. */
  9086. this.children = [];
  9087. /**
  9088. * Defines the `up` direction of the 3D object which influences
  9089. * the orientation via methods like {@link Object3D#lookAt}.
  9090. *
  9091. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  9092. *
  9093. * @type {Vector3}
  9094. */
  9095. this.up = Object3D.DEFAULT_UP.clone();
  9096. const position = new Vector3();
  9097. const rotation = new Euler();
  9098. const quaternion = new Quaternion();
  9099. const scale = new Vector3( 1, 1, 1 );
  9100. function onRotationChange() {
  9101. quaternion.setFromEuler( rotation, false );
  9102. }
  9103. function onQuaternionChange() {
  9104. rotation.setFromQuaternion( quaternion, undefined, false );
  9105. }
  9106. rotation._onChange( onRotationChange );
  9107. quaternion._onChange( onQuaternionChange );
  9108. Object.defineProperties( this, {
  9109. /**
  9110. * Represents the object's local position.
  9111. *
  9112. * @name Object3D#position
  9113. * @type {Vector3}
  9114. * @default (0,0,0)
  9115. */
  9116. position: {
  9117. configurable: true,
  9118. enumerable: true,
  9119. value: position
  9120. },
  9121. /**
  9122. * Represents the object's local rotation as Euler angles, in radians.
  9123. *
  9124. * @name Object3D#rotation
  9125. * @type {Euler}
  9126. * @default (0,0,0)
  9127. */
  9128. rotation: {
  9129. configurable: true,
  9130. enumerable: true,
  9131. value: rotation
  9132. },
  9133. /**
  9134. * Represents the object's local rotation as Quaternions.
  9135. *
  9136. * @name Object3D#quaternion
  9137. * @type {Quaternion}
  9138. */
  9139. quaternion: {
  9140. configurable: true,
  9141. enumerable: true,
  9142. value: quaternion
  9143. },
  9144. /**
  9145. * Represents the object's local scale.
  9146. *
  9147. * @name Object3D#scale
  9148. * @type {Vector3}
  9149. * @default (1,1,1)
  9150. */
  9151. scale: {
  9152. configurable: true,
  9153. enumerable: true,
  9154. value: scale
  9155. },
  9156. /**
  9157. * Represents the object's model-view matrix.
  9158. *
  9159. * @name Object3D#modelViewMatrix
  9160. * @type {Matrix4}
  9161. */
  9162. modelViewMatrix: {
  9163. value: new Matrix4()
  9164. },
  9165. /**
  9166. * Represents the object's normal matrix.
  9167. *
  9168. * @name Object3D#normalMatrix
  9169. * @type {Matrix3}
  9170. */
  9171. normalMatrix: {
  9172. value: new Matrix3()
  9173. }
  9174. } );
  9175. /**
  9176. * Represents the object's transformation matrix in local space.
  9177. *
  9178. * @type {Matrix4}
  9179. */
  9180. this.matrix = new Matrix4();
  9181. /**
  9182. * Represents the object's transformation matrix in world space.
  9183. * If the 3D object has no parent, then it's identical to the local transformation matrix
  9184. *
  9185. * @type {Matrix4}
  9186. */
  9187. this.matrixWorld = new Matrix4();
  9188. /**
  9189. * When set to `true`, the engine automatically computes the local matrix from position,
  9190. * rotation and scale every frame. If set to `false`, the app is responsible for recomputing
  9191. * the local matrix by calling `updateMatrix()`.
  9192. *
  9193. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  9194. *
  9195. * @type {boolean}
  9196. * @default true
  9197. */
  9198. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  9199. /**
  9200. * When set to `true`, the engine automatically computes the world matrix from the current local
  9201. * matrix and the object's transformation hierarchy. If set to `false`, the app is responsible for
  9202. * recomputing the world matrix by directly updating the `matrixWorld` property.
  9203. *
  9204. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  9205. *
  9206. * @type {boolean}
  9207. * @default true
  9208. */
  9209. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  9210. /**
  9211. * When set to `true`, it calculates the world matrix in that frame and resets this property
  9212. * to `false`.
  9213. *
  9214. * @type {boolean}
  9215. * @default false
  9216. */
  9217. this.matrixWorldNeedsUpdate = false;
  9218. /**
  9219. * The layer membership of the 3D object. The 3D object is only visible if it has
  9220. * at least one layer in common with the camera in use. This property can also be
  9221. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  9222. *
  9223. * @type {Layers}
  9224. */
  9225. this.layers = new Layers();
  9226. /**
  9227. * When set to `true`, the 3D object gets rendered.
  9228. *
  9229. * @type {boolean}
  9230. * @default true
  9231. */
  9232. this.visible = true;
  9233. /**
  9234. * When set to `true`, the 3D object gets rendered into shadow maps.
  9235. *
  9236. * @type {boolean}
  9237. * @default false
  9238. */
  9239. this.castShadow = false;
  9240. /**
  9241. * When set to `true`, the 3D object is affected by shadows in the scene.
  9242. *
  9243. * @type {boolean}
  9244. * @default false
  9245. */
  9246. this.receiveShadow = false;
  9247. /**
  9248. * When set to `true`, the 3D object is honored by view frustum culling.
  9249. *
  9250. * @type {boolean}
  9251. * @default true
  9252. */
  9253. this.frustumCulled = true;
  9254. /**
  9255. * This value allows the default rendering order of scene graph objects to be
  9256. * overridden although opaque and transparent objects remain sorted independently.
  9257. * When this property is set for an instance of {@link Group},all descendants
  9258. * objects will be sorted and rendered together. Sorting is from lowest to highest
  9259. * render order.
  9260. *
  9261. * @type {number}
  9262. * @default 0
  9263. */
  9264. this.renderOrder = 0;
  9265. /**
  9266. * An array holding the animation clips of the 3D object.
  9267. *
  9268. * @type {Array<AnimationClip>}
  9269. */
  9270. this.animations = [];
  9271. /**
  9272. * Custom depth material to be used when rendering to the depth map. Can only be used
  9273. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  9274. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  9275. * material for proper shadows.
  9276. *
  9277. * Only relevant in context of {@link WebGLRenderer}.
  9278. *
  9279. * @type {(Material|undefined)}
  9280. * @default undefined
  9281. */
  9282. this.customDepthMaterial = undefined;
  9283. /**
  9284. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  9285. *
  9286. * Only relevant in context of {@link WebGLRenderer}.
  9287. *
  9288. * @type {(Material|undefined)}
  9289. * @default undefined
  9290. */
  9291. this.customDistanceMaterial = undefined;
  9292. /**
  9293. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  9294. * the 3D object is not going to be changed after the initial renderer. This includes
  9295. * geometry and material settings. A static 3D object can be processed by the renderer
  9296. * slightly faster since certain state checks can be bypassed.
  9297. *
  9298. * Only relevant in context of {@link WebGPURenderer}.
  9299. *
  9300. * @type {boolean}
  9301. * @default false
  9302. */
  9303. this.static = false;
  9304. /**
  9305. * An object that can be used to store custom data about the 3D object. It
  9306. * should not hold references to functions as these will not be cloned.
  9307. *
  9308. * @type {Object}
  9309. */
  9310. this.userData = {};
  9311. /**
  9312. * The pivot point for rotation and scale transformations.
  9313. * When set, rotation and scale are applied around this point
  9314. * instead of the object's origin.
  9315. *
  9316. * @type {?Vector3}
  9317. * @default null
  9318. */
  9319. this.pivot = null;
  9320. }
  9321. /**
  9322. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  9323. *
  9324. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9325. * @param {Object3D} object - The 3D object.
  9326. * @param {Camera} camera - The camera that is used to render the scene.
  9327. * @param {Camera} shadowCamera - The shadow camera.
  9328. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9329. * @param {Material} depthMaterial - The depth material.
  9330. * @param {Object} group - The geometry group data.
  9331. */
  9332. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9333. /**
  9334. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  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 {Camera} shadowCamera - The shadow camera.
  9340. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9341. * @param {Material} depthMaterial - The depth material.
  9342. * @param {Object} group - The geometry group data.
  9343. */
  9344. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  9345. /**
  9346. * A callback that is executed immediately before a 3D object is rendered.
  9347. *
  9348. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9349. * @param {Object3D} object - The 3D object.
  9350. * @param {Camera} camera - The camera that is used to render the scene.
  9351. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9352. * @param {Material} material - The 3D object's material.
  9353. * @param {Object} group - The geometry group data.
  9354. */
  9355. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9356. /**
  9357. * A callback that is executed immediately after a 3D object is rendered.
  9358. *
  9359. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  9360. * @param {Object3D} object - The 3D object.
  9361. * @param {Camera} camera - The camera that is used to render the scene.
  9362. * @param {BufferGeometry} geometry - The 3D object's geometry.
  9363. * @param {Material} material - The 3D object's material.
  9364. * @param {Object} group - The geometry group data.
  9365. */
  9366. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  9367. /**
  9368. * Applies the given transformation matrix to the object and updates the object's position,
  9369. * rotation and scale.
  9370. *
  9371. * @param {Matrix4} matrix - The transformation matrix.
  9372. */
  9373. applyMatrix4( matrix ) {
  9374. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9375. this.matrix.premultiply( matrix );
  9376. this.matrix.decompose( this.position, this.quaternion, this.scale );
  9377. }
  9378. /**
  9379. * Applies a rotation represented by given the quaternion to the 3D object.
  9380. *
  9381. * @param {Quaternion} q - The quaternion.
  9382. * @return {Object3D} A reference to this instance.
  9383. */
  9384. applyQuaternion( q ) {
  9385. this.quaternion.premultiply( q );
  9386. return this;
  9387. }
  9388. /**
  9389. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  9390. *
  9391. * @param {Vector3} axis - The (normalized) axis vector.
  9392. * @param {number} angle - The angle in radians.
  9393. */
  9394. setRotationFromAxisAngle( axis, angle ) {
  9395. // assumes axis is normalized
  9396. this.quaternion.setFromAxisAngle( axis, angle );
  9397. }
  9398. /**
  9399. * Sets the given rotation represented as Euler angles to the 3D object.
  9400. *
  9401. * @param {Euler} euler - The Euler angles.
  9402. */
  9403. setRotationFromEuler( euler ) {
  9404. this.quaternion.setFromEuler( euler, true );
  9405. }
  9406. /**
  9407. * Sets the given rotation represented as rotation matrix to the 3D object.
  9408. *
  9409. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  9410. * a pure rotation matrix (i.e, unscaled).
  9411. */
  9412. setRotationFromMatrix( m ) {
  9413. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  9414. this.quaternion.setFromRotationMatrix( m );
  9415. }
  9416. /**
  9417. * Sets the given rotation represented as a Quaternion to the 3D object.
  9418. *
  9419. * @param {Quaternion} q - The Quaternion
  9420. */
  9421. setRotationFromQuaternion( q ) {
  9422. // assumes q is normalized
  9423. this.quaternion.copy( q );
  9424. }
  9425. /**
  9426. * Rotates the 3D object along an axis in local space.
  9427. *
  9428. * @param {Vector3} axis - The (normalized) axis vector.
  9429. * @param {number} angle - The angle in radians.
  9430. * @return {Object3D} A reference to this instance.
  9431. */
  9432. rotateOnAxis( axis, angle ) {
  9433. // rotate object on axis in object space
  9434. // axis is assumed to be normalized
  9435. _q1.setFromAxisAngle( axis, angle );
  9436. this.quaternion.multiply( _q1 );
  9437. return this;
  9438. }
  9439. /**
  9440. * Rotates the 3D object along an axis in world space.
  9441. *
  9442. * @param {Vector3} axis - The (normalized) axis vector.
  9443. * @param {number} angle - The angle in radians.
  9444. * @return {Object3D} A reference to this instance.
  9445. */
  9446. rotateOnWorldAxis( axis, angle ) {
  9447. // rotate object on axis in world space
  9448. // axis is assumed to be normalized
  9449. // method assumes no rotated parent
  9450. _q1.setFromAxisAngle( axis, angle );
  9451. this.quaternion.premultiply( _q1 );
  9452. return this;
  9453. }
  9454. /**
  9455. * Rotates the 3D object around its X axis in local space.
  9456. *
  9457. * @param {number} angle - The angle in radians.
  9458. * @return {Object3D} A reference to this instance.
  9459. */
  9460. rotateX( angle ) {
  9461. return this.rotateOnAxis( _xAxis, angle );
  9462. }
  9463. /**
  9464. * Rotates the 3D object around its Y axis in local space.
  9465. *
  9466. * @param {number} angle - The angle in radians.
  9467. * @return {Object3D} A reference to this instance.
  9468. */
  9469. rotateY( angle ) {
  9470. return this.rotateOnAxis( _yAxis, angle );
  9471. }
  9472. /**
  9473. * Rotates the 3D object around its Z axis in local space.
  9474. *
  9475. * @param {number} angle - The angle in radians.
  9476. * @return {Object3D} A reference to this instance.
  9477. */
  9478. rotateZ( angle ) {
  9479. return this.rotateOnAxis( _zAxis, angle );
  9480. }
  9481. /**
  9482. * Translate the 3D object by a distance along the given axis in local space.
  9483. *
  9484. * @param {Vector3} axis - The (normalized) axis vector.
  9485. * @param {number} distance - The distance in world units.
  9486. * @return {Object3D} A reference to this instance.
  9487. */
  9488. translateOnAxis( axis, distance ) {
  9489. // translate object by distance along axis in object space
  9490. // axis is assumed to be normalized
  9491. _v1$6.copy( axis ).applyQuaternion( this.quaternion );
  9492. this.position.add( _v1$6.multiplyScalar( distance ) );
  9493. return this;
  9494. }
  9495. /**
  9496. * Translate the 3D object by a distance along its X-axis in local space.
  9497. *
  9498. * @param {number} distance - The distance in world units.
  9499. * @return {Object3D} A reference to this instance.
  9500. */
  9501. translateX( distance ) {
  9502. return this.translateOnAxis( _xAxis, distance );
  9503. }
  9504. /**
  9505. * Translate the 3D object by a distance along its Y-axis in local space.
  9506. *
  9507. * @param {number} distance - The distance in world units.
  9508. * @return {Object3D} A reference to this instance.
  9509. */
  9510. translateY( distance ) {
  9511. return this.translateOnAxis( _yAxis, distance );
  9512. }
  9513. /**
  9514. * Translate the 3D object by a distance along its Z-axis in local space.
  9515. *
  9516. * @param {number} distance - The distance in world units.
  9517. * @return {Object3D} A reference to this instance.
  9518. */
  9519. translateZ( distance ) {
  9520. return this.translateOnAxis( _zAxis, distance );
  9521. }
  9522. /**
  9523. * Converts the given vector from this 3D object's local space to world space.
  9524. *
  9525. * @param {Vector3} vector - The vector to convert.
  9526. * @return {Vector3} The converted vector.
  9527. */
  9528. localToWorld( vector ) {
  9529. this.updateWorldMatrix( true, false );
  9530. return vector.applyMatrix4( this.matrixWorld );
  9531. }
  9532. /**
  9533. * Converts the given vector from this 3D object's world space to local space.
  9534. *
  9535. * @param {Vector3} vector - The vector to convert.
  9536. * @return {Vector3} The converted vector.
  9537. */
  9538. worldToLocal( vector ) {
  9539. this.updateWorldMatrix( true, false );
  9540. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  9541. }
  9542. /**
  9543. * Rotates the object to face a point in world space.
  9544. *
  9545. * This method does not support objects having non-uniformly-scaled parent(s).
  9546. *
  9547. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  9548. * @param {number} [y] - The y coordinate in world space.
  9549. * @param {number} [z] - The z coordinate in world space.
  9550. */
  9551. lookAt( x, y, z ) {
  9552. // This method does not support objects having non-uniformly-scaled parent(s)
  9553. if ( x.isVector3 ) {
  9554. _target.copy( x );
  9555. } else {
  9556. _target.set( x, y, z );
  9557. }
  9558. const parent = this.parent;
  9559. this.updateWorldMatrix( true, false );
  9560. _position$4.setFromMatrixPosition( this.matrixWorld );
  9561. if ( this.isCamera || this.isLight ) {
  9562. _m1$1.lookAt( _position$4, _target, this.up );
  9563. } else {
  9564. _m1$1.lookAt( _target, _position$4, this.up );
  9565. }
  9566. this.quaternion.setFromRotationMatrix( _m1$1 );
  9567. if ( parent ) {
  9568. _m1$1.extractRotation( parent.matrixWorld );
  9569. _q1.setFromRotationMatrix( _m1$1 );
  9570. this.quaternion.premultiply( _q1.invert() );
  9571. }
  9572. }
  9573. /**
  9574. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  9575. * objects may be added. Any current parent on an object passed in here will be
  9576. * removed, since an object can have at most one parent.
  9577. *
  9578. * @fires Object3D#added
  9579. * @fires Object3D#childadded
  9580. * @param {Object3D} object - The 3D object to add.
  9581. * @return {Object3D} A reference to this instance.
  9582. */
  9583. add( object ) {
  9584. if ( arguments.length > 1 ) {
  9585. for ( let i = 0; i < arguments.length; i ++ ) {
  9586. this.add( arguments[ i ] );
  9587. }
  9588. return this;
  9589. }
  9590. if ( object === this ) {
  9591. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  9592. return this;
  9593. }
  9594. if ( object && object.isObject3D ) {
  9595. object.removeFromParent();
  9596. object.parent = this;
  9597. this.children.push( object );
  9598. object.dispatchEvent( _addedEvent );
  9599. _childaddedEvent.child = object;
  9600. this.dispatchEvent( _childaddedEvent );
  9601. _childaddedEvent.child = null;
  9602. } else {
  9603. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  9604. }
  9605. return this;
  9606. }
  9607. /**
  9608. * Removes the given 3D object as child from this 3D object.
  9609. * An arbitrary number of objects may be removed.
  9610. *
  9611. * @fires Object3D#removed
  9612. * @fires Object3D#childremoved
  9613. * @param {Object3D} object - The 3D object to remove.
  9614. * @return {Object3D} A reference to this instance.
  9615. */
  9616. remove( object ) {
  9617. if ( arguments.length > 1 ) {
  9618. for ( let i = 0; i < arguments.length; i ++ ) {
  9619. this.remove( arguments[ i ] );
  9620. }
  9621. return this;
  9622. }
  9623. const index = this.children.indexOf( object );
  9624. if ( index !== -1 ) {
  9625. object.parent = null;
  9626. this.children.splice( index, 1 );
  9627. object.dispatchEvent( _removedEvent );
  9628. _childremovedEvent.child = object;
  9629. this.dispatchEvent( _childremovedEvent );
  9630. _childremovedEvent.child = null;
  9631. }
  9632. return this;
  9633. }
  9634. /**
  9635. * Removes this 3D object from its current parent.
  9636. *
  9637. * @fires Object3D#removed
  9638. * @fires Object3D#childremoved
  9639. * @return {Object3D} A reference to this instance.
  9640. */
  9641. removeFromParent() {
  9642. const parent = this.parent;
  9643. if ( parent !== null ) {
  9644. parent.remove( this );
  9645. }
  9646. return this;
  9647. }
  9648. /**
  9649. * Removes all child objects.
  9650. *
  9651. * @fires Object3D#removed
  9652. * @fires Object3D#childremoved
  9653. * @return {Object3D} A reference to this instance.
  9654. */
  9655. clear() {
  9656. return this.remove( ... this.children );
  9657. }
  9658. /**
  9659. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  9660. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  9661. *
  9662. * @fires Object3D#added
  9663. * @fires Object3D#childadded
  9664. * @param {Object3D} object - The 3D object to attach.
  9665. * @return {Object3D} A reference to this instance.
  9666. */
  9667. attach( object ) {
  9668. // adds object as a child of this, while maintaining the object's world transform
  9669. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  9670. this.updateWorldMatrix( true, false );
  9671. _m1$1.copy( this.matrixWorld ).invert();
  9672. if ( object.parent !== null ) {
  9673. object.parent.updateWorldMatrix( true, false );
  9674. _m1$1.multiply( object.parent.matrixWorld );
  9675. }
  9676. object.applyMatrix4( _m1$1 );
  9677. object.removeFromParent();
  9678. object.parent = this;
  9679. this.children.push( object );
  9680. object.updateWorldMatrix( false, true );
  9681. object.dispatchEvent( _addedEvent );
  9682. _childaddedEvent.child = object;
  9683. this.dispatchEvent( _childaddedEvent );
  9684. _childaddedEvent.child = null;
  9685. return this;
  9686. }
  9687. /**
  9688. * Searches through the 3D object and its children, starting with the 3D object
  9689. * itself, and returns the first with a matching ID.
  9690. *
  9691. * @param {number} id - The id.
  9692. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9693. */
  9694. getObjectById( id ) {
  9695. return this.getObjectByProperty( 'id', id );
  9696. }
  9697. /**
  9698. * Searches through the 3D object and its children, starting with the 3D object
  9699. * itself, and returns the first with a matching name.
  9700. *
  9701. * @param {string} name - The name.
  9702. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9703. */
  9704. getObjectByName( name ) {
  9705. return this.getObjectByProperty( 'name', name );
  9706. }
  9707. /**
  9708. * Searches through the 3D object and its children, starting with the 3D object
  9709. * itself, and returns the first with a matching property value.
  9710. *
  9711. * @param {string} name - The name of the property.
  9712. * @param {any} value - The value.
  9713. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  9714. */
  9715. getObjectByProperty( name, value ) {
  9716. if ( this[ name ] === value ) return this;
  9717. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  9718. const child = this.children[ i ];
  9719. const object = child.getObjectByProperty( name, value );
  9720. if ( object !== undefined ) {
  9721. return object;
  9722. }
  9723. }
  9724. return undefined;
  9725. }
  9726. /**
  9727. * Searches through the 3D object and its children, starting with the 3D object
  9728. * itself, and returns all 3D objects with a matching property value.
  9729. *
  9730. * @param {string} name - The name of the property.
  9731. * @param {any} value - The value.
  9732. * @param {Array<Object3D>} result - The method stores the result in this array.
  9733. * @return {Array<Object3D>} The found 3D objects.
  9734. */
  9735. getObjectsByProperty( name, value, result = [] ) {
  9736. if ( this[ name ] === value ) result.push( this );
  9737. const children = this.children;
  9738. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9739. children[ i ].getObjectsByProperty( name, value, result );
  9740. }
  9741. return result;
  9742. }
  9743. /**
  9744. * Returns a vector representing the position of the 3D object in world space.
  9745. *
  9746. * @param {Vector3} target - The target vector the result is stored to.
  9747. * @return {Vector3} The 3D object's position in world space.
  9748. */
  9749. getWorldPosition( target ) {
  9750. this.updateWorldMatrix( true, false );
  9751. return target.setFromMatrixPosition( this.matrixWorld );
  9752. }
  9753. /**
  9754. * Returns a Quaternion representing the position of the 3D object in world space.
  9755. *
  9756. * @param {Quaternion} target - The target Quaternion the result is stored to.
  9757. * @return {Quaternion} The 3D object's rotation in world space.
  9758. */
  9759. getWorldQuaternion( target ) {
  9760. this.updateWorldMatrix( true, false );
  9761. this.matrixWorld.decompose( _position$4, target, _scale$3 );
  9762. return target;
  9763. }
  9764. /**
  9765. * Returns a vector representing the scale of the 3D object in world space.
  9766. *
  9767. * @param {Vector3} target - The target vector the result is stored to.
  9768. * @return {Vector3} The 3D object's scale in world space.
  9769. */
  9770. getWorldScale( target ) {
  9771. this.updateWorldMatrix( true, false );
  9772. this.matrixWorld.decompose( _position$4, _quaternion$3, target );
  9773. return target;
  9774. }
  9775. /**
  9776. * Returns a vector representing the ("look") direction of the 3D object in world space.
  9777. *
  9778. * @param {Vector3} target - The target vector the result is stored to.
  9779. * @return {Vector3} The 3D object's direction in world space.
  9780. */
  9781. getWorldDirection( target ) {
  9782. this.updateWorldMatrix( true, false );
  9783. const e = this.matrixWorld.elements;
  9784. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  9785. }
  9786. /**
  9787. * Abstract method to get intersections between a casted ray and this
  9788. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  9789. * implement this method in order to use raycasting.
  9790. *
  9791. * @abstract
  9792. * @param {Raycaster} raycaster - The raycaster.
  9793. * @param {Array<Object>} intersects - An array holding the result of the method.
  9794. */
  9795. raycast( /* raycaster, intersects */ ) {}
  9796. /**
  9797. * Executes the callback on this 3D object and all descendants.
  9798. *
  9799. * Note: Modifying the scene graph inside the callback is discouraged.
  9800. *
  9801. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9802. */
  9803. traverse( callback ) {
  9804. callback( this );
  9805. const children = this.children;
  9806. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9807. children[ i ].traverse( callback );
  9808. }
  9809. }
  9810. /**
  9811. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  9812. * Descendants of invisible 3D objects are not traversed.
  9813. *
  9814. * Note: Modifying the scene graph inside the callback is discouraged.
  9815. *
  9816. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9817. */
  9818. traverseVisible( callback ) {
  9819. if ( this.visible === false ) return;
  9820. callback( this );
  9821. const children = this.children;
  9822. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9823. children[ i ].traverseVisible( callback );
  9824. }
  9825. }
  9826. /**
  9827. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  9828. *
  9829. * Note: Modifying the scene graph inside the callback is discouraged.
  9830. *
  9831. * @param {Function} callback - A callback function that allows to process the current 3D object.
  9832. */
  9833. traverseAncestors( callback ) {
  9834. const parent = this.parent;
  9835. if ( parent !== null ) {
  9836. callback( parent );
  9837. parent.traverseAncestors( callback );
  9838. }
  9839. }
  9840. /**
  9841. * Updates the transformation matrix in local space by computing it from the current
  9842. * position, rotation and scale values.
  9843. */
  9844. updateMatrix() {
  9845. this.matrix.compose( this.position, this.quaternion, this.scale );
  9846. const pivot = this.pivot;
  9847. if ( pivot !== null ) {
  9848. const px = pivot.x, py = pivot.y, pz = pivot.z;
  9849. const te = this.matrix.elements;
  9850. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  9851. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  9852. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  9853. }
  9854. this.matrixWorldNeedsUpdate = true;
  9855. }
  9856. /**
  9857. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  9858. *
  9859. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  9860. * local space. The computation of the local and world matrix can be controlled with the
  9861. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  9862. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  9863. *
  9864. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  9865. * when {@link Object3D#matrixWorldNeedsUpdate} is `false`.
  9866. */
  9867. updateMatrixWorld( force ) {
  9868. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9869. if ( this.matrixWorldNeedsUpdate || force ) {
  9870. if ( this.matrixWorldAutoUpdate === true ) {
  9871. if ( this.parent === null ) {
  9872. this.matrixWorld.copy( this.matrix );
  9873. } else {
  9874. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9875. }
  9876. }
  9877. this.matrixWorldNeedsUpdate = false;
  9878. force = true;
  9879. }
  9880. // make sure descendants are updated if required
  9881. const children = this.children;
  9882. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9883. const child = children[ i ];
  9884. child.updateMatrixWorld( force );
  9885. }
  9886. }
  9887. /**
  9888. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  9889. * update of ancestor and descendant nodes.
  9890. *
  9891. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  9892. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  9893. */
  9894. updateWorldMatrix( updateParents, updateChildren ) {
  9895. const parent = this.parent;
  9896. if ( updateParents === true && parent !== null ) {
  9897. parent.updateWorldMatrix( true, false );
  9898. }
  9899. if ( this.matrixAutoUpdate ) this.updateMatrix();
  9900. if ( this.matrixWorldAutoUpdate === true ) {
  9901. if ( this.parent === null ) {
  9902. this.matrixWorld.copy( this.matrix );
  9903. } else {
  9904. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9905. }
  9906. }
  9907. // make sure descendants are updated
  9908. if ( updateChildren === true ) {
  9909. const children = this.children;
  9910. for ( let i = 0, l = children.length; i < l; i ++ ) {
  9911. const child = children[ i ];
  9912. child.updateWorldMatrix( false, true );
  9913. }
  9914. }
  9915. }
  9916. /**
  9917. * Serializes the 3D object into JSON.
  9918. *
  9919. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  9920. * @return {Object} A JSON object representing the serialized 3D object.
  9921. * @see {@link ObjectLoader#parse}
  9922. */
  9923. toJSON( meta ) {
  9924. // meta is a string when called from JSON.stringify
  9925. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  9926. const output = {};
  9927. // meta is a hash used to collect geometries, materials.
  9928. // not providing it implies that this is the root object
  9929. // being serialized.
  9930. if ( isRootObject ) {
  9931. // initialize meta obj
  9932. meta = {
  9933. geometries: {},
  9934. materials: {},
  9935. textures: {},
  9936. images: {},
  9937. shapes: {},
  9938. skeletons: {},
  9939. animations: {},
  9940. nodes: {}
  9941. };
  9942. output.metadata = {
  9943. version: 4.7,
  9944. type: 'Object',
  9945. generator: 'Object3D.toJSON'
  9946. };
  9947. }
  9948. // standard Object3D serialization
  9949. const object = {};
  9950. object.uuid = this.uuid;
  9951. object.type = this.type;
  9952. if ( this.name !== '' ) object.name = this.name;
  9953. if ( this.castShadow === true ) object.castShadow = true;
  9954. if ( this.receiveShadow === true ) object.receiveShadow = true;
  9955. if ( this.visible === false ) object.visible = false;
  9956. if ( this.frustumCulled === false ) object.frustumCulled = false;
  9957. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  9958. if ( this.static !== false ) object.static = this.static;
  9959. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  9960. object.layers = this.layers.mask;
  9961. object.matrix = this.matrix.toArray();
  9962. object.up = this.up.toArray();
  9963. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  9964. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  9965. if ( this.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, this.morphTargetDictionary );
  9966. if ( this.morphTargetInfluences !== undefined ) object.morphTargetInfluences = this.morphTargetInfluences.slice();
  9967. // object specific properties
  9968. if ( this.isInstancedMesh ) {
  9969. object.type = 'InstancedMesh';
  9970. object.count = this.count;
  9971. object.instanceMatrix = this.instanceMatrix.toJSON();
  9972. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  9973. }
  9974. if ( this.isBatchedMesh ) {
  9975. object.type = 'BatchedMesh';
  9976. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  9977. object.sortObjects = this.sortObjects;
  9978. object.drawRanges = this._drawRanges;
  9979. object.reservedRanges = this._reservedRanges;
  9980. object.geometryInfo = this._geometryInfo.map( info => ( {
  9981. ...info,
  9982. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  9983. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  9984. } ) );
  9985. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  9986. object.availableInstanceIds = this._availableInstanceIds.slice();
  9987. object.availableGeometryIds = this._availableGeometryIds.slice();
  9988. object.nextIndexStart = this._nextIndexStart;
  9989. object.nextVertexStart = this._nextVertexStart;
  9990. object.geometryCount = this._geometryCount;
  9991. object.maxInstanceCount = this._maxInstanceCount;
  9992. object.maxVertexCount = this._maxVertexCount;
  9993. object.maxIndexCount = this._maxIndexCount;
  9994. object.geometryInitialized = this._geometryInitialized;
  9995. object.matricesTexture = this._matricesTexture.toJSON( meta );
  9996. object.indirectTexture = this._indirectTexture.toJSON( meta );
  9997. if ( this._colorsTexture !== null ) {
  9998. object.colorsTexture = this._colorsTexture.toJSON( meta );
  9999. }
  10000. if ( this.boundingSphere !== null ) {
  10001. object.boundingSphere = this.boundingSphere.toJSON();
  10002. }
  10003. if ( this.boundingBox !== null ) {
  10004. object.boundingBox = this.boundingBox.toJSON();
  10005. }
  10006. }
  10007. //
  10008. function serialize( library, element ) {
  10009. if ( library[ element.uuid ] === undefined ) {
  10010. library[ element.uuid ] = element.toJSON( meta );
  10011. }
  10012. return element.uuid;
  10013. }
  10014. if ( this.isScene ) {
  10015. if ( this.background ) {
  10016. if ( this.background.isColor ) {
  10017. object.background = this.background.toJSON();
  10018. } else if ( this.background.isTexture ) {
  10019. object.background = this.background.toJSON( meta ).uuid;
  10020. }
  10021. }
  10022. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10023. object.environment = this.environment.toJSON( meta ).uuid;
  10024. }
  10025. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10026. object.geometry = serialize( meta.geometries, this.geometry );
  10027. const parameters = this.geometry.parameters;
  10028. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10029. const shapes = parameters.shapes;
  10030. if ( Array.isArray( shapes ) ) {
  10031. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10032. const shape = shapes[ i ];
  10033. serialize( meta.shapes, shape );
  10034. }
  10035. } else {
  10036. serialize( meta.shapes, shapes );
  10037. }
  10038. }
  10039. }
  10040. if ( this.isSkinnedMesh ) {
  10041. object.bindMode = this.bindMode;
  10042. object.bindMatrix = this.bindMatrix.toArray();
  10043. if ( this.skeleton !== undefined ) {
  10044. serialize( meta.skeletons, this.skeleton );
  10045. object.skeleton = this.skeleton.uuid;
  10046. }
  10047. }
  10048. if ( this.material !== undefined ) {
  10049. if ( Array.isArray( this.material ) ) {
  10050. const uuids = [];
  10051. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  10052. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10053. }
  10054. object.material = uuids;
  10055. } else {
  10056. object.material = serialize( meta.materials, this.material );
  10057. }
  10058. }
  10059. //
  10060. if ( this.children.length > 0 ) {
  10061. object.children = [];
  10062. for ( let i = 0; i < this.children.length; i ++ ) {
  10063. object.children.push( this.children[ i ].toJSON( meta ).object );
  10064. }
  10065. }
  10066. //
  10067. if ( this.animations.length > 0 ) {
  10068. object.animations = [];
  10069. for ( let i = 0; i < this.animations.length; i ++ ) {
  10070. const animation = this.animations[ i ];
  10071. object.animations.push( serialize( meta.animations, animation ) );
  10072. }
  10073. }
  10074. if ( isRootObject ) {
  10075. const geometries = extractFromCache( meta.geometries );
  10076. const materials = extractFromCache( meta.materials );
  10077. const textures = extractFromCache( meta.textures );
  10078. const images = extractFromCache( meta.images );
  10079. const shapes = extractFromCache( meta.shapes );
  10080. const skeletons = extractFromCache( meta.skeletons );
  10081. const animations = extractFromCache( meta.animations );
  10082. const nodes = extractFromCache( meta.nodes );
  10083. if ( geometries.length > 0 ) output.geometries = geometries;
  10084. if ( materials.length > 0 ) output.materials = materials;
  10085. if ( textures.length > 0 ) output.textures = textures;
  10086. if ( images.length > 0 ) output.images = images;
  10087. if ( shapes.length > 0 ) output.shapes = shapes;
  10088. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  10089. if ( animations.length > 0 ) output.animations = animations;
  10090. if ( nodes.length > 0 ) output.nodes = nodes;
  10091. }
  10092. output.object = object;
  10093. return output;
  10094. // extract data from the cache hash
  10095. // remove metadata on each item
  10096. // and return as array
  10097. function extractFromCache( cache ) {
  10098. const values = [];
  10099. for ( const key in cache ) {
  10100. const data = cache[ key ];
  10101. delete data.metadata;
  10102. values.push( data );
  10103. }
  10104. return values;
  10105. }
  10106. }
  10107. /**
  10108. * Returns a new 3D object with copied values from this instance.
  10109. *
  10110. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  10111. * @return {Object3D} A clone of this instance.
  10112. */
  10113. clone( recursive ) {
  10114. return new this.constructor().copy( this, recursive );
  10115. }
  10116. /**
  10117. * Copies the values of the given 3D object to this instance.
  10118. *
  10119. * @param {Object3D} source - The 3D object to copy.
  10120. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  10121. * @return {Object3D} A reference to this instance.
  10122. */
  10123. copy( source, recursive = true ) {
  10124. this.name = source.name;
  10125. this.up.copy( source.up );
  10126. this.position.copy( source.position );
  10127. this.rotation.order = source.rotation.order;
  10128. this.quaternion.copy( source.quaternion );
  10129. this.scale.copy( source.scale );
  10130. this.pivot = ( source.pivot !== null ) ? source.pivot.clone() : null;
  10131. this.matrix.copy( source.matrix );
  10132. this.matrixWorld.copy( source.matrixWorld );
  10133. this.matrixAutoUpdate = source.matrixAutoUpdate;
  10134. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  10135. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10136. this.layers.mask = source.layers.mask;
  10137. this.visible = source.visible;
  10138. this.castShadow = source.castShadow;
  10139. this.receiveShadow = source.receiveShadow;
  10140. this.frustumCulled = source.frustumCulled;
  10141. this.renderOrder = source.renderOrder;
  10142. this.static = source.static;
  10143. this.animations = source.animations.slice();
  10144. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10145. if ( recursive === true ) {
  10146. for ( let i = 0; i < source.children.length; i ++ ) {
  10147. const child = source.children[ i ];
  10148. this.add( child.clone() );
  10149. }
  10150. }
  10151. return this;
  10152. }
  10153. }
  10154. /**
  10155. * The default up direction for objects, also used as the default
  10156. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  10157. *
  10158. * @static
  10159. * @type {Vector3}
  10160. * @default (0,1,0)
  10161. */
  10162. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10163. /**
  10164. * The default setting for {@link Object3D#matrixAutoUpdate} for
  10165. * newly created 3D objects.
  10166. *
  10167. * @static
  10168. * @type {boolean}
  10169. * @default true
  10170. */
  10171. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  10172. /**
  10173. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  10174. * newly created 3D objects.
  10175. *
  10176. * @static
  10177. * @type {boolean}
  10178. * @default true
  10179. */
  10180. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  10181. /**
  10182. * This is almost identical to an {@link Object3D}. Its purpose is to
  10183. * make working with groups of objects syntactically clearer.
  10184. *
  10185. * ```js
  10186. * // Create a group and add the two cubes.
  10187. * // These cubes can now be rotated / scaled etc as a group.
  10188. * const group = new THREE.Group();
  10189. *
  10190. * group.add( meshA );
  10191. * group.add( meshB );
  10192. *
  10193. * scene.add( group );
  10194. * ```
  10195. *
  10196. * @augments Object3D
  10197. */
  10198. class Group extends Object3D {
  10199. constructor() {
  10200. super();
  10201. /**
  10202. * This flag can be used for type testing.
  10203. *
  10204. * @type {boolean}
  10205. * @readonly
  10206. * @default true
  10207. */
  10208. this.isGroup = true;
  10209. this.type = 'Group';
  10210. }
  10211. }
  10212. const _moveEvent = { type: 'move' };
  10213. /**
  10214. * Class for representing a XR controller with its
  10215. * different coordinate systems.
  10216. *
  10217. * @private
  10218. */
  10219. class WebXRController {
  10220. /**
  10221. * Constructs a new XR controller.
  10222. */
  10223. constructor() {
  10224. /**
  10225. * A group representing the target ray space
  10226. * of the XR controller.
  10227. *
  10228. * @private
  10229. * @type {?Group}
  10230. * @default null
  10231. */
  10232. this._targetRay = null;
  10233. /**
  10234. * A group representing the grip space
  10235. * of the XR controller.
  10236. *
  10237. * @private
  10238. * @type {?Group}
  10239. * @default null
  10240. */
  10241. this._grip = null;
  10242. /**
  10243. * A group representing the hand space
  10244. * of the XR controller.
  10245. *
  10246. * @private
  10247. * @type {?Group}
  10248. * @default null
  10249. */
  10250. this._hand = null;
  10251. }
  10252. /**
  10253. * Returns a group representing the hand space of the XR controller.
  10254. *
  10255. * @return {Group} A group representing the hand space of the XR controller.
  10256. */
  10257. getHandSpace() {
  10258. if ( this._hand === null ) {
  10259. this._hand = new Group();
  10260. this._hand.matrixAutoUpdate = false;
  10261. this._hand.visible = false;
  10262. this._hand.joints = {};
  10263. this._hand.inputState = { pinching: false };
  10264. }
  10265. return this._hand;
  10266. }
  10267. /**
  10268. * Returns a group representing the target ray space of the XR controller.
  10269. *
  10270. * @return {Group} A group representing the target ray space of the XR controller.
  10271. */
  10272. getTargetRaySpace() {
  10273. if ( this._targetRay === null ) {
  10274. this._targetRay = new Group();
  10275. this._targetRay.matrixAutoUpdate = false;
  10276. this._targetRay.visible = false;
  10277. this._targetRay.hasLinearVelocity = false;
  10278. this._targetRay.linearVelocity = new Vector3();
  10279. this._targetRay.hasAngularVelocity = false;
  10280. this._targetRay.angularVelocity = new Vector3();
  10281. }
  10282. return this._targetRay;
  10283. }
  10284. /**
  10285. * Returns a group representing the grip space of the XR controller.
  10286. *
  10287. * @return {Group} A group representing the grip space of the XR controller.
  10288. */
  10289. getGripSpace() {
  10290. if ( this._grip === null ) {
  10291. this._grip = new Group();
  10292. this._grip.matrixAutoUpdate = false;
  10293. this._grip.visible = false;
  10294. this._grip.hasLinearVelocity = false;
  10295. this._grip.linearVelocity = new Vector3();
  10296. this._grip.hasAngularVelocity = false;
  10297. this._grip.angularVelocity = new Vector3();
  10298. this._grip.eventsEnabled = false;
  10299. }
  10300. return this._grip;
  10301. }
  10302. /**
  10303. * Dispatches the given event to the groups representing
  10304. * the different coordinate spaces of the XR controller.
  10305. *
  10306. * @param {Object} event - The event to dispatch.
  10307. * @return {WebXRController} A reference to this instance.
  10308. */
  10309. dispatchEvent( event ) {
  10310. if ( this._targetRay !== null ) {
  10311. this._targetRay.dispatchEvent( event );
  10312. }
  10313. if ( this._grip !== null ) {
  10314. this._grip.dispatchEvent( event );
  10315. }
  10316. if ( this._hand !== null ) {
  10317. this._hand.dispatchEvent( event );
  10318. }
  10319. return this;
  10320. }
  10321. /**
  10322. * Connects the controller with the given XR input source.
  10323. *
  10324. * @param {XRInputSource} inputSource - The input source.
  10325. * @return {WebXRController} A reference to this instance.
  10326. */
  10327. connect( inputSource ) {
  10328. if ( inputSource && inputSource.hand ) {
  10329. const hand = this._hand;
  10330. if ( hand ) {
  10331. for ( const inputjoint of inputSource.hand.values() ) {
  10332. // Initialize hand with joints when connected
  10333. this._getHandJoint( hand, inputjoint );
  10334. }
  10335. }
  10336. }
  10337. this.dispatchEvent( { type: 'connected', data: inputSource } );
  10338. return this;
  10339. }
  10340. /**
  10341. * Disconnects the controller from the given XR input source.
  10342. *
  10343. * @param {XRInputSource} inputSource - The input source.
  10344. * @return {WebXRController} A reference to this instance.
  10345. */
  10346. disconnect( inputSource ) {
  10347. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  10348. if ( this._targetRay !== null ) {
  10349. this._targetRay.visible = false;
  10350. }
  10351. if ( this._grip !== null ) {
  10352. this._grip.visible = false;
  10353. }
  10354. if ( this._hand !== null ) {
  10355. this._hand.visible = false;
  10356. }
  10357. return this;
  10358. }
  10359. /**
  10360. * Updates the controller with the given input source, XR frame and reference space.
  10361. * This updates the transformations of the groups that represent the different
  10362. * coordinate systems of the controller.
  10363. *
  10364. * @param {XRInputSource} inputSource - The input source.
  10365. * @param {XRFrame} frame - The XR frame.
  10366. * @param {XRReferenceSpace} referenceSpace - The reference space.
  10367. * @return {WebXRController} A reference to this instance.
  10368. */
  10369. update( inputSource, frame, referenceSpace ) {
  10370. let inputPose = null;
  10371. let gripPose = null;
  10372. let handPose = null;
  10373. const targetRay = this._targetRay;
  10374. const grip = this._grip;
  10375. const hand = this._hand;
  10376. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  10377. if ( hand && inputSource.hand ) {
  10378. handPose = true;
  10379. for ( const inputjoint of inputSource.hand.values() ) {
  10380. // Update the joints groups with the XRJoint poses
  10381. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  10382. // The transform of this joint will be updated with the joint pose on each frame
  10383. const joint = this._getHandJoint( hand, inputjoint );
  10384. if ( jointPose !== null ) {
  10385. joint.matrix.fromArray( jointPose.transform.matrix );
  10386. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  10387. joint.matrixWorldNeedsUpdate = true;
  10388. joint.jointRadius = jointPose.radius;
  10389. }
  10390. joint.visible = jointPose !== null;
  10391. }
  10392. // Custom events
  10393. // Check pinchz
  10394. const indexTip = hand.joints[ 'index-finger-tip' ];
  10395. const thumbTip = hand.joints[ 'thumb-tip' ];
  10396. const distance = indexTip.position.distanceTo( thumbTip.position );
  10397. const distanceToPinch = 0.02;
  10398. const threshold = 0.005;
  10399. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  10400. hand.inputState.pinching = false;
  10401. this.dispatchEvent( {
  10402. type: 'pinchend',
  10403. handedness: inputSource.handedness,
  10404. target: this
  10405. } );
  10406. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  10407. hand.inputState.pinching = true;
  10408. this.dispatchEvent( {
  10409. type: 'pinchstart',
  10410. handedness: inputSource.handedness,
  10411. target: this
  10412. } );
  10413. }
  10414. } else {
  10415. if ( grip !== null && inputSource.gripSpace ) {
  10416. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  10417. if ( gripPose !== null ) {
  10418. grip.matrix.fromArray( gripPose.transform.matrix );
  10419. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  10420. grip.matrixWorldNeedsUpdate = true;
  10421. if ( gripPose.linearVelocity ) {
  10422. grip.hasLinearVelocity = true;
  10423. grip.linearVelocity.copy( gripPose.linearVelocity );
  10424. } else {
  10425. grip.hasLinearVelocity = false;
  10426. }
  10427. if ( gripPose.angularVelocity ) {
  10428. grip.hasAngularVelocity = true;
  10429. grip.angularVelocity.copy( gripPose.angularVelocity );
  10430. } else {
  10431. grip.hasAngularVelocity = false;
  10432. }
  10433. // grip update event if enabled
  10434. if ( grip.eventsEnabled ) {
  10435. grip.dispatchEvent( {
  10436. type: 'gripUpdated',
  10437. data: inputSource,
  10438. target: this
  10439. } );
  10440. }
  10441. }
  10442. }
  10443. }
  10444. if ( targetRay !== null ) {
  10445. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  10446. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  10447. if ( inputPose === null && gripPose !== null ) {
  10448. inputPose = gripPose;
  10449. }
  10450. if ( inputPose !== null ) {
  10451. targetRay.matrix.fromArray( inputPose.transform.matrix );
  10452. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  10453. targetRay.matrixWorldNeedsUpdate = true;
  10454. if ( inputPose.linearVelocity ) {
  10455. targetRay.hasLinearVelocity = true;
  10456. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  10457. } else {
  10458. targetRay.hasLinearVelocity = false;
  10459. }
  10460. if ( inputPose.angularVelocity ) {
  10461. targetRay.hasAngularVelocity = true;
  10462. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  10463. } else {
  10464. targetRay.hasAngularVelocity = false;
  10465. }
  10466. this.dispatchEvent( _moveEvent );
  10467. }
  10468. }
  10469. }
  10470. if ( targetRay !== null ) {
  10471. targetRay.visible = ( inputPose !== null );
  10472. }
  10473. if ( grip !== null ) {
  10474. grip.visible = ( gripPose !== null );
  10475. }
  10476. if ( hand !== null ) {
  10477. hand.visible = ( handPose !== null );
  10478. }
  10479. return this;
  10480. }
  10481. /**
  10482. * Returns a group representing the hand joint for the given input joint.
  10483. *
  10484. * @private
  10485. * @param {Group} hand - The group representing the hand space.
  10486. * @param {XRJointSpace} inputjoint - The hand joint data.
  10487. * @return {Group} A group representing the hand joint for the given input joint.
  10488. */
  10489. _getHandJoint( hand, inputjoint ) {
  10490. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  10491. const joint = new Group();
  10492. joint.matrixAutoUpdate = false;
  10493. joint.visible = false;
  10494. hand.joints[ inputjoint.jointName ] = joint;
  10495. hand.add( joint );
  10496. }
  10497. return hand.joints[ inputjoint.jointName ];
  10498. }
  10499. }
  10500. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  10501. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  10502. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  10503. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  10504. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  10505. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  10506. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  10507. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  10508. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  10509. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  10510. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  10511. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  10512. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  10513. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  10514. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  10515. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  10516. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  10517. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  10518. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  10519. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  10520. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  10521. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  10522. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  10523. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  10524. const _hslA = { h: 0, s: 0, l: 0 };
  10525. const _hslB = { h: 0, s: 0, l: 0 };
  10526. function hue2rgb( p, q, t ) {
  10527. if ( t < 0 ) t += 1;
  10528. if ( t > 1 ) t -= 1;
  10529. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  10530. if ( t < 1 / 2 ) return q;
  10531. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  10532. return p;
  10533. }
  10534. /**
  10535. * A Color instance is represented by RGB components in the linear <i>working
  10536. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  10537. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  10538. * strings) are converted to the working color space automatically.
  10539. *
  10540. * ```js
  10541. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  10542. * const color = new THREE.Color().setHex( 0x112233 );
  10543. * ```
  10544. * Source color spaces may be specified explicitly, to ensure correct conversions.
  10545. * ```js
  10546. * // assumed already LinearSRGBColorSpace; no conversion
  10547. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  10548. *
  10549. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  10550. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  10551. * ```
  10552. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  10553. * see <i>Color management</i>. Iterating through a Color instance will yield
  10554. * its components (r, g, b) in the corresponding order. A Color can be initialised
  10555. * in any of the following ways:
  10556. * ```js
  10557. * //empty constructor - will default white
  10558. * const color1 = new THREE.Color();
  10559. *
  10560. * //Hexadecimal color (recommended)
  10561. * const color2 = new THREE.Color( 0xff0000 );
  10562. *
  10563. * //RGB string
  10564. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  10565. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  10566. *
  10567. * //X11 color name - all 140 color names are supported.
  10568. * //Note the lack of CamelCase in the name
  10569. * const color5 = new THREE.Color( 'skyblue' );
  10570. * //HSL string
  10571. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  10572. *
  10573. * //Separate RGB values between 0 and 1
  10574. * const color7 = new THREE.Color( 1, 0, 0 );
  10575. * ```
  10576. */
  10577. class Color {
  10578. /**
  10579. * Constructs a new color.
  10580. *
  10581. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  10582. * and that method is used throughout the rest of the documentation.
  10583. *
  10584. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10585. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10586. * @param {number} [g] - The green component.
  10587. * @param {number} [b] - The blue component.
  10588. */
  10589. constructor( r, g, b ) {
  10590. /**
  10591. * This flag can be used for type testing.
  10592. *
  10593. * @type {boolean}
  10594. * @readonly
  10595. * @default true
  10596. */
  10597. this.isColor = true;
  10598. /**
  10599. * The red component.
  10600. *
  10601. * @type {number}
  10602. * @default 1
  10603. */
  10604. this.r = 1;
  10605. /**
  10606. * The green component.
  10607. *
  10608. * @type {number}
  10609. * @default 1
  10610. */
  10611. this.g = 1;
  10612. /**
  10613. * The blue component.
  10614. *
  10615. * @type {number}
  10616. * @default 1
  10617. */
  10618. this.b = 1;
  10619. return this.set( r, g, b );
  10620. }
  10621. /**
  10622. * Sets the colors's components from the given values.
  10623. *
  10624. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  10625. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  10626. * @param {number} [g] - The green component.
  10627. * @param {number} [b] - The blue component.
  10628. * @return {Color} A reference to this color.
  10629. */
  10630. set( r, g, b ) {
  10631. if ( g === undefined && b === undefined ) {
  10632. // r is THREE.Color, hex or string
  10633. const value = r;
  10634. if ( value && value.isColor ) {
  10635. this.copy( value );
  10636. } else if ( typeof value === 'number' ) {
  10637. this.setHex( value );
  10638. } else if ( typeof value === 'string' ) {
  10639. this.setStyle( value );
  10640. }
  10641. } else {
  10642. this.setRGB( r, g, b );
  10643. }
  10644. return this;
  10645. }
  10646. /**
  10647. * Sets the colors's components to the given scalar value.
  10648. *
  10649. * @param {number} scalar - The scalar value.
  10650. * @return {Color} A reference to this color.
  10651. */
  10652. setScalar( scalar ) {
  10653. this.r = scalar;
  10654. this.g = scalar;
  10655. this.b = scalar;
  10656. return this;
  10657. }
  10658. /**
  10659. * Sets this color from a hexadecimal value.
  10660. *
  10661. * @param {number} hex - The hexadecimal value.
  10662. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10663. * @return {Color} A reference to this color.
  10664. */
  10665. setHex( hex, colorSpace = SRGBColorSpace ) {
  10666. hex = Math.floor( hex );
  10667. this.r = ( hex >> 16 & 255 ) / 255;
  10668. this.g = ( hex >> 8 & 255 ) / 255;
  10669. this.b = ( hex & 255 ) / 255;
  10670. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10671. return this;
  10672. }
  10673. /**
  10674. * Sets this color from RGB values.
  10675. *
  10676. * @param {number} r - Red channel value between `0.0` and `1.0`.
  10677. * @param {number} g - Green channel value between `0.0` and `1.0`.
  10678. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  10679. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10680. * @return {Color} A reference to this color.
  10681. */
  10682. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  10683. this.r = r;
  10684. this.g = g;
  10685. this.b = b;
  10686. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10687. return this;
  10688. }
  10689. /**
  10690. * Sets this color from RGB values.
  10691. *
  10692. * @param {number} h - Hue value between `0.0` and `1.0`.
  10693. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10694. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10695. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10696. * @return {Color} A reference to this color.
  10697. */
  10698. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  10699. // h,s,l ranges are in 0.0 - 1.0
  10700. h = euclideanModulo( h, 1 );
  10701. s = clamp( s, 0, 1 );
  10702. l = clamp( l, 0, 1 );
  10703. if ( s === 0 ) {
  10704. this.r = this.g = this.b = l;
  10705. } else {
  10706. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  10707. const q = ( 2 * l ) - p;
  10708. this.r = hue2rgb( q, p, h + 1 / 3 );
  10709. this.g = hue2rgb( q, p, h );
  10710. this.b = hue2rgb( q, p, h - 1 / 3 );
  10711. }
  10712. ColorManagement.colorSpaceToWorking( this, colorSpace );
  10713. return this;
  10714. }
  10715. /**
  10716. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  10717. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  10718. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  10719. * all 140 color names are supported).
  10720. *
  10721. * @param {string} style - Color as a CSS-style string.
  10722. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10723. * @return {Color} A reference to this color.
  10724. */
  10725. setStyle( style, colorSpace = SRGBColorSpace ) {
  10726. function handleAlpha( string ) {
  10727. if ( string === undefined ) return;
  10728. if ( parseFloat( string ) < 1 ) {
  10729. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  10730. }
  10731. }
  10732. let m;
  10733. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  10734. // rgb / hsl
  10735. let color;
  10736. const name = m[ 1 ];
  10737. const components = m[ 2 ];
  10738. switch ( name ) {
  10739. case 'rgb':
  10740. case 'rgba':
  10741. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10742. // rgb(255,0,0) rgba(255,0,0,0.5)
  10743. handleAlpha( color[ 4 ] );
  10744. return this.setRGB(
  10745. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  10746. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  10747. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  10748. colorSpace
  10749. );
  10750. }
  10751. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10752. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  10753. handleAlpha( color[ 4 ] );
  10754. return this.setRGB(
  10755. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  10756. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  10757. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  10758. colorSpace
  10759. );
  10760. }
  10761. break;
  10762. case 'hsl':
  10763. case 'hsla':
  10764. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  10765. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  10766. handleAlpha( color[ 4 ] );
  10767. return this.setHSL(
  10768. parseFloat( color[ 1 ] ) / 360,
  10769. parseFloat( color[ 2 ] ) / 100,
  10770. parseFloat( color[ 3 ] ) / 100,
  10771. colorSpace
  10772. );
  10773. }
  10774. break;
  10775. default:
  10776. warn( 'Color: Unknown color model ' + style );
  10777. }
  10778. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  10779. // hex color
  10780. const hex = m[ 1 ];
  10781. const size = hex.length;
  10782. if ( size === 3 ) {
  10783. // #ff0
  10784. return this.setRGB(
  10785. parseInt( hex.charAt( 0 ), 16 ) / 15,
  10786. parseInt( hex.charAt( 1 ), 16 ) / 15,
  10787. parseInt( hex.charAt( 2 ), 16 ) / 15,
  10788. colorSpace
  10789. );
  10790. } else if ( size === 6 ) {
  10791. // #ff0000
  10792. return this.setHex( parseInt( hex, 16 ), colorSpace );
  10793. } else {
  10794. warn( 'Color: Invalid hex color ' + style );
  10795. }
  10796. } else if ( style && style.length > 0 ) {
  10797. return this.setColorName( style, colorSpace );
  10798. }
  10799. return this;
  10800. }
  10801. /**
  10802. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  10803. * you don't need the other CSS-style formats.
  10804. *
  10805. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  10806. * ```js
  10807. * Color.NAMES.aliceblue // returns 0xF0F8FF
  10808. * ```
  10809. *
  10810. * @param {string} style - The color name.
  10811. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10812. * @return {Color} A reference to this color.
  10813. */
  10814. setColorName( style, colorSpace = SRGBColorSpace ) {
  10815. // color keywords
  10816. const hex = _colorKeywords[ style.toLowerCase() ];
  10817. if ( hex !== undefined ) {
  10818. // red
  10819. this.setHex( hex, colorSpace );
  10820. } else {
  10821. // unknown color
  10822. warn( 'Color: Unknown color ' + style );
  10823. }
  10824. return this;
  10825. }
  10826. /**
  10827. * Returns a new color with copied values from this instance.
  10828. *
  10829. * @return {Color} A clone of this instance.
  10830. */
  10831. clone() {
  10832. return new this.constructor( this.r, this.g, this.b );
  10833. }
  10834. /**
  10835. * Copies the values of the given color to this instance.
  10836. *
  10837. * @param {Color} color - The color to copy.
  10838. * @return {Color} A reference to this color.
  10839. */
  10840. copy( color ) {
  10841. this.r = color.r;
  10842. this.g = color.g;
  10843. this.b = color.b;
  10844. return this;
  10845. }
  10846. /**
  10847. * Copies the given color into this color, and then converts this color from
  10848. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10849. *
  10850. * @param {Color} color - The color to copy/convert.
  10851. * @return {Color} A reference to this color.
  10852. */
  10853. copySRGBToLinear( color ) {
  10854. this.r = SRGBToLinear( color.r );
  10855. this.g = SRGBToLinear( color.g );
  10856. this.b = SRGBToLinear( color.b );
  10857. return this;
  10858. }
  10859. /**
  10860. * Copies the given color into this color, and then converts this color from
  10861. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10862. *
  10863. * @param {Color} color - The color to copy/convert.
  10864. * @return {Color} A reference to this color.
  10865. */
  10866. copyLinearToSRGB( color ) {
  10867. this.r = LinearToSRGB( color.r );
  10868. this.g = LinearToSRGB( color.g );
  10869. this.b = LinearToSRGB( color.b );
  10870. return this;
  10871. }
  10872. /**
  10873. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  10874. *
  10875. * @return {Color} A reference to this color.
  10876. */
  10877. convertSRGBToLinear() {
  10878. this.copySRGBToLinear( this );
  10879. return this;
  10880. }
  10881. /**
  10882. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  10883. *
  10884. * @return {Color} A reference to this color.
  10885. */
  10886. convertLinearToSRGB() {
  10887. this.copyLinearToSRGB( this );
  10888. return this;
  10889. }
  10890. /**
  10891. * Returns the hexadecimal value of this color.
  10892. *
  10893. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10894. * @return {number} The hexadecimal value.
  10895. */
  10896. getHex( colorSpace = SRGBColorSpace ) {
  10897. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10898. 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 ) );
  10899. }
  10900. /**
  10901. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  10902. *
  10903. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10904. * @return {string} The hexadecimal value as a string.
  10905. */
  10906. getHexString( colorSpace = SRGBColorSpace ) {
  10907. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  10908. }
  10909. /**
  10910. * Converts the colors RGB values into the HSL format and stores them into the
  10911. * given target object.
  10912. *
  10913. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  10914. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10915. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  10916. */
  10917. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  10918. // h,s,l ranges are in 0.0 - 1.0
  10919. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10920. const r = _color.r, g = _color.g, b = _color.b;
  10921. const max = Math.max( r, g, b );
  10922. const min = Math.min( r, g, b );
  10923. let hue, saturation;
  10924. const lightness = ( min + max ) / 2.0;
  10925. if ( min === max ) {
  10926. hue = 0;
  10927. saturation = 0;
  10928. } else {
  10929. const delta = max - min;
  10930. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  10931. switch ( max ) {
  10932. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  10933. case g: hue = ( b - r ) / delta + 2; break;
  10934. case b: hue = ( r - g ) / delta + 4; break;
  10935. }
  10936. hue /= 6;
  10937. }
  10938. target.h = hue;
  10939. target.s = saturation;
  10940. target.l = lightness;
  10941. return target;
  10942. }
  10943. /**
  10944. * Returns the RGB values of this color and stores them into the given target object.
  10945. *
  10946. * @param {Color} target - The target color that is used to store the method's result.
  10947. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  10948. * @return {Color} The RGB representation of this color.
  10949. */
  10950. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  10951. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10952. target.r = _color.r;
  10953. target.g = _color.g;
  10954. target.b = _color.b;
  10955. return target;
  10956. }
  10957. /**
  10958. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  10959. *
  10960. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  10961. * @return {string} The CSS representation of this color.
  10962. */
  10963. getStyle( colorSpace = SRGBColorSpace ) {
  10964. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  10965. const r = _color.r, g = _color.g, b = _color.b;
  10966. if ( colorSpace !== SRGBColorSpace ) {
  10967. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  10968. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  10969. }
  10970. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  10971. }
  10972. /**
  10973. * Adds the given HSL values to this color's values.
  10974. * Internally, this converts the color's RGB values to HSL, adds HSL
  10975. * and then converts the color back to RGB.
  10976. *
  10977. * @param {number} h - Hue value between `0.0` and `1.0`.
  10978. * @param {number} s - Saturation value between `0.0` and `1.0`.
  10979. * @param {number} l - Lightness value between `0.0` and `1.0`.
  10980. * @return {Color} A reference to this color.
  10981. */
  10982. offsetHSL( h, s, l ) {
  10983. this.getHSL( _hslA );
  10984. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  10985. }
  10986. /**
  10987. * Adds the RGB values of the given color to the RGB values of this color.
  10988. *
  10989. * @param {Color} color - The color to add.
  10990. * @return {Color} A reference to this color.
  10991. */
  10992. add( color ) {
  10993. this.r += color.r;
  10994. this.g += color.g;
  10995. this.b += color.b;
  10996. return this;
  10997. }
  10998. /**
  10999. * Adds the RGB values of the given colors and stores the result in this instance.
  11000. *
  11001. * @param {Color} color1 - The first color.
  11002. * @param {Color} color2 - The second color.
  11003. * @return {Color} A reference to this color.
  11004. */
  11005. addColors( color1, color2 ) {
  11006. this.r = color1.r + color2.r;
  11007. this.g = color1.g + color2.g;
  11008. this.b = color1.b + color2.b;
  11009. return this;
  11010. }
  11011. /**
  11012. * Adds the given scalar value to the RGB values of this color.
  11013. *
  11014. * @param {number} s - The scalar to add.
  11015. * @return {Color} A reference to this color.
  11016. */
  11017. addScalar( s ) {
  11018. this.r += s;
  11019. this.g += s;
  11020. this.b += s;
  11021. return this;
  11022. }
  11023. /**
  11024. * Subtracts the RGB values of the given color from the RGB values of this color.
  11025. *
  11026. * @param {Color} color - The color to subtract.
  11027. * @return {Color} A reference to this color.
  11028. */
  11029. sub( color ) {
  11030. this.r = Math.max( 0, this.r - color.r );
  11031. this.g = Math.max( 0, this.g - color.g );
  11032. this.b = Math.max( 0, this.b - color.b );
  11033. return this;
  11034. }
  11035. /**
  11036. * Multiplies the RGB values of the given color with the RGB values of this color.
  11037. *
  11038. * @param {Color} color - The color to multiply.
  11039. * @return {Color} A reference to this color.
  11040. */
  11041. multiply( color ) {
  11042. this.r *= color.r;
  11043. this.g *= color.g;
  11044. this.b *= color.b;
  11045. return this;
  11046. }
  11047. /**
  11048. * Multiplies the given scalar value with the RGB values of this color.
  11049. *
  11050. * @param {number} s - The scalar to multiply.
  11051. * @return {Color} A reference to this color.
  11052. */
  11053. multiplyScalar( s ) {
  11054. this.r *= s;
  11055. this.g *= s;
  11056. this.b *= s;
  11057. return this;
  11058. }
  11059. /**
  11060. * Linearly interpolates this color's RGB values toward the RGB values of the
  11061. * given color. The alpha argument can be thought of as the ratio between
  11062. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  11063. *
  11064. * @param {Color} color - The color to converge on.
  11065. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11066. * @return {Color} A reference to this color.
  11067. */
  11068. lerp( color, alpha ) {
  11069. this.r += ( color.r - this.r ) * alpha;
  11070. this.g += ( color.g - this.g ) * alpha;
  11071. this.b += ( color.b - this.b ) * alpha;
  11072. return this;
  11073. }
  11074. /**
  11075. * Linearly interpolates between the given colors and stores the result in this instance.
  11076. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  11077. * is the first and `1.0` is the second color.
  11078. *
  11079. * @param {Color} color1 - The first color.
  11080. * @param {Color} color2 - The second color.
  11081. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11082. * @return {Color} A reference to this color.
  11083. */
  11084. lerpColors( color1, color2, alpha ) {
  11085. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  11086. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  11087. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  11088. return this;
  11089. }
  11090. /**
  11091. * Linearly interpolates this color's HSL values toward the HSL values of the
  11092. * given color. It differs from {@link Color#lerp} by not interpolating straight
  11093. * from one color to the other, but instead going through all the hues in between
  11094. * those two colors. The alpha argument can be thought of as the ratio between
  11095. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  11096. *
  11097. * @param {Color} color - The color to converge on.
  11098. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  11099. * @return {Color} A reference to this color.
  11100. */
  11101. lerpHSL( color, alpha ) {
  11102. this.getHSL( _hslA );
  11103. color.getHSL( _hslB );
  11104. const h = lerp( _hslA.h, _hslB.h, alpha );
  11105. const s = lerp( _hslA.s, _hslB.s, alpha );
  11106. const l = lerp( _hslA.l, _hslB.l, alpha );
  11107. this.setHSL( h, s, l );
  11108. return this;
  11109. }
  11110. /**
  11111. * Sets the color's RGB components from the given 3D vector.
  11112. *
  11113. * @param {Vector3} v - The vector to set.
  11114. * @return {Color} A reference to this color.
  11115. */
  11116. setFromVector3( v ) {
  11117. this.r = v.x;
  11118. this.g = v.y;
  11119. this.b = v.z;
  11120. return this;
  11121. }
  11122. /**
  11123. * Transforms this color with the given 3x3 matrix.
  11124. *
  11125. * @param {Matrix3} m - The matrix.
  11126. * @return {Color} A reference to this color.
  11127. */
  11128. applyMatrix3( m ) {
  11129. const r = this.r, g = this.g, b = this.b;
  11130. const e = m.elements;
  11131. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  11132. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  11133. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  11134. return this;
  11135. }
  11136. /**
  11137. * Returns `true` if this color is equal with the given one.
  11138. *
  11139. * @param {Color} c - The color to test for equality.
  11140. * @return {boolean} Whether this bounding color is equal with the given one.
  11141. */
  11142. equals( c ) {
  11143. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  11144. }
  11145. /**
  11146. * Sets this color's RGB components from the given array.
  11147. *
  11148. * @param {Array<number>} array - An array holding the RGB values.
  11149. * @param {number} [offset=0] - The offset into the array.
  11150. * @return {Color} A reference to this color.
  11151. */
  11152. fromArray( array, offset = 0 ) {
  11153. this.r = array[ offset ];
  11154. this.g = array[ offset + 1 ];
  11155. this.b = array[ offset + 2 ];
  11156. return this;
  11157. }
  11158. /**
  11159. * Writes the RGB components of this color to the given array. If no array is provided,
  11160. * the method returns a new instance.
  11161. *
  11162. * @param {Array<number>} [array=[]] - The target array holding the color components.
  11163. * @param {number} [offset=0] - Index of the first element in the array.
  11164. * @return {Array<number>} The color components.
  11165. */
  11166. toArray( array = [], offset = 0 ) {
  11167. array[ offset ] = this.r;
  11168. array[ offset + 1 ] = this.g;
  11169. array[ offset + 2 ] = this.b;
  11170. return array;
  11171. }
  11172. /**
  11173. * Sets the components of this color from the given buffer attribute.
  11174. *
  11175. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  11176. * @param {number} index - The index into the attribute.
  11177. * @return {Color} A reference to this color.
  11178. */
  11179. fromBufferAttribute( attribute, index ) {
  11180. this.r = attribute.getX( index );
  11181. this.g = attribute.getY( index );
  11182. this.b = attribute.getZ( index );
  11183. return this;
  11184. }
  11185. /**
  11186. * This methods defines the serialization result of this class. Returns the color
  11187. * as a hexadecimal value.
  11188. *
  11189. * @return {number} The hexadecimal value.
  11190. */
  11191. toJSON() {
  11192. return this.getHex();
  11193. }
  11194. *[ Symbol.iterator ]() {
  11195. yield this.r;
  11196. yield this.g;
  11197. yield this.b;
  11198. }
  11199. }
  11200. const _color = /*@__PURE__*/ new Color();
  11201. /**
  11202. * A dictionary with X11 color names.
  11203. *
  11204. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  11205. *
  11206. * @static
  11207. * @type {Object}
  11208. */
  11209. Color.NAMES = _colorKeywords;
  11210. /**
  11211. * This class can be used to define an exponential squared fog,
  11212. * which gives a clear view near the camera and a faster than exponentially
  11213. * densening fog farther from the camera.
  11214. *
  11215. * ```js
  11216. * const scene = new THREE.Scene();
  11217. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  11218. * ```
  11219. */
  11220. class FogExp2 {
  11221. /**
  11222. * Constructs a new fog.
  11223. *
  11224. * @param {number|Color} color - The fog's color.
  11225. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  11226. */
  11227. constructor( color, density = 0.00025 ) {
  11228. /**
  11229. * This flag can be used for type testing.
  11230. *
  11231. * @type {boolean}
  11232. * @readonly
  11233. * @default true
  11234. */
  11235. this.isFogExp2 = true;
  11236. /**
  11237. * The name of the fog.
  11238. *
  11239. * @type {string}
  11240. */
  11241. this.name = '';
  11242. /**
  11243. * The fog's color.
  11244. *
  11245. * @type {Color}
  11246. */
  11247. this.color = new Color( color );
  11248. /**
  11249. * Defines how fast the fog will grow dense.
  11250. *
  11251. * @type {number}
  11252. * @default 0.00025
  11253. */
  11254. this.density = density;
  11255. }
  11256. /**
  11257. * Returns a new fog with copied values from this instance.
  11258. *
  11259. * @return {FogExp2} A clone of this instance.
  11260. */
  11261. clone() {
  11262. return new FogExp2( this.color, this.density );
  11263. }
  11264. /**
  11265. * Serializes the fog into JSON.
  11266. *
  11267. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11268. * @return {Object} A JSON object representing the serialized fog
  11269. */
  11270. toJSON( /* meta */ ) {
  11271. return {
  11272. type: 'FogExp2',
  11273. name: this.name,
  11274. color: this.color.getHex(),
  11275. density: this.density
  11276. };
  11277. }
  11278. }
  11279. /**
  11280. * This class can be used to define a linear fog that grows linearly denser
  11281. * with the distance.
  11282. *
  11283. * ```js
  11284. * const scene = new THREE.Scene();
  11285. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  11286. * ```
  11287. */
  11288. class Fog {
  11289. /**
  11290. * Constructs a new fog.
  11291. *
  11292. * @param {number|Color} color - The fog's color.
  11293. * @param {number} [near=1] - The minimum distance to start applying fog.
  11294. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  11295. */
  11296. constructor( color, near = 1, far = 1000 ) {
  11297. /**
  11298. * This flag can be used for type testing.
  11299. *
  11300. * @type {boolean}
  11301. * @readonly
  11302. * @default true
  11303. */
  11304. this.isFog = true;
  11305. /**
  11306. * The name of the fog.
  11307. *
  11308. * @type {string}
  11309. */
  11310. this.name = '';
  11311. /**
  11312. * The fog's color.
  11313. *
  11314. * @type {Color}
  11315. */
  11316. this.color = new Color( color );
  11317. /**
  11318. * The minimum distance to start applying fog. Objects that are less than
  11319. * `near` units from the active camera won't be affected by fog.
  11320. *
  11321. * @type {number}
  11322. * @default 1
  11323. */
  11324. this.near = near;
  11325. /**
  11326. * The maximum distance at which fog stops being calculated and applied.
  11327. * Objects that are more than `far` units away from the active camera won't
  11328. * be affected by fog.
  11329. *
  11330. * @type {number}
  11331. * @default 1000
  11332. */
  11333. this.far = far;
  11334. }
  11335. /**
  11336. * Returns a new fog with copied values from this instance.
  11337. *
  11338. * @return {Fog} A clone of this instance.
  11339. */
  11340. clone() {
  11341. return new Fog( this.color, this.near, this.far );
  11342. }
  11343. /**
  11344. * Serializes the fog into JSON.
  11345. *
  11346. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11347. * @return {Object} A JSON object representing the serialized fog
  11348. */
  11349. toJSON( /* meta */ ) {
  11350. return {
  11351. type: 'Fog',
  11352. name: this.name,
  11353. color: this.color.getHex(),
  11354. near: this.near,
  11355. far: this.far
  11356. };
  11357. }
  11358. }
  11359. /**
  11360. * Scenes allow you to set up what is to be rendered and where by three.js.
  11361. * This is where you place 3D objects like meshes, lines or lights.
  11362. *
  11363. * @augments Object3D
  11364. */
  11365. class Scene extends Object3D {
  11366. /**
  11367. * Constructs a new scene.
  11368. */
  11369. constructor() {
  11370. super();
  11371. /**
  11372. * This flag can be used for type testing.
  11373. *
  11374. * @type {boolean}
  11375. * @readonly
  11376. * @default true
  11377. */
  11378. this.isScene = true;
  11379. this.type = 'Scene';
  11380. /**
  11381. * Defines the background of the scene. Valid inputs are:
  11382. *
  11383. * - A color for defining a uniform colored background.
  11384. * - A texture for defining a (flat) textured background.
  11385. * - Cube textures or equirectangular textures for defining a skybox.
  11386. *
  11387. * @type {?(Color|Texture)}
  11388. * @default null
  11389. */
  11390. this.background = null;
  11391. /**
  11392. * Sets the environment map for all physical materials in the scene. However,
  11393. * it's not possible to overwrite an existing texture assigned to the `envMap`
  11394. * material property.
  11395. *
  11396. * @type {?Texture}
  11397. * @default null
  11398. */
  11399. this.environment = null;
  11400. /**
  11401. * A fog instance defining the type of fog that affects everything
  11402. * rendered in the scene.
  11403. *
  11404. * @type {?(Fog|FogExp2)}
  11405. * @default null
  11406. */
  11407. this.fog = null;
  11408. /**
  11409. * Sets the blurriness of the background. Only influences environment maps
  11410. * assigned to {@link Scene#background}. Valid input is a float between `0`
  11411. * and `1`.
  11412. *
  11413. * @type {number}
  11414. * @default 0
  11415. */
  11416. this.backgroundBlurriness = 0;
  11417. /**
  11418. * Attenuates the color of the background. Only applies to background textures.
  11419. *
  11420. * @type {number}
  11421. * @default 1
  11422. */
  11423. this.backgroundIntensity = 1;
  11424. /**
  11425. * The rotation of the background in radians. Only influences environment maps
  11426. * assigned to {@link Scene#background}.
  11427. *
  11428. * @type {Euler}
  11429. * @default (0,0,0)
  11430. */
  11431. this.backgroundRotation = new Euler();
  11432. /**
  11433. * Attenuates the color of the environment. Only influences environment maps
  11434. * assigned to {@link Scene#environment}.
  11435. *
  11436. * @type {number}
  11437. * @default 1
  11438. */
  11439. this.environmentIntensity = 1;
  11440. /**
  11441. * The rotation of the environment map in radians. Only influences physical materials
  11442. * in the scene when {@link Scene#environment} is used.
  11443. *
  11444. * @type {Euler}
  11445. * @default (0,0,0)
  11446. */
  11447. this.environmentRotation = new Euler();
  11448. /**
  11449. * Forces everything in the scene to be rendered with the defined material. It is possible
  11450. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  11451. *
  11452. * @type {?Material}
  11453. * @default null
  11454. */
  11455. this.overrideMaterial = null;
  11456. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  11457. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  11458. }
  11459. }
  11460. copy( source, recursive ) {
  11461. super.copy( source, recursive );
  11462. if ( source.background !== null ) this.background = source.background.clone();
  11463. if ( source.environment !== null ) this.environment = source.environment.clone();
  11464. if ( source.fog !== null ) this.fog = source.fog.clone();
  11465. this.backgroundBlurriness = source.backgroundBlurriness;
  11466. this.backgroundIntensity = source.backgroundIntensity;
  11467. this.backgroundRotation.copy( source.backgroundRotation );
  11468. this.environmentIntensity = source.environmentIntensity;
  11469. this.environmentRotation.copy( source.environmentRotation );
  11470. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  11471. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11472. return this;
  11473. }
  11474. toJSON( meta ) {
  11475. const data = super.toJSON( meta );
  11476. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  11477. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  11478. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  11479. data.object.backgroundRotation = this.backgroundRotation.toArray();
  11480. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  11481. data.object.environmentRotation = this.environmentRotation.toArray();
  11482. return data;
  11483. }
  11484. }
  11485. const _v0$2 = /*@__PURE__*/ new Vector3();
  11486. const _v1$5 = /*@__PURE__*/ new Vector3();
  11487. const _v2$4 = /*@__PURE__*/ new Vector3();
  11488. const _v3$2 = /*@__PURE__*/ new Vector3();
  11489. const _vab = /*@__PURE__*/ new Vector3();
  11490. const _vac = /*@__PURE__*/ new Vector3();
  11491. const _vbc = /*@__PURE__*/ new Vector3();
  11492. const _vap = /*@__PURE__*/ new Vector3();
  11493. const _vbp = /*@__PURE__*/ new Vector3();
  11494. const _vcp = /*@__PURE__*/ new Vector3();
  11495. const _v40 = /*@__PURE__*/ new Vector4();
  11496. const _v41 = /*@__PURE__*/ new Vector4();
  11497. const _v42 = /*@__PURE__*/ new Vector4();
  11498. /**
  11499. * A geometric triangle as defined by three vectors representing its three corners.
  11500. */
  11501. class Triangle {
  11502. /**
  11503. * Constructs a new triangle.
  11504. *
  11505. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11506. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11507. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11508. */
  11509. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11510. /**
  11511. * The first corner of the triangle.
  11512. *
  11513. * @type {Vector3}
  11514. */
  11515. this.a = a;
  11516. /**
  11517. * The second corner of the triangle.
  11518. *
  11519. * @type {Vector3}
  11520. */
  11521. this.b = b;
  11522. /**
  11523. * The third corner of the triangle.
  11524. *
  11525. * @type {Vector3}
  11526. */
  11527. this.c = c;
  11528. }
  11529. /**
  11530. * Computes the normal vector of a triangle.
  11531. *
  11532. * @param {Vector3} a - The first corner of the triangle.
  11533. * @param {Vector3} b - The second corner of the triangle.
  11534. * @param {Vector3} c - The third corner of the triangle.
  11535. * @param {Vector3} target - The target vector that is used to store the method's result.
  11536. * @return {Vector3} The triangle's normal.
  11537. */
  11538. static getNormal( a, b, c, target ) {
  11539. target.subVectors( c, b );
  11540. _v0$2.subVectors( a, b );
  11541. target.cross( _v0$2 );
  11542. const targetLengthSq = target.lengthSq();
  11543. if ( targetLengthSq > 0 ) {
  11544. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11545. }
  11546. return target.set( 0, 0, 0 );
  11547. }
  11548. /**
  11549. * Computes a barycentric coordinates from the given vector.
  11550. * Returns `null` if the triangle is degenerate.
  11551. *
  11552. * @param {Vector3} point - A point in 3D space.
  11553. * @param {Vector3} a - The first corner of the triangle.
  11554. * @param {Vector3} b - The second corner of the triangle.
  11555. * @param {Vector3} c - The third corner of the triangle.
  11556. * @param {Vector3} target - The target vector that is used to store the method's result.
  11557. * @return {?Vector3} The barycentric coordinates for the given point
  11558. */
  11559. static getBarycoord( point, a, b, c, target ) {
  11560. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11561. _v0$2.subVectors( c, a );
  11562. _v1$5.subVectors( b, a );
  11563. _v2$4.subVectors( point, a );
  11564. const dot00 = _v0$2.dot( _v0$2 );
  11565. const dot01 = _v0$2.dot( _v1$5 );
  11566. const dot02 = _v0$2.dot( _v2$4 );
  11567. const dot11 = _v1$5.dot( _v1$5 );
  11568. const dot12 = _v1$5.dot( _v2$4 );
  11569. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11570. // collinear or singular triangle
  11571. if ( denom === 0 ) {
  11572. target.set( 0, 0, 0 );
  11573. return null;
  11574. }
  11575. const invDenom = 1 / denom;
  11576. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11577. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11578. // barycentric coordinates must always sum to 1
  11579. return target.set( 1 - u - v, v, u );
  11580. }
  11581. /**
  11582. * Returns `true` if the given point, when projected onto the plane of the
  11583. * triangle, lies within the triangle.
  11584. *
  11585. * @param {Vector3} point - The point in 3D space to test.
  11586. * @param {Vector3} a - The first corner of the triangle.
  11587. * @param {Vector3} b - The second corner of the triangle.
  11588. * @param {Vector3} c - The third corner of the triangle.
  11589. * @return {boolean} Whether the given point, when projected onto the plane of the
  11590. * triangle, lies within the triangle or not.
  11591. */
  11592. static containsPoint( point, a, b, c ) {
  11593. // if the triangle is degenerate then we can't contain a point
  11594. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11595. return false;
  11596. }
  11597. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11598. }
  11599. /**
  11600. * Computes the value barycentrically interpolated for the given point on the
  11601. * triangle. Returns `null` if the triangle is degenerate.
  11602. *
  11603. * @param {Vector3} point - Position of interpolated point.
  11604. * @param {Vector3} p1 - The first corner of the triangle.
  11605. * @param {Vector3} p2 - The second corner of the triangle.
  11606. * @param {Vector3} p3 - The third corner of the triangle.
  11607. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11608. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11609. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11610. * @param {Vector3} target - The target vector that is used to store the method's result.
  11611. * @return {?Vector3} The interpolated value.
  11612. */
  11613. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11614. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11615. target.x = 0;
  11616. target.y = 0;
  11617. if ( 'z' in target ) target.z = 0;
  11618. if ( 'w' in target ) target.w = 0;
  11619. return null;
  11620. }
  11621. target.setScalar( 0 );
  11622. target.addScaledVector( v1, _v3$2.x );
  11623. target.addScaledVector( v2, _v3$2.y );
  11624. target.addScaledVector( v3, _v3$2.z );
  11625. return target;
  11626. }
  11627. /**
  11628. * Computes the value barycentrically interpolated for the given attribute and indices.
  11629. *
  11630. * @param {BufferAttribute} attr - The attribute to interpolate.
  11631. * @param {number} i1 - Index of first vertex.
  11632. * @param {number} i2 - Index of second vertex.
  11633. * @param {number} i3 - Index of third vertex.
  11634. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11635. * @param {Vector3} target - The target vector that is used to store the method's result.
  11636. * @return {Vector3} The interpolated attribute value.
  11637. */
  11638. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11639. _v40.setScalar( 0 );
  11640. _v41.setScalar( 0 );
  11641. _v42.setScalar( 0 );
  11642. _v40.fromBufferAttribute( attr, i1 );
  11643. _v41.fromBufferAttribute( attr, i2 );
  11644. _v42.fromBufferAttribute( attr, i3 );
  11645. target.setScalar( 0 );
  11646. target.addScaledVector( _v40, barycoord.x );
  11647. target.addScaledVector( _v41, barycoord.y );
  11648. target.addScaledVector( _v42, barycoord.z );
  11649. return target;
  11650. }
  11651. /**
  11652. * Returns `true` if the triangle is oriented towards the given direction.
  11653. *
  11654. * @param {Vector3} a - The first corner of the triangle.
  11655. * @param {Vector3} b - The second corner of the triangle.
  11656. * @param {Vector3} c - The third corner of the triangle.
  11657. * @param {Vector3} direction - The (normalized) direction vector.
  11658. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11659. */
  11660. static isFrontFacing( a, b, c, direction ) {
  11661. _v0$2.subVectors( c, b );
  11662. _v1$5.subVectors( a, b );
  11663. // strictly front facing
  11664. return _v0$2.cross( _v1$5 ).dot( direction ) < 0;
  11665. }
  11666. /**
  11667. * Sets the triangle's vertices by copying the given values.
  11668. *
  11669. * @param {Vector3} a - The first corner of the triangle.
  11670. * @param {Vector3} b - The second corner of the triangle.
  11671. * @param {Vector3} c - The third corner of the triangle.
  11672. * @return {Triangle} A reference to this triangle.
  11673. */
  11674. set( a, b, c ) {
  11675. this.a.copy( a );
  11676. this.b.copy( b );
  11677. this.c.copy( c );
  11678. return this;
  11679. }
  11680. /**
  11681. * Sets the triangle's vertices by copying the given array values.
  11682. *
  11683. * @param {Array<Vector3>} points - An array with 3D points.
  11684. * @param {number} i0 - The array index representing the first corner of the triangle.
  11685. * @param {number} i1 - The array index representing the second corner of the triangle.
  11686. * @param {number} i2 - The array index representing the third corner of the triangle.
  11687. * @return {Triangle} A reference to this triangle.
  11688. */
  11689. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11690. this.a.copy( points[ i0 ] );
  11691. this.b.copy( points[ i1 ] );
  11692. this.c.copy( points[ i2 ] );
  11693. return this;
  11694. }
  11695. /**
  11696. * Sets the triangle's vertices by copying the given attribute values.
  11697. *
  11698. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11699. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11700. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11701. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11702. * @return {Triangle} A reference to this triangle.
  11703. */
  11704. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11705. this.a.fromBufferAttribute( attribute, i0 );
  11706. this.b.fromBufferAttribute( attribute, i1 );
  11707. this.c.fromBufferAttribute( attribute, i2 );
  11708. return this;
  11709. }
  11710. /**
  11711. * Returns a new triangle with copied values from this instance.
  11712. *
  11713. * @return {Triangle} A clone of this instance.
  11714. */
  11715. clone() {
  11716. return new this.constructor().copy( this );
  11717. }
  11718. /**
  11719. * Copies the values of the given triangle to this instance.
  11720. *
  11721. * @param {Triangle} triangle - The triangle to copy.
  11722. * @return {Triangle} A reference to this triangle.
  11723. */
  11724. copy( triangle ) {
  11725. this.a.copy( triangle.a );
  11726. this.b.copy( triangle.b );
  11727. this.c.copy( triangle.c );
  11728. return this;
  11729. }
  11730. /**
  11731. * Computes the area of the triangle.
  11732. *
  11733. * @return {number} The triangle's area.
  11734. */
  11735. getArea() {
  11736. _v0$2.subVectors( this.c, this.b );
  11737. _v1$5.subVectors( this.a, this.b );
  11738. return _v0$2.cross( _v1$5 ).length() * 0.5;
  11739. }
  11740. /**
  11741. * Computes the midpoint of the triangle.
  11742. *
  11743. * @param {Vector3} target - The target vector that is used to store the method's result.
  11744. * @return {Vector3} The triangle's midpoint.
  11745. */
  11746. getMidpoint( target ) {
  11747. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11748. }
  11749. /**
  11750. * Computes the normal of the triangle.
  11751. *
  11752. * @param {Vector3} target - The target vector that is used to store the method's result.
  11753. * @return {Vector3} The triangle's normal.
  11754. */
  11755. getNormal( target ) {
  11756. return Triangle.getNormal( this.a, this.b, this.c, target );
  11757. }
  11758. /**
  11759. * Computes a plane the triangle lies within.
  11760. *
  11761. * @param {Plane} target - The target vector that is used to store the method's result.
  11762. * @return {Plane} The plane the triangle lies within.
  11763. */
  11764. getPlane( target ) {
  11765. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11766. }
  11767. /**
  11768. * Computes a barycentric coordinates from the given vector.
  11769. * Returns `null` if the triangle is degenerate.
  11770. *
  11771. * @param {Vector3} point - A point in 3D space.
  11772. * @param {Vector3} target - The target vector that is used to store the method's result.
  11773. * @return {?Vector3} The barycentric coordinates for the given point
  11774. */
  11775. getBarycoord( point, target ) {
  11776. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11777. }
  11778. /**
  11779. * Computes the value barycentrically interpolated for the given point on the
  11780. * triangle. Returns `null` if the triangle is degenerate.
  11781. *
  11782. * @param {Vector3} point - Position of interpolated point.
  11783. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11784. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11785. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11786. * @param {Vector3} target - The target vector that is used to store the method's result.
  11787. * @return {?Vector3} The interpolated value.
  11788. */
  11789. getInterpolation( point, v1, v2, v3, target ) {
  11790. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11791. }
  11792. /**
  11793. * Returns `true` if the given point, when projected onto the plane of the
  11794. * triangle, lies within the triangle.
  11795. *
  11796. * @param {Vector3} point - The point in 3D space to test.
  11797. * @return {boolean} Whether the given point, when projected onto the plane of the
  11798. * triangle, lies within the triangle or not.
  11799. */
  11800. containsPoint( point ) {
  11801. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11802. }
  11803. /**
  11804. * Returns `true` if the triangle is oriented towards the given direction.
  11805. *
  11806. * @param {Vector3} direction - The (normalized) direction vector.
  11807. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11808. */
  11809. isFrontFacing( direction ) {
  11810. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11811. }
  11812. /**
  11813. * Returns `true` if this triangle intersects with the given box.
  11814. *
  11815. * @param {Box3} box - The box to intersect.
  11816. * @return {boolean} Whether this triangle intersects with the given box or not.
  11817. */
  11818. intersectsBox( box ) {
  11819. return box.intersectsTriangle( this );
  11820. }
  11821. /**
  11822. * Returns the closest point on the triangle to the given point.
  11823. *
  11824. * @param {Vector3} p - The point to compute the closest point for.
  11825. * @param {Vector3} target - The target vector that is used to store the method's result.
  11826. * @return {Vector3} The closest point on the triangle.
  11827. */
  11828. closestPointToPoint( p, target ) {
  11829. const a = this.a, b = this.b, c = this.c;
  11830. let v, w;
  11831. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11832. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11833. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11834. // basically, we're distinguishing which of the voronoi regions of the triangle
  11835. // the point lies in with the minimum amount of redundant computation.
  11836. _vab.subVectors( b, a );
  11837. _vac.subVectors( c, a );
  11838. _vap.subVectors( p, a );
  11839. const d1 = _vab.dot( _vap );
  11840. const d2 = _vac.dot( _vap );
  11841. if ( d1 <= 0 && d2 <= 0 ) {
  11842. // vertex region of A; barycentric coords (1, 0, 0)
  11843. return target.copy( a );
  11844. }
  11845. _vbp.subVectors( p, b );
  11846. const d3 = _vab.dot( _vbp );
  11847. const d4 = _vac.dot( _vbp );
  11848. if ( d3 >= 0 && d4 <= d3 ) {
  11849. // vertex region of B; barycentric coords (0, 1, 0)
  11850. return target.copy( b );
  11851. }
  11852. const vc = d1 * d4 - d3 * d2;
  11853. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11854. v = d1 / ( d1 - d3 );
  11855. // edge region of AB; barycentric coords (1-v, v, 0)
  11856. return target.copy( a ).addScaledVector( _vab, v );
  11857. }
  11858. _vcp.subVectors( p, c );
  11859. const d5 = _vab.dot( _vcp );
  11860. const d6 = _vac.dot( _vcp );
  11861. if ( d6 >= 0 && d5 <= d6 ) {
  11862. // vertex region of C; barycentric coords (0, 0, 1)
  11863. return target.copy( c );
  11864. }
  11865. const vb = d5 * d2 - d1 * d6;
  11866. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11867. w = d2 / ( d2 - d6 );
  11868. // edge region of AC; barycentric coords (1-w, 0, w)
  11869. return target.copy( a ).addScaledVector( _vac, w );
  11870. }
  11871. const va = d3 * d6 - d5 * d4;
  11872. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11873. _vbc.subVectors( c, b );
  11874. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11875. // edge region of BC; barycentric coords (0, 1-w, w)
  11876. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11877. }
  11878. // face region
  11879. const denom = 1 / ( va + vb + vc );
  11880. // u = va * denom
  11881. v = vb * denom;
  11882. w = vc * denom;
  11883. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11884. }
  11885. /**
  11886. * Returns `true` if this triangle is equal with the given one.
  11887. *
  11888. * @param {Triangle} triangle - The triangle to test for equality.
  11889. * @return {boolean} Whether this triangle is equal with the given one.
  11890. */
  11891. equals( triangle ) {
  11892. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11893. }
  11894. }
  11895. /**
  11896. * Represents an axis-aligned bounding box (AABB) in 3D space.
  11897. */
  11898. class Box3 {
  11899. /**
  11900. * Constructs a new bounding box.
  11901. *
  11902. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  11903. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  11904. */
  11905. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  11906. /**
  11907. * This flag can be used for type testing.
  11908. *
  11909. * @type {boolean}
  11910. * @readonly
  11911. * @default true
  11912. */
  11913. this.isBox3 = true;
  11914. /**
  11915. * The lower boundary of the box.
  11916. *
  11917. * @type {Vector3}
  11918. */
  11919. this.min = min;
  11920. /**
  11921. * The upper boundary of the box.
  11922. *
  11923. * @type {Vector3}
  11924. */
  11925. this.max = max;
  11926. }
  11927. /**
  11928. * Sets the lower and upper boundaries of this box.
  11929. * Please note that this method only copies the values from the given objects.
  11930. *
  11931. * @param {Vector3} min - The lower boundary of the box.
  11932. * @param {Vector3} max - The upper boundary of the box.
  11933. * @return {Box3} A reference to this bounding box.
  11934. */
  11935. set( min, max ) {
  11936. this.min.copy( min );
  11937. this.max.copy( max );
  11938. return this;
  11939. }
  11940. /**
  11941. * Sets the upper and lower bounds of this box so it encloses the position data
  11942. * in the given array.
  11943. *
  11944. * @param {Array<number>} array - An array holding 3D position data.
  11945. * @return {Box3} A reference to this bounding box.
  11946. */
  11947. setFromArray( array ) {
  11948. this.makeEmpty();
  11949. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  11950. this.expandByPoint( _vector$b.fromArray( array, i ) );
  11951. }
  11952. return this;
  11953. }
  11954. /**
  11955. * Sets the upper and lower bounds of this box so it encloses the position data
  11956. * in the given buffer attribute.
  11957. *
  11958. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  11959. * @return {Box3} A reference to this bounding box.
  11960. */
  11961. setFromBufferAttribute( attribute ) {
  11962. this.makeEmpty();
  11963. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  11964. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  11965. }
  11966. return this;
  11967. }
  11968. /**
  11969. * Sets the upper and lower bounds of this box so it encloses the position data
  11970. * in the given array.
  11971. *
  11972. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  11973. * @return {Box3} A reference to this bounding box.
  11974. */
  11975. setFromPoints( points ) {
  11976. this.makeEmpty();
  11977. for ( let i = 0, il = points.length; i < il; i ++ ) {
  11978. this.expandByPoint( points[ i ] );
  11979. }
  11980. return this;
  11981. }
  11982. /**
  11983. * Centers this box on the given center vector and sets this box's width, height and
  11984. * depth to the given size values.
  11985. *
  11986. * @param {Vector3} center - The center of the box.
  11987. * @param {Vector3} size - The x, y and z dimensions of the box.
  11988. * @return {Box3} A reference to this bounding box.
  11989. */
  11990. setFromCenterAndSize( center, size ) {
  11991. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  11992. this.min.copy( center ).sub( halfSize );
  11993. this.max.copy( center ).add( halfSize );
  11994. return this;
  11995. }
  11996. /**
  11997. * Computes the world-axis-aligned bounding box for the given 3D object
  11998. * (including its children), accounting for the object's, and children's,
  11999. * world transforms. The function may result in a larger box than strictly necessary.
  12000. *
  12001. * Note: To compute the correct bounding box, make sure the given 3D object
  12002. * has an up-to-date world matrix that reflects the current transformation of its
  12003. * ancestor nodes. Call `object.updateWorldMatrix( true, false )` beforehand if
  12004. * you're unsure.
  12005. *
  12006. * @param {Object3D} object - The 3D object to compute the bounding box for.
  12007. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  12008. * world-axis-aligned bounding box at the expense of more computation.
  12009. * @return {Box3} A reference to this bounding box.
  12010. */
  12011. setFromObject( object, precise = false ) {
  12012. this.makeEmpty();
  12013. return this.expandByObject( object, precise );
  12014. }
  12015. /**
  12016. * Returns a new box with copied values from this instance.
  12017. *
  12018. * @return {Box3} A clone of this instance.
  12019. */
  12020. clone() {
  12021. return new this.constructor().copy( this );
  12022. }
  12023. /**
  12024. * Copies the values of the given box to this instance.
  12025. *
  12026. * @param {Box3} box - The box to copy.
  12027. * @return {Box3} A reference to this bounding box.
  12028. */
  12029. copy( box ) {
  12030. this.min.copy( box.min );
  12031. this.max.copy( box.max );
  12032. return this;
  12033. }
  12034. /**
  12035. * Makes this box empty which means in encloses a zero space in 3D.
  12036. *
  12037. * @return {Box3} A reference to this bounding box.
  12038. */
  12039. makeEmpty() {
  12040. this.min.x = this.min.y = this.min.z = + Infinity;
  12041. this.max.x = this.max.y = this.max.z = - Infinity;
  12042. return this;
  12043. }
  12044. /**
  12045. * Returns true if this box includes zero points within its bounds.
  12046. * Note that a box with equal lower and upper bounds still includes one
  12047. * point, the one both bounds share.
  12048. *
  12049. * @return {boolean} Whether this box is empty or not.
  12050. */
  12051. isEmpty() {
  12052. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  12053. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  12054. }
  12055. /**
  12056. * Returns the center point of this box.
  12057. *
  12058. * @param {Vector3} target - The target vector that is used to store the method's result.
  12059. * @return {Vector3} The center point.
  12060. */
  12061. getCenter( target ) {
  12062. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  12063. }
  12064. /**
  12065. * Returns the dimensions of this box.
  12066. *
  12067. * @param {Vector3} target - The target vector that is used to store the method's result.
  12068. * @return {Vector3} The size.
  12069. */
  12070. getSize( target ) {
  12071. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  12072. }
  12073. /**
  12074. * Expands the boundaries of this box to include the given point.
  12075. *
  12076. * @param {Vector3} point - The point that should be included by the bounding box.
  12077. * @return {Box3} A reference to this bounding box.
  12078. */
  12079. expandByPoint( point ) {
  12080. this.min.min( point );
  12081. this.max.max( point );
  12082. return this;
  12083. }
  12084. /**
  12085. * Expands this box equilaterally by the given vector. The width of this
  12086. * box will be expanded by the x component of the vector in both
  12087. * directions. The height of this box will be expanded by the y component of
  12088. * the vector in both directions. The depth of this box will be
  12089. * expanded by the z component of the vector in both directions.
  12090. *
  12091. * @param {Vector3} vector - The vector that should expand the bounding box.
  12092. * @return {Box3} A reference to this bounding box.
  12093. */
  12094. expandByVector( vector ) {
  12095. this.min.sub( vector );
  12096. this.max.add( vector );
  12097. return this;
  12098. }
  12099. /**
  12100. * Expands each dimension of the box by the given scalar. If negative, the
  12101. * dimensions of the box will be contracted.
  12102. *
  12103. * @param {number} scalar - The scalar value that should expand the bounding box.
  12104. * @return {Box3} A reference to this bounding box.
  12105. */
  12106. expandByScalar( scalar ) {
  12107. this.min.addScalar( - scalar );
  12108. this.max.addScalar( scalar );
  12109. return this;
  12110. }
  12111. /**
  12112. * Expands the boundaries of this box to include the given 3D object and
  12113. * its children, accounting for the object's, and children's, world
  12114. * transforms. The function may result in a larger box than strictly
  12115. * necessary (unless the precise parameter is set to true).
  12116. *
  12117. * @param {Object3D} object - The 3D object that should expand the bounding box.
  12118. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  12119. * as little as necessary at the expense of more computation.
  12120. * @return {Box3} A reference to this bounding box.
  12121. */
  12122. expandByObject( object, precise = false ) {
  12123. // Computes the world-axis-aligned bounding box of an object (including its children),
  12124. // accounting for both the object's, and children's, world transforms
  12125. object.updateWorldMatrix( false, false );
  12126. const geometry = object.geometry;
  12127. if ( geometry !== undefined ) {
  12128. const positionAttribute = geometry.getAttribute( 'position' );
  12129. // precise AABB computation based on vertex data requires at least a position attribute.
  12130. // instancing isn't supported so far and uses the normal (conservative) code path.
  12131. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  12132. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  12133. if ( object.isMesh === true ) {
  12134. object.getVertexPosition( i, _vector$b );
  12135. } else {
  12136. _vector$b.fromBufferAttribute( positionAttribute, i );
  12137. }
  12138. _vector$b.applyMatrix4( object.matrixWorld );
  12139. this.expandByPoint( _vector$b );
  12140. }
  12141. } else {
  12142. if ( object.boundingBox !== undefined ) {
  12143. // object-level bounding box
  12144. if ( object.boundingBox === null ) {
  12145. object.computeBoundingBox();
  12146. }
  12147. _box$4.copy( object.boundingBox );
  12148. } else {
  12149. // geometry-level bounding box
  12150. if ( geometry.boundingBox === null ) {
  12151. geometry.computeBoundingBox();
  12152. }
  12153. _box$4.copy( geometry.boundingBox );
  12154. }
  12155. _box$4.applyMatrix4( object.matrixWorld );
  12156. this.union( _box$4 );
  12157. }
  12158. }
  12159. const children = object.children;
  12160. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12161. this.expandByObject( children[ i ], precise );
  12162. }
  12163. return this;
  12164. }
  12165. /**
  12166. * Returns `true` if the given point lies within or on the boundaries of this box.
  12167. *
  12168. * @param {Vector3} point - The point to test.
  12169. * @return {boolean} Whether the bounding box contains the given point or not.
  12170. */
  12171. containsPoint( point ) {
  12172. return point.x >= this.min.x && point.x <= this.max.x &&
  12173. point.y >= this.min.y && point.y <= this.max.y &&
  12174. point.z >= this.min.z && point.z <= this.max.z;
  12175. }
  12176. /**
  12177. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  12178. * If this box and the given one are identical, this function also returns `true`.
  12179. *
  12180. * @param {Box3} box - The bounding box to test.
  12181. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  12182. */
  12183. containsBox( box ) {
  12184. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  12185. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  12186. this.min.z <= box.min.z && box.max.z <= this.max.z;
  12187. }
  12188. /**
  12189. * Returns a point as a proportion of this box's width, height and depth.
  12190. *
  12191. * @param {Vector3} point - A point in 3D space.
  12192. * @param {Vector3} target - The target vector that is used to store the method's result.
  12193. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  12194. */
  12195. getParameter( point, target ) {
  12196. // This can potentially have a divide by zero if the box
  12197. // has a size dimension of 0.
  12198. return target.set(
  12199. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  12200. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  12201. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  12202. );
  12203. }
  12204. /**
  12205. * Returns `true` if the given bounding box intersects with this bounding box.
  12206. *
  12207. * @param {Box3} box - The bounding box to test.
  12208. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  12209. */
  12210. intersectsBox( box ) {
  12211. // using 6 splitting planes to rule out intersections.
  12212. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  12213. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  12214. box.max.z >= this.min.z && box.min.z <= this.max.z;
  12215. }
  12216. /**
  12217. * Returns `true` if the given bounding sphere intersects with this bounding box.
  12218. *
  12219. * @param {Sphere} sphere - The bounding sphere to test.
  12220. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  12221. */
  12222. intersectsSphere( sphere ) {
  12223. // Find the point on the AABB closest to the sphere center.
  12224. this.clampPoint( sphere.center, _vector$b );
  12225. // If that point is inside the sphere, the AABB and sphere intersect.
  12226. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  12227. }
  12228. /**
  12229. * Returns `true` if the given plane intersects with this bounding box.
  12230. *
  12231. * @param {Plane} plane - The plane to test.
  12232. * @return {boolean} Whether the given plane intersects with this bounding box.
  12233. */
  12234. intersectsPlane( plane ) {
  12235. // We compute the minimum and maximum dot product values. If those values
  12236. // are on the same side (back or front) of the plane, then there is no intersection.
  12237. let min, max;
  12238. if ( plane.normal.x > 0 ) {
  12239. min = plane.normal.x * this.min.x;
  12240. max = plane.normal.x * this.max.x;
  12241. } else {
  12242. min = plane.normal.x * this.max.x;
  12243. max = plane.normal.x * this.min.x;
  12244. }
  12245. if ( plane.normal.y > 0 ) {
  12246. min += plane.normal.y * this.min.y;
  12247. max += plane.normal.y * this.max.y;
  12248. } else {
  12249. min += plane.normal.y * this.max.y;
  12250. max += plane.normal.y * this.min.y;
  12251. }
  12252. if ( plane.normal.z > 0 ) {
  12253. min += plane.normal.z * this.min.z;
  12254. max += plane.normal.z * this.max.z;
  12255. } else {
  12256. min += plane.normal.z * this.max.z;
  12257. max += plane.normal.z * this.min.z;
  12258. }
  12259. return ( min <= - plane.constant && max >= - plane.constant );
  12260. }
  12261. /**
  12262. * Returns `true` if the given triangle intersects with this bounding box.
  12263. *
  12264. * @param {Triangle} triangle - The triangle to test.
  12265. * @return {boolean} Whether the given triangle intersects with this bounding box.
  12266. */
  12267. intersectsTriangle( triangle ) {
  12268. if ( this.isEmpty() ) {
  12269. return false;
  12270. }
  12271. // compute box center and extents
  12272. this.getCenter( _center );
  12273. _extents.subVectors( this.max, _center );
  12274. // translate triangle to aabb origin
  12275. _v0$1.subVectors( triangle.a, _center );
  12276. _v1$4.subVectors( triangle.b, _center );
  12277. _v2$3.subVectors( triangle.c, _center );
  12278. // compute edge vectors for triangle
  12279. _f0.subVectors( _v1$4, _v0$1 );
  12280. _f1.subVectors( _v2$3, _v1$4 );
  12281. _f2.subVectors( _v0$1, _v2$3 );
  12282. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  12283. // 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
  12284. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  12285. let axes = [
  12286. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  12287. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  12288. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  12289. ];
  12290. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12291. return false;
  12292. }
  12293. // test 3 face normals from the aabb
  12294. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  12295. if ( ! satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents ) ) {
  12296. return false;
  12297. }
  12298. // finally testing the face normal of the triangle
  12299. // use already existing triangle edge vectors here
  12300. _triangleNormal.crossVectors( _f0, _f1 );
  12301. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  12302. return satForAxes( axes, _v0$1, _v1$4, _v2$3, _extents );
  12303. }
  12304. /**
  12305. * Clamps the given point within the bounds of this box.
  12306. *
  12307. * @param {Vector3} point - The point to clamp.
  12308. * @param {Vector3} target - The target vector that is used to store the method's result.
  12309. * @return {Vector3} The clamped point.
  12310. */
  12311. clampPoint( point, target ) {
  12312. return target.copy( point ).clamp( this.min, this.max );
  12313. }
  12314. /**
  12315. * Returns the euclidean distance from any edge of this box to the specified point. If
  12316. * the given point lies inside of this box, the distance will be `0`.
  12317. *
  12318. * @param {Vector3} point - The point to compute the distance to.
  12319. * @return {number} The euclidean distance.
  12320. */
  12321. distanceToPoint( point ) {
  12322. return this.clampPoint( point, _vector$b ).distanceTo( point );
  12323. }
  12324. /**
  12325. * Returns a bounding sphere that encloses this bounding box.
  12326. *
  12327. * @param {Sphere} target - The target sphere that is used to store the method's result.
  12328. * @return {Sphere} The bounding sphere that encloses this bounding box.
  12329. */
  12330. getBoundingSphere( target ) {
  12331. if ( this.isEmpty() ) {
  12332. target.makeEmpty();
  12333. } else {
  12334. this.getCenter( target.center );
  12335. target.radius = this.getSize( _vector$b ).length() * 0.5;
  12336. }
  12337. return target;
  12338. }
  12339. /**
  12340. * Computes the intersection of this bounding box and the given one, setting the upper
  12341. * bound of this box to the lesser of the two boxes' upper bounds and the
  12342. * lower bound of this box to the greater of the two boxes' lower bounds. If
  12343. * there's no overlap, makes this box empty.
  12344. *
  12345. * @param {Box3} box - The bounding box to intersect with.
  12346. * @return {Box3} A reference to this bounding box.
  12347. */
  12348. intersect( box ) {
  12349. this.min.max( box.min );
  12350. this.max.min( box.max );
  12351. // 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.
  12352. if ( this.isEmpty() ) this.makeEmpty();
  12353. return this;
  12354. }
  12355. /**
  12356. * Computes the union of this box and another and the given one, setting the upper
  12357. * bound of this box to the greater of the two boxes' upper bounds and the
  12358. * lower bound of this box to the lesser of the two boxes' lower bounds.
  12359. *
  12360. * @param {Box3} box - The bounding box that will be unioned with this instance.
  12361. * @return {Box3} A reference to this bounding box.
  12362. */
  12363. union( box ) {
  12364. this.min.min( box.min );
  12365. this.max.max( box.max );
  12366. return this;
  12367. }
  12368. /**
  12369. * Transforms this bounding box by the given 4x4 transformation matrix.
  12370. *
  12371. * @param {Matrix4} matrix - The transformation matrix.
  12372. * @return {Box3} A reference to this bounding box.
  12373. */
  12374. applyMatrix4( matrix ) {
  12375. // transform of empty box is an empty box.
  12376. if ( this.isEmpty() ) return this;
  12377. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  12378. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  12379. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  12380. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  12381. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  12382. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  12383. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  12384. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  12385. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  12386. this.setFromPoints( _points );
  12387. return this;
  12388. }
  12389. /**
  12390. * Adds the given offset to both the upper and lower bounds of this bounding box,
  12391. * effectively moving it in 3D space.
  12392. *
  12393. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  12394. * @return {Box3} A reference to this bounding box.
  12395. */
  12396. translate( offset ) {
  12397. this.min.add( offset );
  12398. this.max.add( offset );
  12399. return this;
  12400. }
  12401. /**
  12402. * Returns `true` if this bounding box is equal with the given one.
  12403. *
  12404. * @param {Box3} box - The box to test for equality.
  12405. * @return {boolean} Whether this bounding box is equal with the given one.
  12406. */
  12407. equals( box ) {
  12408. return box.min.equals( this.min ) && box.max.equals( this.max );
  12409. }
  12410. /**
  12411. * Returns a serialized structure of the bounding box.
  12412. *
  12413. * @return {Object} Serialized structure with fields representing the object state.
  12414. */
  12415. toJSON() {
  12416. return {
  12417. min: this.min.toArray(),
  12418. max: this.max.toArray()
  12419. };
  12420. }
  12421. /**
  12422. * Returns a serialized structure of the bounding box.
  12423. *
  12424. * @param {Object} json - The serialized json to set the box from.
  12425. * @return {Box3} A reference to this bounding box.
  12426. */
  12427. fromJSON( json ) {
  12428. this.min.fromArray( json.min );
  12429. this.max.fromArray( json.max );
  12430. return this;
  12431. }
  12432. }
  12433. const _points = [
  12434. /*@__PURE__*/ new Vector3(),
  12435. /*@__PURE__*/ new Vector3(),
  12436. /*@__PURE__*/ new Vector3(),
  12437. /*@__PURE__*/ new Vector3(),
  12438. /*@__PURE__*/ new Vector3(),
  12439. /*@__PURE__*/ new Vector3(),
  12440. /*@__PURE__*/ new Vector3(),
  12441. /*@__PURE__*/ new Vector3()
  12442. ];
  12443. const _vector$b = /*@__PURE__*/ new Vector3();
  12444. const _box$4 = /*@__PURE__*/ new Box3();
  12445. // triangle centered vertices
  12446. const _v0$1 = /*@__PURE__*/ new Vector3();
  12447. const _v1$4 = /*@__PURE__*/ new Vector3();
  12448. const _v2$3 = /*@__PURE__*/ new Vector3();
  12449. // triangle edge vectors
  12450. const _f0 = /*@__PURE__*/ new Vector3();
  12451. const _f1 = /*@__PURE__*/ new Vector3();
  12452. const _f2 = /*@__PURE__*/ new Vector3();
  12453. const _center = /*@__PURE__*/ new Vector3();
  12454. const _extents = /*@__PURE__*/ new Vector3();
  12455. const _triangleNormal = /*@__PURE__*/ new Vector3();
  12456. const _testAxis = /*@__PURE__*/ new Vector3();
  12457. function satForAxes( axes, v0, v1, v2, extents ) {
  12458. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  12459. _testAxis.fromArray( axes, i );
  12460. // project the aabb onto the separating axis
  12461. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  12462. // project all 3 vertices of the triangle onto the separating axis
  12463. const p0 = v0.dot( _testAxis );
  12464. const p1 = v1.dot( _testAxis );
  12465. const p2 = v2.dot( _testAxis );
  12466. // actual test, basically see if either of the most extreme of the triangle points intersects r
  12467. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  12468. // points of the projected triangle are outside the projected half-length of the aabb
  12469. // the axis is separating and we can exit
  12470. return false;
  12471. }
  12472. }
  12473. return true;
  12474. }
  12475. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  12476. const _tables = /*@__PURE__*/ _generateTables();
  12477. function _generateTables() {
  12478. // float32 to float16 helpers
  12479. const buffer = new ArrayBuffer( 4 );
  12480. const floatView = new Float32Array( buffer );
  12481. const uint32View = new Uint32Array( buffer );
  12482. const baseTable = new Uint32Array( 512 );
  12483. const shiftTable = new Uint32Array( 512 );
  12484. for ( let i = 0; i < 256; ++ i ) {
  12485. const e = i - 127;
  12486. // very small number (0, -0)
  12487. if ( e < -27 ) {
  12488. baseTable[ i ] = 0x0000;
  12489. baseTable[ i | 0x100 ] = 0x8000;
  12490. shiftTable[ i ] = 24;
  12491. shiftTable[ i | 0x100 ] = 24;
  12492. // small number (denorm)
  12493. } else if ( e < -14 ) {
  12494. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  12495. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  12496. shiftTable[ i ] = - e - 1;
  12497. shiftTable[ i | 0x100 ] = - e - 1;
  12498. // normal number
  12499. } else if ( e <= 15 ) {
  12500. baseTable[ i ] = ( e + 15 ) << 10;
  12501. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  12502. shiftTable[ i ] = 13;
  12503. shiftTable[ i | 0x100 ] = 13;
  12504. // large number (Infinity, -Infinity)
  12505. } else if ( e < 128 ) {
  12506. baseTable[ i ] = 0x7c00;
  12507. baseTable[ i | 0x100 ] = 0xfc00;
  12508. shiftTable[ i ] = 24;
  12509. shiftTable[ i | 0x100 ] = 24;
  12510. // stay (NaN, Infinity, -Infinity)
  12511. } else {
  12512. baseTable[ i ] = 0x7c00;
  12513. baseTable[ i | 0x100 ] = 0xfc00;
  12514. shiftTable[ i ] = 13;
  12515. shiftTable[ i | 0x100 ] = 13;
  12516. }
  12517. }
  12518. // float16 to float32 helpers
  12519. const mantissaTable = new Uint32Array( 2048 );
  12520. const exponentTable = new Uint32Array( 64 );
  12521. const offsetTable = new Uint32Array( 64 );
  12522. for ( let i = 1; i < 1024; ++ i ) {
  12523. let m = i << 13; // zero pad mantissa bits
  12524. let e = 0; // zero exponent
  12525. // normalized
  12526. while ( ( m & 0x00800000 ) === 0 ) {
  12527. m <<= 1;
  12528. e -= 0x00800000; // decrement exponent
  12529. }
  12530. m &= -8388609; // clear leading 1 bit
  12531. e += 0x38800000; // adjust bias
  12532. mantissaTable[ i ] = m | e;
  12533. }
  12534. for ( let i = 1024; i < 2048; ++ i ) {
  12535. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  12536. }
  12537. for ( let i = 1; i < 31; ++ i ) {
  12538. exponentTable[ i ] = i << 23;
  12539. }
  12540. exponentTable[ 31 ] = 0x47800000;
  12541. exponentTable[ 32 ] = 0x80000000;
  12542. for ( let i = 33; i < 63; ++ i ) {
  12543. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  12544. }
  12545. exponentTable[ 63 ] = 0xc7800000;
  12546. for ( let i = 1; i < 64; ++ i ) {
  12547. if ( i !== 32 ) {
  12548. offsetTable[ i ] = 1024;
  12549. }
  12550. }
  12551. return {
  12552. floatView: floatView,
  12553. uint32View: uint32View,
  12554. baseTable: baseTable,
  12555. shiftTable: shiftTable,
  12556. mantissaTable: mantissaTable,
  12557. exponentTable: exponentTable,
  12558. offsetTable: offsetTable
  12559. };
  12560. }
  12561. /**
  12562. * Returns a half precision floating point value (FP16) from the given single
  12563. * precision floating point value (FP32).
  12564. *
  12565. * @param {number} val - A single precision floating point value.
  12566. * @return {number} The FP16 value.
  12567. */
  12568. function toHalfFloat( val ) {
  12569. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  12570. val = clamp( val, -65504, 65504 );
  12571. _tables.floatView[ 0 ] = val;
  12572. const f = _tables.uint32View[ 0 ];
  12573. const e = ( f >> 23 ) & 0x1ff;
  12574. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  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. function fromHalfFloat( val ) {
  12584. const m = val >> 10;
  12585. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  12586. return _tables.floatView[ 0 ];
  12587. }
  12588. /**
  12589. * A class containing utility functions for data.
  12590. *
  12591. * @hideconstructor
  12592. */
  12593. class DataUtils {
  12594. /**
  12595. * Returns a half precision floating point value (FP16) from the given single
  12596. * precision floating point value (FP32).
  12597. *
  12598. * @param {number} val - A single precision floating point value.
  12599. * @return {number} The FP16 value.
  12600. */
  12601. static toHalfFloat( val ) {
  12602. return toHalfFloat( val );
  12603. }
  12604. /**
  12605. * Returns a single precision floating point value (FP32) from the given half
  12606. * precision floating point value (FP16).
  12607. *
  12608. * @param {number} val - A half precision floating point value.
  12609. * @return {number} The FP32 value.
  12610. */
  12611. static fromHalfFloat( val ) {
  12612. return fromHalfFloat( val );
  12613. }
  12614. }
  12615. const _vector$a = /*@__PURE__*/ new Vector3();
  12616. const _vector2$1 = /*@__PURE__*/ new Vector2();
  12617. let _id$2 = 0;
  12618. /**
  12619. * This class stores data for an attribute (such as vertex positions, face
  12620. * indices, normals, colors, UVs, and any custom attributes ) associated with
  12621. * a geometry, which allows for more efficient passing of data to the GPU.
  12622. *
  12623. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  12624. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  12625. */
  12626. class BufferAttribute extends EventDispatcher {
  12627. /**
  12628. * Constructs a new buffer attribute.
  12629. *
  12630. * @param {TypedArray} array - The array holding the attribute data.
  12631. * @param {number} itemSize - The item size.
  12632. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  12633. */
  12634. constructor( array, itemSize, normalized = false ) {
  12635. super();
  12636. if ( Array.isArray( array ) ) {
  12637. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12638. }
  12639. /**
  12640. * This flag can be used for type testing.
  12641. *
  12642. * @type {boolean}
  12643. * @readonly
  12644. * @default true
  12645. */
  12646. this.isBufferAttribute = true;
  12647. /**
  12648. * The ID of the buffer attribute.
  12649. *
  12650. * @name BufferAttribute#id
  12651. * @type {number}
  12652. * @readonly
  12653. */
  12654. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  12655. /**
  12656. * The name of the buffer attribute.
  12657. *
  12658. * @type {string}
  12659. */
  12660. this.name = '';
  12661. /**
  12662. * The array holding the attribute data. It should have `itemSize * numVertices`
  12663. * elements, where `numVertices` is the number of vertices in the associated geometry.
  12664. *
  12665. * @type {TypedArray}
  12666. */
  12667. this.array = array;
  12668. /**
  12669. * The number of values of the array that should be associated with a particular vertex.
  12670. * For instance, if this attribute is storing a 3-component vector (such as a position,
  12671. * normal, or color), then the value should be `3`.
  12672. *
  12673. * @type {number}
  12674. */
  12675. this.itemSize = itemSize;
  12676. /**
  12677. * Represents the number of items this buffer attribute stores. It is internally computed
  12678. * by dividing the `array` length by the `itemSize`.
  12679. *
  12680. * @type {number}
  12681. * @readonly
  12682. */
  12683. this.count = array !== undefined ? array.length / itemSize : 0;
  12684. /**
  12685. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  12686. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  12687. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  12688. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  12689. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  12690. *
  12691. * @type {boolean}
  12692. */
  12693. this.normalized = normalized;
  12694. /**
  12695. * Defines the intended usage pattern of the data store for optimization purposes.
  12696. *
  12697. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  12698. * instantiate a new one and set the desired usage before the next render.
  12699. *
  12700. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  12701. * @default StaticDrawUsage
  12702. */
  12703. this.usage = StaticDrawUsage;
  12704. /**
  12705. * This can be used to only update some components of stored vectors (for example, just the
  12706. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  12707. *
  12708. * @type {Array<Object>}
  12709. */
  12710. this.updateRanges = [];
  12711. /**
  12712. * Configures the bound GPU type for use in shaders.
  12713. *
  12714. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  12715. * For lower precision float types, use `Float16BufferAttribute`.
  12716. *
  12717. * @type {(FloatType|IntType)}
  12718. * @default FloatType
  12719. */
  12720. this.gpuType = FloatType;
  12721. /**
  12722. * A version number, incremented every time the `needsUpdate` is set to `true`.
  12723. *
  12724. * @type {number}
  12725. */
  12726. this.version = 0;
  12727. }
  12728. /**
  12729. * A callback function that is executed after the renderer has transferred the attribute
  12730. * array data to the GPU.
  12731. */
  12732. onUploadCallback() {}
  12733. /**
  12734. * Flag to indicate that this attribute has changed and should be re-sent to
  12735. * the GPU. Set this to `true` when you modify the value of the array.
  12736. *
  12737. * @type {number}
  12738. * @default false
  12739. * @param {boolean} value
  12740. */
  12741. set needsUpdate( value ) {
  12742. if ( value === true ) this.version ++;
  12743. }
  12744. /**
  12745. * Sets the usage of this buffer attribute.
  12746. *
  12747. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  12748. * @return {BufferAttribute} A reference to this buffer attribute.
  12749. */
  12750. setUsage( value ) {
  12751. this.usage = value;
  12752. return this;
  12753. }
  12754. /**
  12755. * Adds a range of data in the data array to be updated on the GPU.
  12756. *
  12757. * @param {number} start - Position at which to start update.
  12758. * @param {number} count - The number of components to update.
  12759. */
  12760. addUpdateRange( start, count ) {
  12761. this.updateRanges.push( { start, count } );
  12762. }
  12763. /**
  12764. * Clears the update ranges.
  12765. */
  12766. clearUpdateRanges() {
  12767. this.updateRanges.length = 0;
  12768. }
  12769. /**
  12770. * Copies the values of the given buffer attribute to this instance.
  12771. *
  12772. * @param {BufferAttribute} source - The buffer attribute to copy.
  12773. * @return {BufferAttribute} A reference to this instance.
  12774. */
  12775. copy( source ) {
  12776. this.name = source.name;
  12777. this.array = new source.array.constructor( source.array );
  12778. this.itemSize = source.itemSize;
  12779. this.count = source.count;
  12780. this.normalized = source.normalized;
  12781. this.usage = source.usage;
  12782. this.gpuType = source.gpuType;
  12783. return this;
  12784. }
  12785. /**
  12786. * Copies a vector from the given buffer attribute to this one. The start
  12787. * and destination position in the attribute buffers are represented by the
  12788. * given indices.
  12789. *
  12790. * @param {number} index1 - The destination index into this buffer attribute.
  12791. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  12792. * @param {number} index2 - The source index into the given buffer attribute.
  12793. * @return {BufferAttribute} A reference to this instance.
  12794. */
  12795. copyAt( index1, attribute, index2 ) {
  12796. index1 *= this.itemSize;
  12797. index2 *= attribute.itemSize;
  12798. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  12799. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12800. }
  12801. return this;
  12802. }
  12803. /**
  12804. * Copies the given array data into this buffer attribute.
  12805. *
  12806. * @param {(TypedArray|Array)} array - The array to copy.
  12807. * @return {BufferAttribute} A reference to this instance.
  12808. */
  12809. copyArray( array ) {
  12810. this.array.set( array );
  12811. return this;
  12812. }
  12813. /**
  12814. * Applies the given 3x3 matrix to the given attribute. Works with
  12815. * item size `2` and `3`.
  12816. *
  12817. * @param {Matrix3} m - The matrix to apply.
  12818. * @return {BufferAttribute} A reference to this instance.
  12819. */
  12820. applyMatrix3( m ) {
  12821. if ( this.itemSize === 2 ) {
  12822. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12823. _vector2$1.fromBufferAttribute( this, i );
  12824. _vector2$1.applyMatrix3( m );
  12825. this.setXY( i, _vector2$1.x, _vector2$1.y );
  12826. }
  12827. } else if ( this.itemSize === 3 ) {
  12828. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12829. _vector$a.fromBufferAttribute( this, i );
  12830. _vector$a.applyMatrix3( m );
  12831. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12832. }
  12833. }
  12834. return this;
  12835. }
  12836. /**
  12837. * Applies the given 4x4 matrix to the given attribute. Only works with
  12838. * item size `3`.
  12839. *
  12840. * @param {Matrix4} m - The matrix to apply.
  12841. * @return {BufferAttribute} A reference to this instance.
  12842. */
  12843. applyMatrix4( m ) {
  12844. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12845. _vector$a.fromBufferAttribute( this, i );
  12846. _vector$a.applyMatrix4( m );
  12847. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12848. }
  12849. return this;
  12850. }
  12851. /**
  12852. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  12853. * item size `3`.
  12854. *
  12855. * @param {Matrix3} m - The normal matrix to apply.
  12856. * @return {BufferAttribute} A reference to this instance.
  12857. */
  12858. applyNormalMatrix( m ) {
  12859. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12860. _vector$a.fromBufferAttribute( this, i );
  12861. _vector$a.applyNormalMatrix( m );
  12862. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12863. }
  12864. return this;
  12865. }
  12866. /**
  12867. * Applies the given 4x4 matrix to the given attribute. Only works with
  12868. * item size `3` and with direction vectors.
  12869. *
  12870. * @param {Matrix4} m - The matrix to apply.
  12871. * @return {BufferAttribute} A reference to this instance.
  12872. */
  12873. transformDirection( m ) {
  12874. for ( let i = 0, l = this.count; i < l; i ++ ) {
  12875. _vector$a.fromBufferAttribute( this, i );
  12876. _vector$a.transformDirection( m );
  12877. this.setXYZ( i, _vector$a.x, _vector$a.y, _vector$a.z );
  12878. }
  12879. return this;
  12880. }
  12881. /**
  12882. * Sets the given array data in the buffer attribute.
  12883. *
  12884. * @param {(TypedArray|Array)} value - The array data to set.
  12885. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  12886. * @return {BufferAttribute} A reference to this instance.
  12887. */
  12888. set( value, offset = 0 ) {
  12889. // Matching BufferAttribute constructor, do not normalize the array.
  12890. this.array.set( value, offset );
  12891. return this;
  12892. }
  12893. /**
  12894. * Returns the given component of the vector at the given index.
  12895. *
  12896. * @param {number} index - The index into the buffer attribute.
  12897. * @param {number} component - The component index.
  12898. * @return {number} The returned value.
  12899. */
  12900. getComponent( index, component ) {
  12901. let value = this.array[ index * this.itemSize + component ];
  12902. if ( this.normalized ) value = denormalize( value, this.array );
  12903. return value;
  12904. }
  12905. /**
  12906. * Sets the given value to the given component of the vector at the given index.
  12907. *
  12908. * @param {number} index - The index into the buffer attribute.
  12909. * @param {number} component - The component index.
  12910. * @param {number} value - The value to set.
  12911. * @return {BufferAttribute} A reference to this instance.
  12912. */
  12913. setComponent( index, component, value ) {
  12914. if ( this.normalized ) value = normalize( value, this.array );
  12915. this.array[ index * this.itemSize + component ] = value;
  12916. return this;
  12917. }
  12918. /**
  12919. * Returns the x component of the vector at the given index.
  12920. *
  12921. * @param {number} index - The index into the buffer attribute.
  12922. * @return {number} The x component.
  12923. */
  12924. getX( index ) {
  12925. let x = this.array[ index * this.itemSize ];
  12926. if ( this.normalized ) x = denormalize( x, this.array );
  12927. return x;
  12928. }
  12929. /**
  12930. * Sets the x component of the vector at the given index.
  12931. *
  12932. * @param {number} index - The index into the buffer attribute.
  12933. * @param {number} x - The value to set.
  12934. * @return {BufferAttribute} A reference to this instance.
  12935. */
  12936. setX( index, x ) {
  12937. if ( this.normalized ) x = normalize( x, this.array );
  12938. this.array[ index * this.itemSize ] = x;
  12939. return this;
  12940. }
  12941. /**
  12942. * Returns the y component of the vector at the given index.
  12943. *
  12944. * @param {number} index - The index into the buffer attribute.
  12945. * @return {number} The y component.
  12946. */
  12947. getY( index ) {
  12948. let y = this.array[ index * this.itemSize + 1 ];
  12949. if ( this.normalized ) y = denormalize( y, this.array );
  12950. return y;
  12951. }
  12952. /**
  12953. * Sets the y component of the vector at the given index.
  12954. *
  12955. * @param {number} index - The index into the buffer attribute.
  12956. * @param {number} y - The value to set.
  12957. * @return {BufferAttribute} A reference to this instance.
  12958. */
  12959. setY( index, y ) {
  12960. if ( this.normalized ) y = normalize( y, this.array );
  12961. this.array[ index * this.itemSize + 1 ] = y;
  12962. return this;
  12963. }
  12964. /**
  12965. * Returns the z component of the vector at the given index.
  12966. *
  12967. * @param {number} index - The index into the buffer attribute.
  12968. * @return {number} The z component.
  12969. */
  12970. getZ( index ) {
  12971. let z = this.array[ index * this.itemSize + 2 ];
  12972. if ( this.normalized ) z = denormalize( z, this.array );
  12973. return z;
  12974. }
  12975. /**
  12976. * Sets the z component of the vector at the given index.
  12977. *
  12978. * @param {number} index - The index into the buffer attribute.
  12979. * @param {number} z - The value to set.
  12980. * @return {BufferAttribute} A reference to this instance.
  12981. */
  12982. setZ( index, z ) {
  12983. if ( this.normalized ) z = normalize( z, this.array );
  12984. this.array[ index * this.itemSize + 2 ] = z;
  12985. return this;
  12986. }
  12987. /**
  12988. * Returns the w component of the vector at the given index.
  12989. *
  12990. * @param {number} index - The index into the buffer attribute.
  12991. * @return {number} The w component.
  12992. */
  12993. getW( index ) {
  12994. let w = this.array[ index * this.itemSize + 3 ];
  12995. if ( this.normalized ) w = denormalize( w, this.array );
  12996. return w;
  12997. }
  12998. /**
  12999. * Sets the w component of the vector at the given index.
  13000. *
  13001. * @param {number} index - The index into the buffer attribute.
  13002. * @param {number} w - The value to set.
  13003. * @return {BufferAttribute} A reference to this instance.
  13004. */
  13005. setW( index, w ) {
  13006. if ( this.normalized ) w = normalize( w, this.array );
  13007. this.array[ index * this.itemSize + 3 ] = w;
  13008. return this;
  13009. }
  13010. /**
  13011. * Sets the x and y component of the vector at the given index.
  13012. *
  13013. * @param {number} index - The index into the buffer attribute.
  13014. * @param {number} x - The value for the x component to set.
  13015. * @param {number} y - The value for the y component to set.
  13016. * @return {BufferAttribute} A reference to this instance.
  13017. */
  13018. setXY( index, x, y ) {
  13019. index *= this.itemSize;
  13020. if ( this.normalized ) {
  13021. x = normalize( x, this.array );
  13022. y = normalize( y, this.array );
  13023. }
  13024. this.array[ index + 0 ] = x;
  13025. this.array[ index + 1 ] = y;
  13026. return this;
  13027. }
  13028. /**
  13029. * Sets the x, y and z component of the vector at the given index.
  13030. *
  13031. * @param {number} index - The index into the buffer attribute.
  13032. * @param {number} x - The value for the x component to set.
  13033. * @param {number} y - The value for the y component to set.
  13034. * @param {number} z - The value for the z component to set.
  13035. * @return {BufferAttribute} A reference to this instance.
  13036. */
  13037. setXYZ( index, x, y, z ) {
  13038. index *= this.itemSize;
  13039. if ( this.normalized ) {
  13040. x = normalize( x, this.array );
  13041. y = normalize( y, this.array );
  13042. z = normalize( z, this.array );
  13043. }
  13044. this.array[ index + 0 ] = x;
  13045. this.array[ index + 1 ] = y;
  13046. this.array[ index + 2 ] = z;
  13047. return this;
  13048. }
  13049. /**
  13050. * Sets the x, y, z and w component of the vector at the given index.
  13051. *
  13052. * @param {number} index - The index into the buffer attribute.
  13053. * @param {number} x - The value for the x component to set.
  13054. * @param {number} y - The value for the y component to set.
  13055. * @param {number} z - The value for the z component to set.
  13056. * @param {number} w - The value for the w component to set.
  13057. * @return {BufferAttribute} A reference to this instance.
  13058. */
  13059. setXYZW( index, x, y, z, w ) {
  13060. index *= this.itemSize;
  13061. if ( this.normalized ) {
  13062. x = normalize( x, this.array );
  13063. y = normalize( y, this.array );
  13064. z = normalize( z, this.array );
  13065. w = normalize( w, this.array );
  13066. }
  13067. this.array[ index + 0 ] = x;
  13068. this.array[ index + 1 ] = y;
  13069. this.array[ index + 2 ] = z;
  13070. this.array[ index + 3 ] = w;
  13071. return this;
  13072. }
  13073. /**
  13074. * Sets the given callback function that is executed after the Renderer has transferred
  13075. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13076. * the upload when attribute data are not needed anymore on the CPU side.
  13077. *
  13078. * @param {Function} callback - The `onUpload()` callback.
  13079. * @return {BufferAttribute} A reference to this instance.
  13080. */
  13081. onUpload( callback ) {
  13082. this.onUploadCallback = callback;
  13083. return this;
  13084. }
  13085. /**
  13086. * Returns a new buffer attribute with copied values from this instance.
  13087. *
  13088. * @return {BufferAttribute} A clone of this instance.
  13089. */
  13090. clone() {
  13091. return new this.constructor( this.array, this.itemSize ).copy( this );
  13092. }
  13093. /**
  13094. * Serializes the buffer attribute into JSON.
  13095. *
  13096. * @return {Object} A JSON object representing the serialized buffer attribute.
  13097. */
  13098. toJSON() {
  13099. const data = {
  13100. itemSize: this.itemSize,
  13101. type: this.array.constructor.name,
  13102. array: Array.from( this.array ),
  13103. normalized: this.normalized
  13104. };
  13105. if ( this.name !== '' ) data.name = this.name;
  13106. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13107. return data;
  13108. }
  13109. /**
  13110. * Disposes of the buffer attribute. Available only in {@link WebGPURenderer}.
  13111. */
  13112. dispose() {
  13113. this.dispatchEvent( { type: 'dispose' } );
  13114. }
  13115. }
  13116. /**
  13117. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13118. * a plain `Array` instance.
  13119. *
  13120. * @augments BufferAttribute
  13121. */
  13122. class Int8BufferAttribute extends BufferAttribute {
  13123. /**
  13124. * Constructs a new buffer attribute.
  13125. *
  13126. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13127. * @param {number} itemSize - The item size.
  13128. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13129. */
  13130. constructor( array, itemSize, normalized ) {
  13131. super( new Int8Array( array ), itemSize, normalized );
  13132. }
  13133. }
  13134. /**
  13135. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13136. * a plain `Array` instance.
  13137. *
  13138. * @augments BufferAttribute
  13139. */
  13140. class Uint8BufferAttribute extends BufferAttribute {
  13141. /**
  13142. * Constructs a new buffer attribute.
  13143. *
  13144. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13145. * @param {number} itemSize - The item size.
  13146. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13147. */
  13148. constructor( array, itemSize, normalized ) {
  13149. super( new Uint8Array( array ), itemSize, normalized );
  13150. }
  13151. }
  13152. /**
  13153. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13154. * a plain `Array` instance.
  13155. *
  13156. * @augments BufferAttribute
  13157. */
  13158. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13159. /**
  13160. * Constructs a new buffer attribute.
  13161. *
  13162. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13163. * @param {number} itemSize - The item size.
  13164. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13165. */
  13166. constructor( array, itemSize, normalized ) {
  13167. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13168. }
  13169. }
  13170. /**
  13171. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13172. * a plain `Array` instance.
  13173. *
  13174. * @augments BufferAttribute
  13175. */
  13176. class Int16BufferAttribute extends BufferAttribute {
  13177. /**
  13178. * Constructs a new buffer attribute.
  13179. *
  13180. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13181. * @param {number} itemSize - The item size.
  13182. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13183. */
  13184. constructor( array, itemSize, normalized ) {
  13185. super( new Int16Array( array ), itemSize, normalized );
  13186. }
  13187. }
  13188. /**
  13189. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13190. * a plain `Array` instance.
  13191. *
  13192. * @augments BufferAttribute
  13193. */
  13194. class Uint16BufferAttribute extends BufferAttribute {
  13195. /**
  13196. * Constructs a new buffer attribute.
  13197. *
  13198. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13199. * @param {number} itemSize - The item size.
  13200. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13201. */
  13202. constructor( array, itemSize, normalized ) {
  13203. super( new Uint16Array( array ), itemSize, normalized );
  13204. }
  13205. }
  13206. /**
  13207. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13208. * a plain `Array` instance.
  13209. *
  13210. * @augments BufferAttribute
  13211. */
  13212. class Int32BufferAttribute extends BufferAttribute {
  13213. /**
  13214. * Constructs a new buffer attribute.
  13215. *
  13216. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13217. * @param {number} itemSize - The item size.
  13218. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13219. */
  13220. constructor( array, itemSize, normalized ) {
  13221. super( new Int32Array( array ), itemSize, normalized );
  13222. }
  13223. }
  13224. /**
  13225. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13226. * a plain `Array` instance.
  13227. *
  13228. * @augments BufferAttribute
  13229. */
  13230. class Uint32BufferAttribute extends BufferAttribute {
  13231. /**
  13232. * Constructs a new buffer attribute.
  13233. *
  13234. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13235. * @param {number} itemSize - The item size.
  13236. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13237. */
  13238. constructor( array, itemSize, normalized ) {
  13239. super( new Uint32Array( array ), itemSize, normalized );
  13240. }
  13241. }
  13242. /**
  13243. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13244. * a plain `Array` instance.
  13245. *
  13246. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13247. * browser support is still problematic.
  13248. *
  13249. * @augments BufferAttribute
  13250. */
  13251. class Float16BufferAttribute extends BufferAttribute {
  13252. /**
  13253. * Constructs a new buffer attribute.
  13254. *
  13255. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13256. * @param {number} itemSize - The item size.
  13257. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13258. */
  13259. constructor( array, itemSize, normalized ) {
  13260. super( new Uint16Array( array ), itemSize, normalized );
  13261. this.isFloat16BufferAttribute = true;
  13262. }
  13263. getX( index ) {
  13264. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  13265. if ( this.normalized ) x = denormalize( x, this.array );
  13266. return x;
  13267. }
  13268. setX( index, x ) {
  13269. if ( this.normalized ) x = normalize( x, this.array );
  13270. this.array[ index * this.itemSize ] = toHalfFloat( x );
  13271. return this;
  13272. }
  13273. getY( index ) {
  13274. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  13275. if ( this.normalized ) y = denormalize( y, this.array );
  13276. return y;
  13277. }
  13278. setY( index, y ) {
  13279. if ( this.normalized ) y = normalize( y, this.array );
  13280. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  13281. return this;
  13282. }
  13283. getZ( index ) {
  13284. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  13285. if ( this.normalized ) z = denormalize( z, this.array );
  13286. return z;
  13287. }
  13288. setZ( index, z ) {
  13289. if ( this.normalized ) z = normalize( z, this.array );
  13290. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  13291. return this;
  13292. }
  13293. getW( index ) {
  13294. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  13295. if ( this.normalized ) w = denormalize( w, this.array );
  13296. return w;
  13297. }
  13298. setW( index, w ) {
  13299. if ( this.normalized ) w = normalize( w, this.array );
  13300. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  13301. return this;
  13302. }
  13303. setXY( index, x, y ) {
  13304. index *= this.itemSize;
  13305. if ( this.normalized ) {
  13306. x = normalize( x, this.array );
  13307. y = normalize( y, this.array );
  13308. }
  13309. this.array[ index + 0 ] = toHalfFloat( x );
  13310. this.array[ index + 1 ] = toHalfFloat( y );
  13311. return this;
  13312. }
  13313. setXYZ( index, x, y, z ) {
  13314. index *= this.itemSize;
  13315. if ( this.normalized ) {
  13316. x = normalize( x, this.array );
  13317. y = normalize( y, this.array );
  13318. z = normalize( z, this.array );
  13319. }
  13320. this.array[ index + 0 ] = toHalfFloat( x );
  13321. this.array[ index + 1 ] = toHalfFloat( y );
  13322. this.array[ index + 2 ] = toHalfFloat( z );
  13323. return this;
  13324. }
  13325. setXYZW( index, x, y, z, w ) {
  13326. index *= this.itemSize;
  13327. if ( this.normalized ) {
  13328. x = normalize( x, this.array );
  13329. y = normalize( y, this.array );
  13330. z = normalize( z, this.array );
  13331. w = normalize( w, this.array );
  13332. }
  13333. this.array[ index + 0 ] = toHalfFloat( x );
  13334. this.array[ index + 1 ] = toHalfFloat( y );
  13335. this.array[ index + 2 ] = toHalfFloat( z );
  13336. this.array[ index + 3 ] = toHalfFloat( w );
  13337. return this;
  13338. }
  13339. }
  13340. /**
  13341. * Convenient class that can be used when creating a `Float32` buffer attribute with
  13342. * a plain `Array` instance.
  13343. *
  13344. * @augments BufferAttribute
  13345. */
  13346. class Float32BufferAttribute extends BufferAttribute {
  13347. /**
  13348. * Constructs a new buffer attribute.
  13349. *
  13350. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  13351. * @param {number} itemSize - The item size.
  13352. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13353. */
  13354. constructor( array, itemSize, normalized ) {
  13355. super( new Float32Array( array ), itemSize, normalized );
  13356. }
  13357. }
  13358. const _box$3 = /*@__PURE__*/ new Box3();
  13359. const _v1$3 = /*@__PURE__*/ new Vector3();
  13360. const _v2$2 = /*@__PURE__*/ new Vector3();
  13361. /**
  13362. * An analytical 3D sphere defined by a center and radius. This class is mainly
  13363. * used as a Bounding Sphere for 3D objects.
  13364. */
  13365. class Sphere {
  13366. /**
  13367. * Constructs a new sphere.
  13368. *
  13369. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  13370. * @param {number} [radius=-1] - The radius of the sphere.
  13371. */
  13372. constructor( center = new Vector3(), radius = -1 ) {
  13373. /**
  13374. * This flag can be used for type testing.
  13375. *
  13376. * @type {boolean}
  13377. * @readonly
  13378. * @default true
  13379. */
  13380. this.isSphere = true;
  13381. /**
  13382. * The center of the sphere
  13383. *
  13384. * @type {Vector3}
  13385. */
  13386. this.center = center;
  13387. /**
  13388. * The radius of the sphere.
  13389. *
  13390. * @type {number}
  13391. */
  13392. this.radius = radius;
  13393. }
  13394. /**
  13395. * Sets the sphere's components by copying the given values.
  13396. *
  13397. * @param {Vector3} center - The center.
  13398. * @param {number} radius - The radius.
  13399. * @return {Sphere} A reference to this sphere.
  13400. */
  13401. set( center, radius ) {
  13402. this.center.copy( center );
  13403. this.radius = radius;
  13404. return this;
  13405. }
  13406. /**
  13407. * Computes the minimum bounding sphere for list of points.
  13408. * If the optional center point is given, it is used as the sphere's
  13409. * center. Otherwise, the center of the axis-aligned bounding box
  13410. * encompassing the points is calculated.
  13411. *
  13412. * @param {Array<Vector3>} points - A list of points in 3D space.
  13413. * @param {Vector3} [optionalCenter] - The center of the sphere.
  13414. * @return {Sphere} A reference to this sphere.
  13415. */
  13416. setFromPoints( points, optionalCenter ) {
  13417. const center = this.center;
  13418. if ( optionalCenter !== undefined ) {
  13419. center.copy( optionalCenter );
  13420. } else {
  13421. _box$3.setFromPoints( points ).getCenter( center );
  13422. }
  13423. let maxRadiusSq = 0;
  13424. for ( let i = 0, il = points.length; i < il; i ++ ) {
  13425. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  13426. }
  13427. this.radius = Math.sqrt( maxRadiusSq );
  13428. return this;
  13429. }
  13430. /**
  13431. * Copies the values of the given sphere to this instance.
  13432. *
  13433. * @param {Sphere} sphere - The sphere to copy.
  13434. * @return {Sphere} A reference to this sphere.
  13435. */
  13436. copy( sphere ) {
  13437. this.center.copy( sphere.center );
  13438. this.radius = sphere.radius;
  13439. return this;
  13440. }
  13441. /**
  13442. * Returns `true` if the sphere is empty (the radius set to a negative number).
  13443. *
  13444. * Spheres with a radius of `0` contain only their center point and are not
  13445. * considered to be empty.
  13446. *
  13447. * @return {boolean} Whether this sphere is empty or not.
  13448. */
  13449. isEmpty() {
  13450. return ( this.radius < 0 );
  13451. }
  13452. /**
  13453. * Makes this sphere empty which means in encloses a zero space in 3D.
  13454. *
  13455. * @return {Sphere} A reference to this sphere.
  13456. */
  13457. makeEmpty() {
  13458. this.center.set( 0, 0, 0 );
  13459. this.radius = -1;
  13460. return this;
  13461. }
  13462. /**
  13463. * Returns `true` if this sphere contains the given point inclusive of
  13464. * the surface of the sphere.
  13465. *
  13466. * @param {Vector3} point - The point to check.
  13467. * @return {boolean} Whether this sphere contains the given point or not.
  13468. */
  13469. containsPoint( point ) {
  13470. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  13471. }
  13472. /**
  13473. * Returns the closest distance from the boundary of the sphere to the
  13474. * given point. If the sphere contains the point, the distance will
  13475. * be negative.
  13476. *
  13477. * @param {Vector3} point - The point to compute the distance to.
  13478. * @return {number} The distance to the point.
  13479. */
  13480. distanceToPoint( point ) {
  13481. return ( point.distanceTo( this.center ) - this.radius );
  13482. }
  13483. /**
  13484. * Returns `true` if this sphere intersects with the given one.
  13485. *
  13486. * @param {Sphere} sphere - The sphere to test.
  13487. * @return {boolean} Whether this sphere intersects with the given one or not.
  13488. */
  13489. intersectsSphere( sphere ) {
  13490. const radiusSum = this.radius + sphere.radius;
  13491. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  13492. }
  13493. /**
  13494. * Returns `true` if this sphere intersects with the given box.
  13495. *
  13496. * @param {Box3} box - The box to test.
  13497. * @return {boolean} Whether this sphere intersects with the given box or not.
  13498. */
  13499. intersectsBox( box ) {
  13500. return box.intersectsSphere( this );
  13501. }
  13502. /**
  13503. * Returns `true` if this sphere intersects with the given plane.
  13504. *
  13505. * @param {Plane} plane - The plane to test.
  13506. * @return {boolean} Whether this sphere intersects with the given plane or not.
  13507. */
  13508. intersectsPlane( plane ) {
  13509. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  13510. }
  13511. /**
  13512. * Clamps a point within the sphere. If the point is outside the sphere, it
  13513. * will clamp it to the closest point on the edge of the sphere. Points
  13514. * already inside the sphere will not be affected.
  13515. *
  13516. * @param {Vector3} point - The plane to clamp.
  13517. * @param {Vector3} target - The target vector that is used to store the method's result.
  13518. * @return {Vector3} The clamped point.
  13519. */
  13520. clampPoint( point, target ) {
  13521. const deltaLengthSq = this.center.distanceToSquared( point );
  13522. target.copy( point );
  13523. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  13524. target.sub( this.center ).normalize();
  13525. target.multiplyScalar( this.radius ).add( this.center );
  13526. }
  13527. return target;
  13528. }
  13529. /**
  13530. * Returns a bounding box that encloses this sphere.
  13531. *
  13532. * @param {Box3} target - The target box that is used to store the method's result.
  13533. * @return {Box3} The bounding box that encloses this sphere.
  13534. */
  13535. getBoundingBox( target ) {
  13536. if ( this.isEmpty() ) {
  13537. // Empty sphere produces empty bounding box
  13538. target.makeEmpty();
  13539. return target;
  13540. }
  13541. target.set( this.center, this.center );
  13542. target.expandByScalar( this.radius );
  13543. return target;
  13544. }
  13545. /**
  13546. * Transforms this sphere with the given 4x4 transformation matrix.
  13547. *
  13548. * @param {Matrix4} matrix - The transformation matrix.
  13549. * @return {Sphere} A reference to this sphere.
  13550. */
  13551. applyMatrix4( matrix ) {
  13552. this.center.applyMatrix4( matrix );
  13553. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  13554. return this;
  13555. }
  13556. /**
  13557. * Translates the sphere's center by the given offset.
  13558. *
  13559. * @param {Vector3} offset - The offset.
  13560. * @return {Sphere} A reference to this sphere.
  13561. */
  13562. translate( offset ) {
  13563. this.center.add( offset );
  13564. return this;
  13565. }
  13566. /**
  13567. * Expands the boundaries of this sphere to include the given point.
  13568. *
  13569. * @param {Vector3} point - The point to include.
  13570. * @return {Sphere} A reference to this sphere.
  13571. */
  13572. expandByPoint( point ) {
  13573. if ( this.isEmpty() ) {
  13574. this.center.copy( point );
  13575. this.radius = 0;
  13576. return this;
  13577. }
  13578. _v1$3.subVectors( point, this.center );
  13579. const lengthSq = _v1$3.lengthSq();
  13580. if ( lengthSq > ( this.radius * this.radius ) ) {
  13581. // calculate the minimal sphere
  13582. const length = Math.sqrt( lengthSq );
  13583. const delta = ( length - this.radius ) * 0.5;
  13584. this.center.addScaledVector( _v1$3, delta / length );
  13585. this.radius += delta;
  13586. }
  13587. return this;
  13588. }
  13589. /**
  13590. * Expands this sphere to enclose both the original sphere and the given sphere.
  13591. *
  13592. * @param {Sphere} sphere - The sphere to include.
  13593. * @return {Sphere} A reference to this sphere.
  13594. */
  13595. union( sphere ) {
  13596. if ( sphere.isEmpty() ) {
  13597. return this;
  13598. }
  13599. if ( this.isEmpty() ) {
  13600. this.copy( sphere );
  13601. return this;
  13602. }
  13603. if ( this.center.equals( sphere.center ) === true ) {
  13604. this.radius = Math.max( this.radius, sphere.radius );
  13605. } else {
  13606. _v2$2.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  13607. this.expandByPoint( _v1$3.copy( sphere.center ).add( _v2$2 ) );
  13608. this.expandByPoint( _v1$3.copy( sphere.center ).sub( _v2$2 ) );
  13609. }
  13610. return this;
  13611. }
  13612. /**
  13613. * Returns `true` if this sphere is equal with the given one.
  13614. *
  13615. * @param {Sphere} sphere - The sphere to test for equality.
  13616. * @return {boolean} Whether this bounding sphere is equal with the given one.
  13617. */
  13618. equals( sphere ) {
  13619. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  13620. }
  13621. /**
  13622. * Returns a new sphere with copied values from this instance.
  13623. *
  13624. * @return {Sphere} A clone of this instance.
  13625. */
  13626. clone() {
  13627. return new this.constructor().copy( this );
  13628. }
  13629. /**
  13630. * Returns a serialized structure of the bounding sphere.
  13631. *
  13632. * @return {Object} Serialized structure with fields representing the object state.
  13633. */
  13634. toJSON() {
  13635. return {
  13636. radius: this.radius,
  13637. center: this.center.toArray()
  13638. };
  13639. }
  13640. /**
  13641. * Returns a serialized structure of the bounding sphere.
  13642. *
  13643. * @param {Object} json - The serialized json to set the sphere from.
  13644. * @return {Sphere} A reference to this bounding sphere.
  13645. */
  13646. fromJSON( json ) {
  13647. this.radius = json.radius;
  13648. this.center.fromArray( json.center );
  13649. return this;
  13650. }
  13651. }
  13652. let _id$1 = 0;
  13653. const _m1 = /*@__PURE__*/ new Matrix4();
  13654. const _obj = /*@__PURE__*/ new Object3D();
  13655. const _offset = /*@__PURE__*/ new Vector3();
  13656. const _box$2 = /*@__PURE__*/ new Box3();
  13657. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  13658. const _vector$9 = /*@__PURE__*/ new Vector3();
  13659. /**
  13660. * A representation of mesh, line, or point geometry. Includes vertex
  13661. * positions, face indices, normals, colors, UVs, and custom attributes
  13662. * within buffers, reducing the cost of passing all this data to the GPU.
  13663. *
  13664. * ```js
  13665. * const geometry = new THREE.BufferGeometry();
  13666. * // create a simple square shape. We duplicate the top left and bottom right
  13667. * // vertices because each vertex needs to appear once per triangle.
  13668. * const vertices = new Float32Array( [
  13669. * -1.0, -1.0, 1.0, // v0
  13670. * 1.0, -1.0, 1.0, // v1
  13671. * 1.0, 1.0, 1.0, // v2
  13672. *
  13673. * 1.0, 1.0, 1.0, // v3
  13674. * -1.0, 1.0, 1.0, // v4
  13675. * -1.0, -1.0, 1.0 // v5
  13676. * ] );
  13677. * // itemSize = 3 because there are 3 values (components) per vertex
  13678. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13679. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  13680. * const mesh = new THREE.Mesh( geometry, material );
  13681. * ```
  13682. *
  13683. * @augments EventDispatcher
  13684. */
  13685. class BufferGeometry extends EventDispatcher {
  13686. /**
  13687. * Constructs a new geometry.
  13688. */
  13689. constructor() {
  13690. super();
  13691. /**
  13692. * This flag can be used for type testing.
  13693. *
  13694. * @type {boolean}
  13695. * @readonly
  13696. * @default true
  13697. */
  13698. this.isBufferGeometry = true;
  13699. /**
  13700. * The ID of the geometry.
  13701. *
  13702. * @name BufferGeometry#id
  13703. * @type {number}
  13704. * @readonly
  13705. */
  13706. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  13707. /**
  13708. * The UUID of the geometry.
  13709. *
  13710. * @type {string}
  13711. * @readonly
  13712. */
  13713. this.uuid = generateUUID();
  13714. /**
  13715. * The name of the geometry.
  13716. *
  13717. * @type {string}
  13718. */
  13719. this.name = '';
  13720. this.type = 'BufferGeometry';
  13721. /**
  13722. * Allows for vertices to be re-used across multiple triangles; this is
  13723. * called using "indexed triangles". Each triangle is associated with the
  13724. * indices of three vertices. This attribute therefore stores the index of
  13725. * each vertex for each triangular face. If this attribute is not set, the
  13726. * renderer assumes that each three contiguous positions represent a single triangle.
  13727. *
  13728. * @type {?BufferAttribute}
  13729. * @default null
  13730. */
  13731. this.index = null;
  13732. /**
  13733. * A (storage) buffer attribute which was generated with a compute shader and
  13734. * now defines indirect draw calls.
  13735. *
  13736. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13737. *
  13738. * @type {?BufferAttribute}
  13739. * @default null
  13740. */
  13741. this.indirect = null;
  13742. /**
  13743. * 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.
  13744. *
  13745. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  13746. *
  13747. * @type {number|Array<number>}
  13748. * @default 0
  13749. */
  13750. this.indirectOffset = 0;
  13751. /**
  13752. * This dictionary has as id the name of the attribute to be set and as value
  13753. * the buffer attribute to set it to. Rather than accessing this property directly,
  13754. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  13755. *
  13756. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  13757. */
  13758. this.attributes = {};
  13759. /**
  13760. * This dictionary holds the morph targets of the geometry.
  13761. *
  13762. * Note: Once the geometry has been rendered, the morph attribute data cannot
  13763. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  13764. *
  13765. * @type {Object}
  13766. */
  13767. this.morphAttributes = {};
  13768. /**
  13769. * Used to control the morph target behavior; when set to `true`, the morph
  13770. * target data is treated as relative offsets, rather than as absolute
  13771. * positions/normals.
  13772. *
  13773. * @type {boolean}
  13774. * @default false
  13775. */
  13776. this.morphTargetsRelative = false;
  13777. /**
  13778. * Split the geometry into groups, each of which will be rendered in a
  13779. * separate draw call. This allows an array of materials to be used with the geometry.
  13780. *
  13781. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  13782. *
  13783. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  13784. * indices, and must not leave vertices or indices unused.
  13785. *
  13786. * @type {Array<Object>}
  13787. */
  13788. this.groups = [];
  13789. /**
  13790. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  13791. *
  13792. * @type {?Box3}
  13793. * @default null
  13794. */
  13795. this.boundingBox = null;
  13796. /**
  13797. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  13798. *
  13799. * @type {?Sphere}
  13800. * @default null
  13801. */
  13802. this.boundingSphere = null;
  13803. /**
  13804. * Determines the part of the geometry to render. This should not be set directly,
  13805. * instead use `setDrawRange()`.
  13806. *
  13807. * @type {{start:number,count:number}}
  13808. */
  13809. this.drawRange = { start: 0, count: Infinity };
  13810. /**
  13811. * An object that can be used to store custom data about the geometry.
  13812. * It should not hold references to functions as these will not be cloned.
  13813. *
  13814. * @type {Object}
  13815. */
  13816. this.userData = {};
  13817. /**
  13818. * `true` when the geometry has been transformed since construction
  13819. * (e.g. via {@link BufferGeometry#applyMatrix4}). Only relevant for
  13820. * geometry generators (subclasses that populate `parameters`): when set,
  13821. * {@link BufferGeometry#toJSON} omits `parameters` since they no longer
  13822. * describe the geometry.
  13823. *
  13824. * @private
  13825. * @type {boolean}
  13826. * @default false
  13827. */
  13828. this._transformed = false;
  13829. }
  13830. /**
  13831. * Returns the index of this geometry.
  13832. *
  13833. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  13834. */
  13835. getIndex() {
  13836. return this.index;
  13837. }
  13838. /**
  13839. * Sets the given index to this geometry.
  13840. *
  13841. * @param {Array<number>|BufferAttribute} index - The index to set.
  13842. * @return {BufferGeometry} A reference to this instance.
  13843. */
  13844. setIndex( index ) {
  13845. if ( Array.isArray( index ) ) {
  13846. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  13847. } else {
  13848. this.index = index;
  13849. }
  13850. return this;
  13851. }
  13852. /**
  13853. * Sets the given indirect attribute to this geometry.
  13854. *
  13855. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  13856. * @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.
  13857. * @return {BufferGeometry} A reference to this instance.
  13858. */
  13859. setIndirect( indirect, indirectOffset = 0 ) {
  13860. this.indirect = indirect;
  13861. this.indirectOffset = indirectOffset;
  13862. return this;
  13863. }
  13864. /**
  13865. * Returns the indirect attribute of this geometry.
  13866. *
  13867. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  13868. */
  13869. getIndirect() {
  13870. return this.indirect;
  13871. }
  13872. /**
  13873. * Returns the buffer attribute for the given name.
  13874. *
  13875. * @param {string} name - The attribute name.
  13876. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  13877. * Returns `undefined` if not attribute has been found.
  13878. */
  13879. getAttribute( name ) {
  13880. return this.attributes[ name ];
  13881. }
  13882. /**
  13883. * Sets the given attribute for the given name.
  13884. *
  13885. * @param {string} name - The attribute name.
  13886. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  13887. * @return {BufferGeometry} A reference to this instance.
  13888. */
  13889. setAttribute( name, attribute ) {
  13890. this.attributes[ name ] = attribute;
  13891. return this;
  13892. }
  13893. /**
  13894. * Deletes the attribute for the given name.
  13895. *
  13896. * @param {string} name - The attribute name to delete.
  13897. * @return {BufferGeometry} A reference to this instance.
  13898. */
  13899. deleteAttribute( name ) {
  13900. delete this.attributes[ name ];
  13901. return this;
  13902. }
  13903. /**
  13904. * Returns `true` if this geometry has an attribute for the given name.
  13905. *
  13906. * @param {string} name - The attribute name.
  13907. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  13908. */
  13909. hasAttribute( name ) {
  13910. return this.attributes[ name ] !== undefined;
  13911. }
  13912. /**
  13913. * Adds a group to this geometry.
  13914. *
  13915. * @param {number} start - The first element in this draw call. That is the first
  13916. * vertex for non-indexed geometry, otherwise the first triangle index.
  13917. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  13918. * @param {number} [materialIndex=0] - The material array index to use.
  13919. */
  13920. addGroup( start, count, materialIndex = 0 ) {
  13921. this.groups.push( {
  13922. start: start,
  13923. count: count,
  13924. materialIndex: materialIndex
  13925. } );
  13926. }
  13927. /**
  13928. * Clears all groups.
  13929. */
  13930. clearGroups() {
  13931. this.groups = [];
  13932. }
  13933. /**
  13934. * Sets the draw range for this geometry.
  13935. *
  13936. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  13937. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  13938. * For indexed BufferGeometry, `count` is the number of indices to render.
  13939. */
  13940. setDrawRange( start, count ) {
  13941. this.drawRange.start = start;
  13942. this.drawRange.count = count;
  13943. }
  13944. /**
  13945. * Applies the given 4x4 transformation matrix to the geometry.
  13946. *
  13947. * @param {Matrix4} matrix - The matrix to apply.
  13948. * @return {BufferGeometry} A reference to this instance.
  13949. */
  13950. applyMatrix4( matrix ) {
  13951. const position = this.attributes.position;
  13952. if ( position !== undefined ) {
  13953. position.applyMatrix4( matrix );
  13954. position.needsUpdate = true;
  13955. }
  13956. const normal = this.attributes.normal;
  13957. if ( normal !== undefined ) {
  13958. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  13959. normal.applyNormalMatrix( normalMatrix );
  13960. normal.needsUpdate = true;
  13961. }
  13962. const tangent = this.attributes.tangent;
  13963. if ( tangent !== undefined ) {
  13964. tangent.transformDirection( matrix );
  13965. tangent.needsUpdate = true;
  13966. }
  13967. if ( this.boundingBox !== null ) {
  13968. this.computeBoundingBox();
  13969. }
  13970. if ( this.boundingSphere !== null ) {
  13971. this.computeBoundingSphere();
  13972. }
  13973. this._transformed = true;
  13974. return this;
  13975. }
  13976. /**
  13977. * Applies the rotation represented by the Quaternion to the geometry.
  13978. *
  13979. * @param {Quaternion} q - The Quaternion to apply.
  13980. * @return {BufferGeometry} A reference to this instance.
  13981. */
  13982. applyQuaternion( q ) {
  13983. _m1.makeRotationFromQuaternion( q );
  13984. this.applyMatrix4( _m1 );
  13985. return this;
  13986. }
  13987. /**
  13988. * Rotates the geometry about the X axis. This is typically done as a one time
  13989. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  13990. * real-time mesh rotation.
  13991. *
  13992. * @param {number} angle - The angle in radians.
  13993. * @return {BufferGeometry} A reference to this instance.
  13994. */
  13995. rotateX( angle ) {
  13996. // rotate geometry around world x-axis
  13997. _m1.makeRotationX( angle );
  13998. this.applyMatrix4( _m1 );
  13999. return this;
  14000. }
  14001. /**
  14002. * Rotates the geometry about the Y axis. This is typically done as a one time
  14003. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14004. * real-time mesh rotation.
  14005. *
  14006. * @param {number} angle - The angle in radians.
  14007. * @return {BufferGeometry} A reference to this instance.
  14008. */
  14009. rotateY( angle ) {
  14010. // rotate geometry around world y-axis
  14011. _m1.makeRotationY( angle );
  14012. this.applyMatrix4( _m1 );
  14013. return this;
  14014. }
  14015. /**
  14016. * Rotates the geometry about the Z axis. This is typically done as a one time
  14017. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14018. * real-time mesh rotation.
  14019. *
  14020. * @param {number} angle - The angle in radians.
  14021. * @return {BufferGeometry} A reference to this instance.
  14022. */
  14023. rotateZ( angle ) {
  14024. // rotate geometry around world z-axis
  14025. _m1.makeRotationZ( angle );
  14026. this.applyMatrix4( _m1 );
  14027. return this;
  14028. }
  14029. /**
  14030. * Translates the geometry. This is typically done as a one time
  14031. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14032. * real-time mesh rotation.
  14033. *
  14034. * @param {number} x - The x offset.
  14035. * @param {number} y - The y offset.
  14036. * @param {number} z - The z offset.
  14037. * @return {BufferGeometry} A reference to this instance.
  14038. */
  14039. translate( x, y, z ) {
  14040. // translate geometry
  14041. _m1.makeTranslation( x, y, z );
  14042. this.applyMatrix4( _m1 );
  14043. return this;
  14044. }
  14045. /**
  14046. * Scales the geometry. This is typically done as a one time
  14047. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14048. * real-time mesh rotation.
  14049. *
  14050. * @param {number} x - The x scale.
  14051. * @param {number} y - The y scale.
  14052. * @param {number} z - The z scale.
  14053. * @return {BufferGeometry} A reference to this instance.
  14054. */
  14055. scale( x, y, z ) {
  14056. // scale geometry
  14057. _m1.makeScale( x, y, z );
  14058. this.applyMatrix4( _m1 );
  14059. return this;
  14060. }
  14061. /**
  14062. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14063. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14064. * real-time mesh rotation.
  14065. *
  14066. * @param {Vector3} vector - The target point.
  14067. * @return {BufferGeometry} A reference to this instance.
  14068. */
  14069. lookAt( vector ) {
  14070. _obj.lookAt( vector );
  14071. _obj.updateMatrix();
  14072. this.applyMatrix4( _obj.matrix );
  14073. return this;
  14074. }
  14075. /**
  14076. * Center the geometry based on its bounding box.
  14077. *
  14078. * @return {BufferGeometry} A reference to this instance.
  14079. */
  14080. center() {
  14081. this.computeBoundingBox();
  14082. this.boundingBox.getCenter( _offset ).negate();
  14083. this.translate( _offset.x, _offset.y, _offset.z );
  14084. return this;
  14085. }
  14086. /**
  14087. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14088. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14089. * set to `0`.
  14090. *
  14091. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14092. * data from the array. The length of the array must match the vertex count.
  14093. *
  14094. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14095. * @return {BufferGeometry} A reference to this instance.
  14096. */
  14097. setFromPoints( points ) {
  14098. const positionAttribute = this.getAttribute( 'position' );
  14099. if ( positionAttribute === undefined ) {
  14100. const position = [];
  14101. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14102. const point = points[ i ];
  14103. position.push( point.x, point.y, point.z || 0 );
  14104. }
  14105. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14106. } else {
  14107. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14108. for ( let i = 0; i < l; i ++ ) {
  14109. const point = points[ i ];
  14110. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14111. }
  14112. if ( points.length > positionAttribute.count ) {
  14113. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14114. }
  14115. positionAttribute.needsUpdate = true;
  14116. }
  14117. return this;
  14118. }
  14119. /**
  14120. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14121. * The bounding box is not computed by the engine; it must be computed by your app.
  14122. * You may need to recompute the bounding box if the geometry vertices are modified.
  14123. */
  14124. computeBoundingBox() {
  14125. if ( this.boundingBox === null ) {
  14126. this.boundingBox = new Box3();
  14127. }
  14128. const position = this.attributes.position;
  14129. const morphAttributesPosition = this.morphAttributes.position;
  14130. if ( position && position.isGLBufferAttribute ) {
  14131. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14132. this.boundingBox.set(
  14133. new Vector3( - Infinity, - Infinity, - Infinity ),
  14134. new Vector3( + Infinity, + Infinity, + Infinity )
  14135. );
  14136. return;
  14137. }
  14138. if ( position !== undefined ) {
  14139. this.boundingBox.setFromBufferAttribute( position );
  14140. // process morph attributes if present
  14141. if ( morphAttributesPosition ) {
  14142. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14143. const morphAttribute = morphAttributesPosition[ i ];
  14144. _box$2.setFromBufferAttribute( morphAttribute );
  14145. if ( this.morphTargetsRelative ) {
  14146. _vector$9.addVectors( this.boundingBox.min, _box$2.min );
  14147. this.boundingBox.expandByPoint( _vector$9 );
  14148. _vector$9.addVectors( this.boundingBox.max, _box$2.max );
  14149. this.boundingBox.expandByPoint( _vector$9 );
  14150. } else {
  14151. this.boundingBox.expandByPoint( _box$2.min );
  14152. this.boundingBox.expandByPoint( _box$2.max );
  14153. }
  14154. }
  14155. }
  14156. } else {
  14157. this.boundingBox.makeEmpty();
  14158. }
  14159. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14160. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14161. }
  14162. }
  14163. /**
  14164. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14165. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14166. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14167. */
  14168. computeBoundingSphere() {
  14169. if ( this.boundingSphere === null ) {
  14170. this.boundingSphere = new Sphere();
  14171. }
  14172. const position = this.attributes.position;
  14173. const morphAttributesPosition = this.morphAttributes.position;
  14174. if ( position && position.isGLBufferAttribute ) {
  14175. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14176. this.boundingSphere.set( new Vector3(), Infinity );
  14177. return;
  14178. }
  14179. if ( position ) {
  14180. // first, find the center of the bounding sphere
  14181. const center = this.boundingSphere.center;
  14182. _box$2.setFromBufferAttribute( position );
  14183. // process morph attributes if present
  14184. if ( morphAttributesPosition ) {
  14185. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14186. const morphAttribute = morphAttributesPosition[ i ];
  14187. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14188. if ( this.morphTargetsRelative ) {
  14189. _vector$9.addVectors( _box$2.min, _boxMorphTargets.min );
  14190. _box$2.expandByPoint( _vector$9 );
  14191. _vector$9.addVectors( _box$2.max, _boxMorphTargets.max );
  14192. _box$2.expandByPoint( _vector$9 );
  14193. } else {
  14194. _box$2.expandByPoint( _boxMorphTargets.min );
  14195. _box$2.expandByPoint( _boxMorphTargets.max );
  14196. }
  14197. }
  14198. }
  14199. _box$2.getCenter( center );
  14200. // second, try to find a boundingSphere with a radius smaller than the
  14201. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14202. let maxRadiusSq = 0;
  14203. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14204. _vector$9.fromBufferAttribute( position, i );
  14205. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14206. }
  14207. // process morph attributes if present
  14208. if ( morphAttributesPosition ) {
  14209. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14210. const morphAttribute = morphAttributesPosition[ i ];
  14211. const morphTargetsRelative = this.morphTargetsRelative;
  14212. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14213. _vector$9.fromBufferAttribute( morphAttribute, j );
  14214. if ( morphTargetsRelative ) {
  14215. _offset.fromBufferAttribute( position, j );
  14216. _vector$9.add( _offset );
  14217. }
  14218. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$9 ) );
  14219. }
  14220. }
  14221. }
  14222. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14223. if ( isNaN( this.boundingSphere.radius ) ) {
  14224. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14225. }
  14226. }
  14227. }
  14228. /**
  14229. * Calculates and adds a tangent attribute to this geometry.
  14230. *
  14231. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14232. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14233. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14234. */
  14235. computeTangents() {
  14236. const index = this.index;
  14237. const attributes = this.attributes;
  14238. // based on http://www.terathon.com/code/tangent.html
  14239. // (per vertex tangents)
  14240. if ( index === null ||
  14241. attributes.position === undefined ||
  14242. attributes.normal === undefined ||
  14243. attributes.uv === undefined ) {
  14244. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14245. return;
  14246. }
  14247. const positionAttribute = attributes.position;
  14248. const normalAttribute = attributes.normal;
  14249. const uvAttribute = attributes.uv;
  14250. let tangentAttribute = this.getAttribute( 'tangent' );
  14251. if ( tangentAttribute === undefined || tangentAttribute.count !== positionAttribute.count ) {
  14252. tangentAttribute = new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 );
  14253. this.setAttribute( 'tangent', tangentAttribute );
  14254. }
  14255. const tan1 = [], tan2 = [];
  14256. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14257. tan1[ i ] = new Vector3();
  14258. tan2[ i ] = new Vector3();
  14259. }
  14260. const vA = new Vector3(),
  14261. vB = new Vector3(),
  14262. vC = new Vector3(),
  14263. uvA = new Vector2(),
  14264. uvB = new Vector2(),
  14265. uvC = new Vector2(),
  14266. sdir = new Vector3(),
  14267. tdir = new Vector3();
  14268. function handleTriangle( a, b, c ) {
  14269. vA.fromBufferAttribute( positionAttribute, a );
  14270. vB.fromBufferAttribute( positionAttribute, b );
  14271. vC.fromBufferAttribute( positionAttribute, c );
  14272. uvA.fromBufferAttribute( uvAttribute, a );
  14273. uvB.fromBufferAttribute( uvAttribute, b );
  14274. uvC.fromBufferAttribute( uvAttribute, c );
  14275. vB.sub( vA );
  14276. vC.sub( vA );
  14277. uvB.sub( uvA );
  14278. uvC.sub( uvA );
  14279. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14280. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14281. if ( ! isFinite( r ) ) return;
  14282. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14283. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14284. tan1[ a ].add( sdir );
  14285. tan1[ b ].add( sdir );
  14286. tan1[ c ].add( sdir );
  14287. tan2[ a ].add( tdir );
  14288. tan2[ b ].add( tdir );
  14289. tan2[ c ].add( tdir );
  14290. }
  14291. let groups = this.groups;
  14292. if ( groups.length === 0 ) {
  14293. groups = [ {
  14294. start: 0,
  14295. count: index.count
  14296. } ];
  14297. }
  14298. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14299. const group = groups[ i ];
  14300. const start = group.start;
  14301. const count = group.count;
  14302. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14303. handleTriangle(
  14304. index.getX( j + 0 ),
  14305. index.getX( j + 1 ),
  14306. index.getX( j + 2 )
  14307. );
  14308. }
  14309. }
  14310. const tmp = new Vector3(), tmp2 = new Vector3();
  14311. const n = new Vector3(), n2 = new Vector3();
  14312. function handleVertex( v ) {
  14313. n.fromBufferAttribute( normalAttribute, v );
  14314. n2.copy( n );
  14315. const t = tan1[ v ];
  14316. // Gram-Schmidt orthogonalize
  14317. tmp.copy( t );
  14318. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14319. // Calculate handedness
  14320. tmp2.crossVectors( n2, t );
  14321. const test = tmp2.dot( tan2[ v ] );
  14322. const w = ( test < 0.0 ) ? -1 : 1.0;
  14323. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14324. }
  14325. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14326. const group = groups[ i ];
  14327. const start = group.start;
  14328. const count = group.count;
  14329. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14330. handleVertex( index.getX( j + 0 ) );
  14331. handleVertex( index.getX( j + 1 ) );
  14332. handleVertex( index.getX( j + 2 ) );
  14333. }
  14334. }
  14335. this._transformed = true;
  14336. }
  14337. /**
  14338. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14339. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14340. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14341. * to be the same as the face normal.
  14342. */
  14343. computeVertexNormals() {
  14344. const index = this.index;
  14345. const positionAttribute = this.getAttribute( 'position' );
  14346. if ( positionAttribute !== undefined ) {
  14347. let normalAttribute = this.getAttribute( 'normal' );
  14348. if ( normalAttribute === undefined || normalAttribute.count !== positionAttribute.count ) {
  14349. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14350. this.setAttribute( 'normal', normalAttribute );
  14351. } else {
  14352. // reset existing normals to zero
  14353. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14354. normalAttribute.setXYZ( i, 0, 0, 0 );
  14355. }
  14356. }
  14357. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14358. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14359. const cb = new Vector3(), ab = new Vector3();
  14360. // indexed elements
  14361. if ( index ) {
  14362. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14363. const vA = index.getX( i + 0 );
  14364. const vB = index.getX( i + 1 );
  14365. const vC = index.getX( i + 2 );
  14366. pA.fromBufferAttribute( positionAttribute, vA );
  14367. pB.fromBufferAttribute( positionAttribute, vB );
  14368. pC.fromBufferAttribute( positionAttribute, vC );
  14369. cb.subVectors( pC, pB );
  14370. ab.subVectors( pA, pB );
  14371. cb.cross( ab );
  14372. nA.fromBufferAttribute( normalAttribute, vA );
  14373. nB.fromBufferAttribute( normalAttribute, vB );
  14374. nC.fromBufferAttribute( normalAttribute, vC );
  14375. nA.add( cb );
  14376. nB.add( cb );
  14377. nC.add( cb );
  14378. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14379. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14380. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14381. }
  14382. } else {
  14383. // non-indexed elements (unconnected triangle soup)
  14384. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14385. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14386. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14387. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14388. cb.subVectors( pC, pB );
  14389. ab.subVectors( pA, pB );
  14390. cb.cross( ab );
  14391. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14392. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14393. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14394. }
  14395. }
  14396. this.normalizeNormals();
  14397. normalAttribute.needsUpdate = true;
  14398. }
  14399. }
  14400. /**
  14401. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14402. * correct lighting on the geometry surfaces.
  14403. */
  14404. normalizeNormals() {
  14405. const normals = this.attributes.normal;
  14406. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14407. _vector$9.fromBufferAttribute( normals, i );
  14408. _vector$9.normalize();
  14409. normals.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  14410. }
  14411. }
  14412. /**
  14413. * Return a new non-index version of this indexed geometry. If the geometry
  14414. * is already non-indexed, the method is a NOOP.
  14415. *
  14416. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14417. */
  14418. toNonIndexed() {
  14419. function convertBufferAttribute( attribute, indices ) {
  14420. const array = attribute.array;
  14421. const itemSize = attribute.itemSize;
  14422. const normalized = attribute.normalized;
  14423. const array2 = new array.constructor( indices.length * itemSize );
  14424. let index = 0, index2 = 0;
  14425. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14426. if ( attribute.isInterleavedBufferAttribute ) {
  14427. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14428. } else {
  14429. index = indices[ i ] * itemSize;
  14430. }
  14431. for ( let j = 0; j < itemSize; j ++ ) {
  14432. array2[ index2 ++ ] = array[ index ++ ];
  14433. }
  14434. }
  14435. return new BufferAttribute( array2, itemSize, normalized );
  14436. }
  14437. //
  14438. if ( this.index === null ) {
  14439. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14440. return this;
  14441. }
  14442. const geometry2 = new BufferGeometry();
  14443. const indices = this.index.array;
  14444. const attributes = this.attributes;
  14445. // attributes
  14446. for ( const name in attributes ) {
  14447. const attribute = attributes[ name ];
  14448. const newAttribute = convertBufferAttribute( attribute, indices );
  14449. geometry2.setAttribute( name, newAttribute );
  14450. }
  14451. // morph attributes
  14452. const morphAttributes = this.morphAttributes;
  14453. for ( const name in morphAttributes ) {
  14454. const morphArray = [];
  14455. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14456. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14457. const attribute = morphAttribute[ i ];
  14458. const newAttribute = convertBufferAttribute( attribute, indices );
  14459. morphArray.push( newAttribute );
  14460. }
  14461. geometry2.morphAttributes[ name ] = morphArray;
  14462. }
  14463. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14464. // groups
  14465. const groups = this.groups;
  14466. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14467. const group = groups[ i ];
  14468. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14469. }
  14470. return geometry2;
  14471. }
  14472. /**
  14473. * Serializes the geometry into JSON.
  14474. *
  14475. * @return {Object} A JSON object representing the serialized geometry.
  14476. */
  14477. toJSON() {
  14478. const data = {
  14479. metadata: {
  14480. version: 4.7,
  14481. type: 'BufferGeometry',
  14482. generator: 'BufferGeometry.toJSON'
  14483. }
  14484. };
  14485. // standard BufferGeometry serialization
  14486. data.uuid = this.uuid;
  14487. data.type = ( this.parameters !== undefined && this._transformed === true ) ? 'BufferGeometry' : this.type;
  14488. if ( this.name !== '' ) data.name = this.name;
  14489. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14490. if ( this.parameters !== undefined && this._transformed !== true ) {
  14491. const parameters = this.parameters;
  14492. for ( const key in parameters ) {
  14493. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14494. }
  14495. return data;
  14496. }
  14497. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14498. data.data = { attributes: {} };
  14499. const index = this.index;
  14500. if ( index !== null ) {
  14501. data.data.index = {
  14502. type: index.array.constructor.name,
  14503. array: Array.prototype.slice.call( index.array )
  14504. };
  14505. }
  14506. const attributes = this.attributes;
  14507. for ( const key in attributes ) {
  14508. const attribute = attributes[ key ];
  14509. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14510. }
  14511. const morphAttributes = {};
  14512. let hasMorphAttributes = false;
  14513. for ( const key in this.morphAttributes ) {
  14514. const attributeArray = this.morphAttributes[ key ];
  14515. const array = [];
  14516. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14517. const attribute = attributeArray[ i ];
  14518. array.push( attribute.toJSON( data.data ) );
  14519. }
  14520. if ( array.length > 0 ) {
  14521. morphAttributes[ key ] = array;
  14522. hasMorphAttributes = true;
  14523. }
  14524. }
  14525. if ( hasMorphAttributes ) {
  14526. data.data.morphAttributes = morphAttributes;
  14527. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14528. }
  14529. const groups = this.groups;
  14530. if ( groups.length > 0 ) {
  14531. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14532. }
  14533. const boundingSphere = this.boundingSphere;
  14534. if ( boundingSphere !== null ) {
  14535. data.data.boundingSphere = boundingSphere.toJSON();
  14536. }
  14537. return data;
  14538. }
  14539. /**
  14540. * Returns a new geometry with copied values from this instance.
  14541. *
  14542. * @return {BufferGeometry} A clone of this instance.
  14543. */
  14544. clone() {
  14545. return new this.constructor().copy( this );
  14546. }
  14547. /**
  14548. * Copies the values of the given geometry to this instance.
  14549. *
  14550. * @param {BufferGeometry} source - The geometry to copy.
  14551. * @return {BufferGeometry} A reference to this instance.
  14552. */
  14553. copy( source ) {
  14554. // reset
  14555. this.index = null;
  14556. this.attributes = {};
  14557. this.morphAttributes = {};
  14558. this.groups = [];
  14559. this.boundingBox = null;
  14560. this.boundingSphere = null;
  14561. // used for storing cloned, shared data
  14562. const data = {};
  14563. // name
  14564. this.name = source.name;
  14565. // index
  14566. const index = source.index;
  14567. if ( index !== null ) {
  14568. this.setIndex( index.clone() );
  14569. }
  14570. // attributes
  14571. const attributes = source.attributes;
  14572. for ( const name in attributes ) {
  14573. const attribute = attributes[ name ];
  14574. this.setAttribute( name, attribute.clone( data ) );
  14575. }
  14576. // morph attributes
  14577. const morphAttributes = source.morphAttributes;
  14578. for ( const name in morphAttributes ) {
  14579. const array = [];
  14580. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14581. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  14582. array.push( morphAttribute[ i ].clone( data ) );
  14583. }
  14584. this.morphAttributes[ name ] = array;
  14585. }
  14586. this.morphTargetsRelative = source.morphTargetsRelative;
  14587. // groups
  14588. const groups = source.groups;
  14589. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14590. const group = groups[ i ];
  14591. this.addGroup( group.start, group.count, group.materialIndex );
  14592. }
  14593. // bounding box
  14594. const boundingBox = source.boundingBox;
  14595. if ( boundingBox !== null ) {
  14596. this.boundingBox = boundingBox.clone();
  14597. }
  14598. // bounding sphere
  14599. const boundingSphere = source.boundingSphere;
  14600. if ( boundingSphere !== null ) {
  14601. this.boundingSphere = boundingSphere.clone();
  14602. }
  14603. // draw range
  14604. this.drawRange.start = source.drawRange.start;
  14605. this.drawRange.count = source.drawRange.count;
  14606. // user data
  14607. this.userData = source.userData;
  14608. // transformed flag
  14609. this._transformed = source._transformed;
  14610. return this;
  14611. }
  14612. /**
  14613. * Frees the GPU-related resources allocated by this instance. Call this
  14614. * method whenever this instance is no longer used in your app.
  14615. *
  14616. * @fires BufferGeometry#dispose
  14617. */
  14618. dispose() {
  14619. this.dispatchEvent( { type: 'dispose' } );
  14620. }
  14621. }
  14622. /**
  14623. * "Interleaved" means that multiple attributes, possibly of different types,
  14624. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  14625. *
  14626. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  14627. */
  14628. class InterleavedBuffer {
  14629. /**
  14630. * Constructs a new interleaved buffer.
  14631. *
  14632. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  14633. * @param {number} stride - The number of typed-array elements per vertex.
  14634. */
  14635. constructor( array, stride ) {
  14636. /**
  14637. * This flag can be used for type testing.
  14638. *
  14639. * @type {boolean}
  14640. * @readonly
  14641. * @default true
  14642. */
  14643. this.isInterleavedBuffer = true;
  14644. /**
  14645. * A typed array with a shared buffer storing attribute data.
  14646. *
  14647. * @type {TypedArray}
  14648. */
  14649. this.array = array;
  14650. /**
  14651. * The number of typed-array elements per vertex.
  14652. *
  14653. * @type {number}
  14654. */
  14655. this.stride = stride;
  14656. /**
  14657. * The total number of elements in the array
  14658. *
  14659. * @type {number}
  14660. * @readonly
  14661. */
  14662. this.count = array !== undefined ? array.length / stride : 0;
  14663. /**
  14664. * Defines the intended usage pattern of the data store for optimization purposes.
  14665. *
  14666. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  14667. * instantiate a new one and set the desired usage before the next render.
  14668. *
  14669. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  14670. * @default StaticDrawUsage
  14671. */
  14672. this.usage = StaticDrawUsage;
  14673. /**
  14674. * This can be used to only update some components of stored vectors (for example, just the
  14675. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  14676. *
  14677. * @type {Array<Object>}
  14678. */
  14679. this.updateRanges = [];
  14680. /**
  14681. * A version number, incremented every time the `needsUpdate` is set to `true`.
  14682. *
  14683. * @type {number}
  14684. */
  14685. this.version = 0;
  14686. /**
  14687. * The UUID of the interleaved buffer.
  14688. *
  14689. * @type {string}
  14690. * @readonly
  14691. */
  14692. this.uuid = generateUUID();
  14693. }
  14694. /**
  14695. * A callback function that is executed after the renderer has transferred the attribute array
  14696. * data to the GPU.
  14697. */
  14698. onUploadCallback() {}
  14699. /**
  14700. * Flag to indicate that this attribute has changed and should be re-sent to
  14701. * the GPU. Set this to `true` when you modify the value of the array.
  14702. *
  14703. * @type {number}
  14704. * @default false
  14705. * @param {boolean} value
  14706. */
  14707. set needsUpdate( value ) {
  14708. if ( value === true ) this.version ++;
  14709. }
  14710. /**
  14711. * Sets the usage of this interleaved buffer.
  14712. *
  14713. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  14714. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  14715. */
  14716. setUsage( value ) {
  14717. this.usage = value;
  14718. return this;
  14719. }
  14720. /**
  14721. * Adds a range of data in the data array to be updated on the GPU.
  14722. *
  14723. * @param {number} start - Position at which to start update.
  14724. * @param {number} count - The number of components to update.
  14725. */
  14726. addUpdateRange( start, count ) {
  14727. this.updateRanges.push( { start, count } );
  14728. }
  14729. /**
  14730. * Clears the update ranges.
  14731. */
  14732. clearUpdateRanges() {
  14733. this.updateRanges.length = 0;
  14734. }
  14735. /**
  14736. * Copies the values of the given interleaved buffer to this instance.
  14737. *
  14738. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  14739. * @return {InterleavedBuffer} A reference to this instance.
  14740. */
  14741. copy( source ) {
  14742. this.array = new source.array.constructor( source.array );
  14743. this.count = source.count;
  14744. this.stride = source.stride;
  14745. this.usage = source.usage;
  14746. return this;
  14747. }
  14748. /**
  14749. * Copies a vector from the given interleaved buffer to this one. The start
  14750. * and destination position in the attribute buffers are represented by the
  14751. * given indices.
  14752. *
  14753. * @param {number} index1 - The destination index into this interleaved buffer.
  14754. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  14755. * @param {number} index2 - The source index into the given interleaved buffer.
  14756. * @return {InterleavedBuffer} A reference to this instance.
  14757. */
  14758. copyAt( index1, interleavedBuffer, index2 ) {
  14759. index1 *= this.stride;
  14760. index2 *= interleavedBuffer.stride;
  14761. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  14762. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  14763. }
  14764. return this;
  14765. }
  14766. /**
  14767. * Sets the given array data in the interleaved buffer.
  14768. *
  14769. * @param {(TypedArray|Array)} value - The array data to set.
  14770. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  14771. * @return {InterleavedBuffer} A reference to this instance.
  14772. */
  14773. set( value, offset = 0 ) {
  14774. this.array.set( value, offset );
  14775. return this;
  14776. }
  14777. /**
  14778. * Returns a new interleaved buffer with copied values from this instance.
  14779. *
  14780. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  14781. * @return {InterleavedBuffer} A clone of this instance.
  14782. */
  14783. clone( data ) {
  14784. if ( data.arrayBuffers === undefined ) {
  14785. data.arrayBuffers = {};
  14786. }
  14787. if ( this.array.buffer._uuid === undefined ) {
  14788. this.array.buffer._uuid = generateUUID();
  14789. }
  14790. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14791. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  14792. }
  14793. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  14794. const ib = new this.constructor( array, this.stride );
  14795. ib.setUsage( this.usage );
  14796. return ib;
  14797. }
  14798. /**
  14799. * Sets the given callback function that is executed after the Renderer has transferred
  14800. * the array data to the GPU. Can be used to perform clean-up operations after
  14801. * the upload when data are not needed anymore on the CPU side.
  14802. *
  14803. * @param {Function} callback - The `onUpload()` callback.
  14804. * @return {InterleavedBuffer} A reference to this instance.
  14805. */
  14806. onUpload( callback ) {
  14807. this.onUploadCallback = callback;
  14808. return this;
  14809. }
  14810. /**
  14811. * Serializes the interleaved buffer into JSON.
  14812. *
  14813. * @param {Object} [data] - An optional value holding meta information about the serialization.
  14814. * @return {Object} A JSON object representing the serialized interleaved buffer.
  14815. */
  14816. toJSON( data ) {
  14817. if ( data.arrayBuffers === undefined ) {
  14818. data.arrayBuffers = {};
  14819. }
  14820. // generate UUID for array buffer if necessary
  14821. if ( this.array.buffer._uuid === undefined ) {
  14822. this.array.buffer._uuid = generateUUID();
  14823. }
  14824. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  14825. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  14826. }
  14827. //
  14828. return {
  14829. uuid: this.uuid,
  14830. buffer: this.array.buffer._uuid,
  14831. type: this.array.constructor.name,
  14832. stride: this.stride
  14833. };
  14834. }
  14835. }
  14836. const _vector$8 = /*@__PURE__*/ new Vector3();
  14837. /**
  14838. * An alternative version of a buffer attribute with interleaved data. Interleaved
  14839. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  14840. * different offsets into the buffer.
  14841. */
  14842. class InterleavedBufferAttribute {
  14843. /**
  14844. * Constructs a new interleaved buffer attribute.
  14845. *
  14846. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  14847. * @param {number} itemSize - The item size.
  14848. * @param {number} offset - The attribute offset into the buffer.
  14849. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14850. */
  14851. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  14852. /**
  14853. * This flag can be used for type testing.
  14854. *
  14855. * @type {boolean}
  14856. * @readonly
  14857. * @default true
  14858. */
  14859. this.isInterleavedBufferAttribute = true;
  14860. /**
  14861. * The name of the buffer attribute.
  14862. *
  14863. * @type {string}
  14864. */
  14865. this.name = '';
  14866. /**
  14867. * The buffer holding the interleaved data.
  14868. *
  14869. * @type {InterleavedBuffer}
  14870. */
  14871. this.data = interleavedBuffer;
  14872. /**
  14873. * The item size, see {@link BufferAttribute#itemSize}.
  14874. *
  14875. * @type {number}
  14876. */
  14877. this.itemSize = itemSize;
  14878. /**
  14879. * The attribute offset into the buffer.
  14880. *
  14881. * @type {number}
  14882. */
  14883. this.offset = offset;
  14884. /**
  14885. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  14886. *
  14887. * @type {InterleavedBuffer}
  14888. */
  14889. this.normalized = normalized;
  14890. }
  14891. /**
  14892. * The item count of this buffer attribute.
  14893. *
  14894. * @type {number}
  14895. * @readonly
  14896. */
  14897. get count() {
  14898. return this.data.count;
  14899. }
  14900. /**
  14901. * The array holding the interleaved buffer attribute data.
  14902. *
  14903. * @type {TypedArray}
  14904. */
  14905. get array() {
  14906. return this.data.array;
  14907. }
  14908. /**
  14909. * Flag to indicate that this attribute has changed and should be re-sent to
  14910. * the GPU. Set this to `true` when you modify the value of the array.
  14911. *
  14912. * @type {number}
  14913. * @default false
  14914. * @param {boolean} value
  14915. */
  14916. set needsUpdate( value ) {
  14917. this.data.needsUpdate = value;
  14918. }
  14919. /**
  14920. * Applies the given 4x4 matrix to the given attribute. Only works with
  14921. * item size `3`.
  14922. *
  14923. * @param {Matrix4} m - The matrix to apply.
  14924. * @return {InterleavedBufferAttribute} A reference to this instance.
  14925. */
  14926. applyMatrix4( m ) {
  14927. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  14928. _vector$8.fromBufferAttribute( this, i );
  14929. _vector$8.applyMatrix4( m );
  14930. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14931. }
  14932. return this;
  14933. }
  14934. /**
  14935. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  14936. * item size `3`.
  14937. *
  14938. * @param {Matrix3} m - The normal matrix to apply.
  14939. * @return {InterleavedBufferAttribute} A reference to this instance.
  14940. */
  14941. applyNormalMatrix( m ) {
  14942. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14943. _vector$8.fromBufferAttribute( this, i );
  14944. _vector$8.applyNormalMatrix( m );
  14945. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14946. }
  14947. return this;
  14948. }
  14949. /**
  14950. * Applies the given 4x4 matrix to the given attribute. Only works with
  14951. * item size `3` and with direction vectors.
  14952. *
  14953. * @param {Matrix4} m - The matrix to apply.
  14954. * @return {InterleavedBufferAttribute} A reference to this instance.
  14955. */
  14956. transformDirection( m ) {
  14957. for ( let i = 0, l = this.count; i < l; i ++ ) {
  14958. _vector$8.fromBufferAttribute( this, i );
  14959. _vector$8.transformDirection( m );
  14960. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14961. }
  14962. return this;
  14963. }
  14964. /**
  14965. * Returns the given component of the vector at the given index.
  14966. *
  14967. * @param {number} index - The index into the buffer attribute.
  14968. * @param {number} component - The component index.
  14969. * @return {number} The returned value.
  14970. */
  14971. getComponent( index, component ) {
  14972. let value = this.array[ index * this.data.stride + this.offset + component ];
  14973. if ( this.normalized ) value = denormalize( value, this.array );
  14974. return value;
  14975. }
  14976. /**
  14977. * Sets the given value to the given component of the vector at the given index.
  14978. *
  14979. * @param {number} index - The index into the buffer attribute.
  14980. * @param {number} component - The component index.
  14981. * @param {number} value - The value to set.
  14982. * @return {InterleavedBufferAttribute} A reference to this instance.
  14983. */
  14984. setComponent( index, component, value ) {
  14985. if ( this.normalized ) value = normalize( value, this.array );
  14986. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  14987. return this;
  14988. }
  14989. /**
  14990. * Sets the x component of the vector at the given index.
  14991. *
  14992. * @param {number} index - The index into the buffer attribute.
  14993. * @param {number} x - The value to set.
  14994. * @return {InterleavedBufferAttribute} A reference to this instance.
  14995. */
  14996. setX( index, x ) {
  14997. if ( this.normalized ) x = normalize( x, this.array );
  14998. this.data.array[ index * this.data.stride + this.offset ] = x;
  14999. return this;
  15000. }
  15001. /**
  15002. * Sets the y component of the vector at the given index.
  15003. *
  15004. * @param {number} index - The index into the buffer attribute.
  15005. * @param {number} y - The value to set.
  15006. * @return {InterleavedBufferAttribute} A reference to this instance.
  15007. */
  15008. setY( index, y ) {
  15009. if ( this.normalized ) y = normalize( y, this.array );
  15010. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15011. return this;
  15012. }
  15013. /**
  15014. * Sets the z component of the vector at the given index.
  15015. *
  15016. * @param {number} index - The index into the buffer attribute.
  15017. * @param {number} z - The value to set.
  15018. * @return {InterleavedBufferAttribute} A reference to this instance.
  15019. */
  15020. setZ( index, z ) {
  15021. if ( this.normalized ) z = normalize( z, this.array );
  15022. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15023. return this;
  15024. }
  15025. /**
  15026. * Sets the w component of the vector at the given index.
  15027. *
  15028. * @param {number} index - The index into the buffer attribute.
  15029. * @param {number} w - The value to set.
  15030. * @return {InterleavedBufferAttribute} A reference to this instance.
  15031. */
  15032. setW( index, w ) {
  15033. if ( this.normalized ) w = normalize( w, this.array );
  15034. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15035. return this;
  15036. }
  15037. /**
  15038. * Returns the x component of the vector at the given index.
  15039. *
  15040. * @param {number} index - The index into the buffer attribute.
  15041. * @return {number} The x component.
  15042. */
  15043. getX( index ) {
  15044. let x = this.data.array[ index * this.data.stride + this.offset ];
  15045. if ( this.normalized ) x = denormalize( x, this.array );
  15046. return x;
  15047. }
  15048. /**
  15049. * Returns the y component of the vector at the given index.
  15050. *
  15051. * @param {number} index - The index into the buffer attribute.
  15052. * @return {number} The y component.
  15053. */
  15054. getY( index ) {
  15055. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  15056. if ( this.normalized ) y = denormalize( y, this.array );
  15057. return y;
  15058. }
  15059. /**
  15060. * Returns the z component of the vector at the given index.
  15061. *
  15062. * @param {number} index - The index into the buffer attribute.
  15063. * @return {number} The z component.
  15064. */
  15065. getZ( index ) {
  15066. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  15067. if ( this.normalized ) z = denormalize( z, this.array );
  15068. return z;
  15069. }
  15070. /**
  15071. * Returns the w component of the vector at the given index.
  15072. *
  15073. * @param {number} index - The index into the buffer attribute.
  15074. * @return {number} The w component.
  15075. */
  15076. getW( index ) {
  15077. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  15078. if ( this.normalized ) w = denormalize( w, this.array );
  15079. return w;
  15080. }
  15081. /**
  15082. * Sets the x and y component of the vector at the given index.
  15083. *
  15084. * @param {number} index - The index into the buffer attribute.
  15085. * @param {number} x - The value for the x component to set.
  15086. * @param {number} y - The value for the y component to set.
  15087. * @return {InterleavedBufferAttribute} A reference to this instance.
  15088. */
  15089. setXY( index, x, y ) {
  15090. index = index * this.data.stride + this.offset;
  15091. if ( this.normalized ) {
  15092. x = normalize( x, this.array );
  15093. y = normalize( y, this.array );
  15094. }
  15095. this.data.array[ index + 0 ] = x;
  15096. this.data.array[ index + 1 ] = y;
  15097. return this;
  15098. }
  15099. /**
  15100. * Sets the x, y and z component of the vector at the given index.
  15101. *
  15102. * @param {number} index - The index into the buffer attribute.
  15103. * @param {number} x - The value for the x component to set.
  15104. * @param {number} y - The value for the y component to set.
  15105. * @param {number} z - The value for the z component to set.
  15106. * @return {InterleavedBufferAttribute} A reference to this instance.
  15107. */
  15108. setXYZ( index, x, y, z ) {
  15109. index = index * this.data.stride + this.offset;
  15110. if ( this.normalized ) {
  15111. x = normalize( x, this.array );
  15112. y = normalize( y, this.array );
  15113. z = normalize( z, this.array );
  15114. }
  15115. this.data.array[ index + 0 ] = x;
  15116. this.data.array[ index + 1 ] = y;
  15117. this.data.array[ index + 2 ] = z;
  15118. return this;
  15119. }
  15120. /**
  15121. * Sets the x, y, z and w component of the vector at the given index.
  15122. *
  15123. * @param {number} index - The index into the buffer attribute.
  15124. * @param {number} x - The value for the x component to set.
  15125. * @param {number} y - The value for the y component to set.
  15126. * @param {number} z - The value for the z component to set.
  15127. * @param {number} w - The value for the w component to set.
  15128. * @return {InterleavedBufferAttribute} A reference to this instance.
  15129. */
  15130. setXYZW( index, x, y, z, w ) {
  15131. index = index * this.data.stride + this.offset;
  15132. if ( this.normalized ) {
  15133. x = normalize( x, this.array );
  15134. y = normalize( y, this.array );
  15135. z = normalize( z, this.array );
  15136. w = normalize( w, this.array );
  15137. }
  15138. this.data.array[ index + 0 ] = x;
  15139. this.data.array[ index + 1 ] = y;
  15140. this.data.array[ index + 2 ] = z;
  15141. this.data.array[ index + 3 ] = w;
  15142. return this;
  15143. }
  15144. /**
  15145. * Returns a new buffer attribute with copied values from this instance.
  15146. *
  15147. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15148. *
  15149. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  15150. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  15151. */
  15152. clone( data ) {
  15153. if ( data === undefined ) {
  15154. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  15155. const array = [];
  15156. for ( let i = 0; i < this.count; i ++ ) {
  15157. const index = i * this.data.stride + this.offset;
  15158. for ( let j = 0; j < this.itemSize; j ++ ) {
  15159. array.push( this.data.array[ index + j ] );
  15160. }
  15161. }
  15162. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  15163. } else {
  15164. if ( data.interleavedBuffers === undefined ) {
  15165. data.interleavedBuffers = {};
  15166. }
  15167. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15168. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  15169. }
  15170. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  15171. }
  15172. }
  15173. /**
  15174. * Serializes the buffer attribute into JSON.
  15175. *
  15176. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  15177. *
  15178. * @param {Object} [data] - An optional value holding meta information about the serialization.
  15179. * @return {Object} A JSON object representing the serialized buffer attribute.
  15180. */
  15181. toJSON( data ) {
  15182. if ( data === undefined ) {
  15183. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  15184. const array = [];
  15185. for ( let i = 0; i < this.count; i ++ ) {
  15186. const index = i * this.data.stride + this.offset;
  15187. for ( let j = 0; j < this.itemSize; j ++ ) {
  15188. array.push( this.data.array[ index + j ] );
  15189. }
  15190. }
  15191. // de-interleave data and save it as an ordinary buffer attribute for now
  15192. return {
  15193. itemSize: this.itemSize,
  15194. type: this.array.constructor.name,
  15195. array: array,
  15196. normalized: this.normalized
  15197. };
  15198. } else {
  15199. // save as true interleaved attribute
  15200. if ( data.interleavedBuffers === undefined ) {
  15201. data.interleavedBuffers = {};
  15202. }
  15203. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  15204. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  15205. }
  15206. return {
  15207. isInterleavedBufferAttribute: true,
  15208. itemSize: this.itemSize,
  15209. data: this.data.uuid,
  15210. offset: this.offset,
  15211. normalized: this.normalized
  15212. };
  15213. }
  15214. }
  15215. }
  15216. let _materialId = 0;
  15217. /**
  15218. * Abstract base class for materials.
  15219. *
  15220. * Materials define the appearance of renderable 3D objects.
  15221. *
  15222. * @abstract
  15223. * @augments EventDispatcher
  15224. */
  15225. class Material extends EventDispatcher {
  15226. /**
  15227. * Constructs a new material.
  15228. */
  15229. constructor() {
  15230. super();
  15231. /**
  15232. * This flag can be used for type testing.
  15233. *
  15234. * @type {boolean}
  15235. * @readonly
  15236. * @default true
  15237. */
  15238. this.isMaterial = true;
  15239. /**
  15240. * The ID of the material.
  15241. *
  15242. * @name Material#id
  15243. * @type {number}
  15244. * @readonly
  15245. */
  15246. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  15247. /**
  15248. * The UUID of the material.
  15249. *
  15250. * @type {string}
  15251. * @readonly
  15252. */
  15253. this.uuid = generateUUID();
  15254. /**
  15255. * The name of the material.
  15256. *
  15257. * @type {string}
  15258. */
  15259. this.name = '';
  15260. /**
  15261. * The type property is used for detecting the object type
  15262. * in context of serialization/deserialization.
  15263. *
  15264. * @type {string}
  15265. * @readonly
  15266. */
  15267. this.type = 'Material';
  15268. /**
  15269. * Defines the blending type of the material.
  15270. *
  15271. * It must be set to `CustomBlending` if custom blending properties like
  15272. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  15273. * should have any effect.
  15274. *
  15275. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  15276. * @default NormalBlending
  15277. */
  15278. this.blending = NormalBlending;
  15279. /**
  15280. * Defines which side of faces will be rendered - front, back or both.
  15281. *
  15282. * @type {(FrontSide|BackSide|DoubleSide)}
  15283. * @default FrontSide
  15284. */
  15285. this.side = FrontSide;
  15286. /**
  15287. * If set to `true`, vertex colors should be used.
  15288. *
  15289. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  15290. * four (RGBA) component color buffer attribute is used.
  15291. *
  15292. * @type {boolean}
  15293. * @default false
  15294. */
  15295. this.vertexColors = false;
  15296. /**
  15297. * Defines how transparent the material is.
  15298. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  15299. *
  15300. * If the {@link Material#transparent} is not set to `true`,
  15301. * the material will remain fully opaque and this value will only affect its color.
  15302. *
  15303. * @type {number}
  15304. * @default 1
  15305. */
  15306. this.opacity = 1;
  15307. /**
  15308. * Defines whether this material is transparent. This has an effect on
  15309. * rendering as transparent objects need special treatment and are rendered
  15310. * after non-transparent objects.
  15311. *
  15312. * When set to true, the extent to which the material is transparent is
  15313. * controlled by {@link Material#opacity}.
  15314. *
  15315. * @type {boolean}
  15316. * @default false
  15317. */
  15318. this.transparent = false;
  15319. /**
  15320. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  15321. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  15322. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  15323. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  15324. *
  15325. * @type {boolean}
  15326. * @default false
  15327. */
  15328. this.alphaHash = false;
  15329. /**
  15330. * Defines the blending source factor.
  15331. *
  15332. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15333. * @default SrcAlphaFactor
  15334. */
  15335. this.blendSrc = SrcAlphaFactor;
  15336. /**
  15337. * Defines the blending destination factor.
  15338. *
  15339. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15340. * @default OneMinusSrcAlphaFactor
  15341. */
  15342. this.blendDst = OneMinusSrcAlphaFactor;
  15343. /**
  15344. * Defines the blending equation.
  15345. *
  15346. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15347. * @default AddEquation
  15348. */
  15349. this.blendEquation = AddEquation;
  15350. /**
  15351. * Defines the blending source alpha factor.
  15352. *
  15353. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15354. * @default null
  15355. */
  15356. this.blendSrcAlpha = null;
  15357. /**
  15358. * Defines the blending destination alpha factor.
  15359. *
  15360. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  15361. * @default null
  15362. */
  15363. this.blendDstAlpha = null;
  15364. /**
  15365. * Defines the blending equation of the alpha channel.
  15366. *
  15367. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  15368. * @default null
  15369. */
  15370. this.blendEquationAlpha = null;
  15371. /**
  15372. * Represents the RGB values of the constant blend color.
  15373. *
  15374. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  15375. *
  15376. * @type {Color}
  15377. * @default (0,0,0)
  15378. */
  15379. this.blendColor = new Color( 0, 0, 0 );
  15380. /**
  15381. * Represents the alpha value of the constant blend color.
  15382. *
  15383. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  15384. *
  15385. * @type {number}
  15386. * @default 0
  15387. */
  15388. this.blendAlpha = 0;
  15389. /**
  15390. * Defines the depth function.
  15391. *
  15392. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  15393. * @default LessEqualDepth
  15394. */
  15395. this.depthFunc = LessEqualDepth;
  15396. /**
  15397. * Whether to have depth test enabled when rendering this material.
  15398. * When the depth test is disabled, the depth write will also be implicitly disabled.
  15399. *
  15400. * @type {boolean}
  15401. * @default true
  15402. */
  15403. this.depthTest = true;
  15404. /**
  15405. * Whether rendering this material has any effect on the depth buffer.
  15406. *
  15407. * When drawing 2D overlays it can be useful to disable the depth writing in
  15408. * order to layer several things together without creating z-index artifacts.
  15409. *
  15410. * @type {boolean}
  15411. * @default true
  15412. */
  15413. this.depthWrite = true;
  15414. /**
  15415. * The bit mask to use when writing to the stencil buffer.
  15416. *
  15417. * @type {number}
  15418. * @default 0xff
  15419. */
  15420. this.stencilWriteMask = 0xff;
  15421. /**
  15422. * The stencil comparison function to use.
  15423. *
  15424. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  15425. * @default AlwaysStencilFunc
  15426. */
  15427. this.stencilFunc = AlwaysStencilFunc;
  15428. /**
  15429. * The value to use when performing stencil comparisons or stencil operations.
  15430. *
  15431. * @type {number}
  15432. * @default 0
  15433. */
  15434. this.stencilRef = 0;
  15435. /**
  15436. * The bit mask to use when comparing against the stencil buffer.
  15437. *
  15438. * @type {number}
  15439. * @default 0xff
  15440. */
  15441. this.stencilFuncMask = 0xff;
  15442. /**
  15443. * Which stencil operation to perform when the comparison function returns `false`.
  15444. *
  15445. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15446. * @default KeepStencilOp
  15447. */
  15448. this.stencilFail = KeepStencilOp;
  15449. /**
  15450. * Which stencil operation to perform when the comparison function returns
  15451. * `true` but the depth test fails.
  15452. *
  15453. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15454. * @default KeepStencilOp
  15455. */
  15456. this.stencilZFail = KeepStencilOp;
  15457. /**
  15458. * Which stencil operation to perform when the comparison function returns
  15459. * `true` and the depth test passes.
  15460. *
  15461. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  15462. * @default KeepStencilOp
  15463. */
  15464. this.stencilZPass = KeepStencilOp;
  15465. /**
  15466. * Whether stencil operations are performed against the stencil buffer. In
  15467. * order to perform writes or comparisons against the stencil buffer this
  15468. * value must be `true`.
  15469. *
  15470. * @type {boolean}
  15471. * @default false
  15472. */
  15473. this.stencilWrite = false;
  15474. /**
  15475. * User-defined clipping planes specified as THREE.Plane objects in world
  15476. * space. These planes apply to the objects this material is attached to.
  15477. * Points in space whose signed distance to the plane is negative are clipped
  15478. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  15479. * be `true`.
  15480. *
  15481. * @type {?Array<Plane>}
  15482. * @default null
  15483. */
  15484. this.clippingPlanes = null;
  15485. /**
  15486. * Changes the behavior of clipping planes so that only their intersection is
  15487. * clipped, rather than their union.
  15488. *
  15489. * @type {boolean}
  15490. * @default false
  15491. */
  15492. this.clipIntersection = false;
  15493. /**
  15494. * Defines whether to clip shadows according to the clipping planes specified
  15495. * on this material.
  15496. *
  15497. * @type {boolean}
  15498. * @default false
  15499. */
  15500. this.clipShadows = false;
  15501. /**
  15502. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  15503. * is determined as follows:
  15504. *
  15505. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  15506. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  15507. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  15508. *
  15509. * @type {?(FrontSide|BackSide|DoubleSide)}
  15510. * @default null
  15511. */
  15512. this.shadowSide = null;
  15513. /**
  15514. * Whether to render the material's color.
  15515. *
  15516. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  15517. * objects that occlude other objects.
  15518. *
  15519. * @type {boolean}
  15520. * @default true
  15521. */
  15522. this.colorWrite = true;
  15523. /**
  15524. * Override the renderer's default precision for this material.
  15525. *
  15526. * @type {?('highp'|'mediump'|'lowp')}
  15527. * @default null
  15528. */
  15529. this.precision = null;
  15530. /**
  15531. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  15532. * be offset after it is interpolated from the depth values of the appropriate vertices.
  15533. * The offset is added before the depth test is performed and before the value is written
  15534. * into the depth buffer.
  15535. *
  15536. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  15537. * rendering solids with highlighted edges.
  15538. *
  15539. * @type {boolean}
  15540. * @default false
  15541. */
  15542. this.polygonOffset = false;
  15543. /**
  15544. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  15545. *
  15546. * @type {number}
  15547. * @default 0
  15548. */
  15549. this.polygonOffsetFactor = 0;
  15550. /**
  15551. * Is multiplied by an implementation-specific value to create a constant depth offset.
  15552. *
  15553. * @type {number}
  15554. * @default 0
  15555. */
  15556. this.polygonOffsetUnits = 0;
  15557. /**
  15558. * Whether to apply dithering to the color to remove the appearance of banding.
  15559. *
  15560. * @type {boolean}
  15561. * @default false
  15562. */
  15563. this.dithering = false;
  15564. /**
  15565. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  15566. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  15567. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  15568. *
  15569. * @type {boolean}
  15570. * @default false
  15571. */
  15572. this.alphaToCoverage = false;
  15573. /**
  15574. * Whether to premultiply the alpha (transparency) value.
  15575. *
  15576. * @type {boolean}
  15577. * @default false
  15578. */
  15579. this.premultipliedAlpha = false;
  15580. /**
  15581. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  15582. *
  15583. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  15584. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  15585. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  15586. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  15587. * disable the two pass rendering to avoid performance issues.
  15588. *
  15589. * @type {boolean}
  15590. * @default false
  15591. */
  15592. this.forceSinglePass = false;
  15593. /**
  15594. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  15595. *
  15596. * @type {boolean}
  15597. * @default true
  15598. */
  15599. this.allowOverride = true;
  15600. /**
  15601. * Defines whether 3D objects using this material are visible.
  15602. *
  15603. * @type {boolean}
  15604. * @default true
  15605. */
  15606. this.visible = true;
  15607. /**
  15608. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  15609. *
  15610. * It is ignored when rendering to a render target or using post processing or when using
  15611. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  15612. *
  15613. * @type {boolean}
  15614. * @default true
  15615. */
  15616. this.toneMapped = true;
  15617. /**
  15618. * An object that can be used to store custom data about the Material. It
  15619. * should not hold references to functions as these will not be cloned.
  15620. *
  15621. * @type {Object}
  15622. */
  15623. this.userData = {};
  15624. /**
  15625. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  15626. *
  15627. * @type {number}
  15628. * @readonly
  15629. * @default 0
  15630. */
  15631. this.version = 0;
  15632. this._alphaTest = 0;
  15633. }
  15634. /**
  15635. * Sets the alpha value to be used when running an alpha test. The material
  15636. * will not be rendered if the opacity is lower than this value.
  15637. *
  15638. * @type {number}
  15639. * @readonly
  15640. * @default 0
  15641. */
  15642. get alphaTest() {
  15643. return this._alphaTest;
  15644. }
  15645. set alphaTest( value ) {
  15646. if ( this._alphaTest > 0 !== value > 0 ) {
  15647. this.version ++;
  15648. }
  15649. this._alphaTest = value;
  15650. }
  15651. /**
  15652. * An optional callback that is executed immediately before the material is used to render a 3D object.
  15653. *
  15654. * This method can only be used when rendering with {@link WebGLRenderer}.
  15655. *
  15656. * @param {WebGLRenderer} renderer - The renderer.
  15657. * @param {Scene} scene - The scene.
  15658. * @param {Camera} camera - The camera that is used to render the scene.
  15659. * @param {BufferGeometry} geometry - The 3D object's geometry.
  15660. * @param {Object3D} object - The 3D object.
  15661. * @param {Object} group - The geometry group data.
  15662. */
  15663. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  15664. /**
  15665. * An optional callback that is executed immediately before the shader
  15666. * program is compiled. This function is called with the shader source code
  15667. * as a parameter. Useful for the modification of built-in materials.
  15668. *
  15669. * This method can only be used when rendering with {@link WebGLRenderer}. The
  15670. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  15671. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  15672. *
  15673. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  15674. * @param {WebGLRenderer} renderer - A reference to the renderer.
  15675. */
  15676. onBeforeCompile( /* shaderobject, renderer */ ) {}
  15677. /**
  15678. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  15679. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  15680. * shader or recompile the shader for this material as needed.
  15681. *
  15682. * This method can only be used when rendering with {@link WebGLRenderer}.
  15683. *
  15684. * @return {string} The custom program cache key.
  15685. */
  15686. customProgramCacheKey() {
  15687. return this.onBeforeCompile.toString();
  15688. }
  15689. /**
  15690. * This method can be used to set default values from parameter objects.
  15691. * It is a generic implementation so it can be used with different types
  15692. * of materials.
  15693. *
  15694. * @param {Object} [values] - The material values to set.
  15695. */
  15696. setValues( values ) {
  15697. if ( values === undefined ) return;
  15698. for ( const key in values ) {
  15699. const newValue = values[ key ];
  15700. if ( newValue === undefined ) {
  15701. warn( `Material: parameter '${ key }' has value of undefined.` );
  15702. continue;
  15703. }
  15704. const currentValue = this[ key ];
  15705. if ( currentValue === undefined ) {
  15706. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  15707. continue;
  15708. }
  15709. if ( currentValue && currentValue.isColor ) {
  15710. currentValue.set( newValue );
  15711. } else if (
  15712. ( ( currentValue && currentValue.isVector2 ) && ( newValue && newValue.isVector2 ) ) ||
  15713. ( ( currentValue && currentValue.isEuler ) && ( newValue && newValue.isEuler ) ) ||
  15714. ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) )
  15715. ) {
  15716. currentValue.copy( newValue );
  15717. } else {
  15718. this[ key ] = newValue;
  15719. }
  15720. }
  15721. }
  15722. /**
  15723. * Serializes the material into JSON.
  15724. *
  15725. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  15726. * @return {Object} A JSON object representing the serialized material.
  15727. * @see {@link ObjectLoader#parse}
  15728. */
  15729. toJSON( meta ) {
  15730. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  15731. if ( isRootObject ) {
  15732. meta = {
  15733. textures: {},
  15734. images: {}
  15735. };
  15736. }
  15737. const data = {
  15738. metadata: {
  15739. version: 4.7,
  15740. type: 'Material',
  15741. generator: 'Material.toJSON'
  15742. }
  15743. };
  15744. // standard Material serialization
  15745. data.uuid = this.uuid;
  15746. data.type = this.type;
  15747. if ( this.name !== '' ) data.name = this.name;
  15748. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  15749. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  15750. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  15751. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  15752. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  15753. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  15754. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  15755. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  15756. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  15757. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  15758. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  15759. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  15760. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  15761. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  15762. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  15763. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  15764. }
  15765. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  15766. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  15767. }
  15768. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  15769. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  15770. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  15771. }
  15772. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  15773. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  15774. }
  15775. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  15776. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  15777. }
  15778. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  15779. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  15780. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  15781. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  15782. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  15783. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  15784. }
  15785. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  15786. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  15787. }
  15788. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  15789. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  15790. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  15791. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  15792. }
  15793. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  15794. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  15795. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  15796. if ( this.lightMap && this.lightMap.isTexture ) {
  15797. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  15798. data.lightMapIntensity = this.lightMapIntensity;
  15799. }
  15800. if ( this.aoMap && this.aoMap.isTexture ) {
  15801. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  15802. data.aoMapIntensity = this.aoMapIntensity;
  15803. }
  15804. if ( this.bumpMap && this.bumpMap.isTexture ) {
  15805. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  15806. data.bumpScale = this.bumpScale;
  15807. }
  15808. if ( this.normalMap && this.normalMap.isTexture ) {
  15809. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  15810. data.normalMapType = this.normalMapType;
  15811. data.normalScale = this.normalScale.toArray();
  15812. }
  15813. if ( this.displacementMap && this.displacementMap.isTexture ) {
  15814. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  15815. data.displacementScale = this.displacementScale;
  15816. data.displacementBias = this.displacementBias;
  15817. }
  15818. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  15819. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  15820. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  15821. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  15822. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  15823. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  15824. if ( this.envMap && this.envMap.isTexture ) {
  15825. data.envMap = this.envMap.toJSON( meta ).uuid;
  15826. if ( this.combine !== undefined ) data.combine = this.combine;
  15827. }
  15828. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  15829. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  15830. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  15831. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  15832. if ( this.gradientMap && this.gradientMap.isTexture ) {
  15833. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  15834. }
  15835. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  15836. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  15837. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  15838. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  15839. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  15840. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  15841. if ( this.size !== undefined ) data.size = this.size;
  15842. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  15843. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  15844. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  15845. if ( this.side !== FrontSide ) data.side = this.side;
  15846. if ( this.vertexColors === true ) data.vertexColors = true;
  15847. if ( this.opacity < 1 ) data.opacity = this.opacity;
  15848. if ( this.transparent === true ) data.transparent = true;
  15849. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  15850. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  15851. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  15852. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  15853. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  15854. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  15855. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  15856. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  15857. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  15858. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  15859. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  15860. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  15861. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  15862. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  15863. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  15864. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  15865. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  15866. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  15867. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  15868. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  15869. // rotation (SpriteMaterial)
  15870. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  15871. if ( this.polygonOffset === true ) data.polygonOffset = true;
  15872. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  15873. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  15874. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  15875. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  15876. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  15877. if ( this.scale !== undefined ) data.scale = this.scale;
  15878. if ( this.dithering === true ) data.dithering = true;
  15879. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  15880. if ( this.alphaHash === true ) data.alphaHash = true;
  15881. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  15882. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  15883. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  15884. if ( this.allowOverride === false ) data.allowOverride = false;
  15885. if ( this.wireframe === true ) data.wireframe = true;
  15886. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  15887. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  15888. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  15889. if ( this.flatShading === true ) data.flatShading = true;
  15890. if ( this.visible === false ) data.visible = false;
  15891. if ( this.toneMapped === false ) data.toneMapped = false;
  15892. if ( this.fog === false ) data.fog = false;
  15893. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15894. // TODO: Copied from Object3D.toJSON
  15895. function extractFromCache( cache ) {
  15896. const values = [];
  15897. for ( const key in cache ) {
  15898. const data = cache[ key ];
  15899. delete data.metadata;
  15900. values.push( data );
  15901. }
  15902. return values;
  15903. }
  15904. if ( isRootObject ) {
  15905. const textures = extractFromCache( meta.textures );
  15906. const images = extractFromCache( meta.images );
  15907. if ( textures.length > 0 ) data.textures = textures;
  15908. if ( images.length > 0 ) data.images = images;
  15909. }
  15910. return data;
  15911. }
  15912. /**
  15913. * Deserializes the material from the given JSON.
  15914. *
  15915. * @param {Object} json - The JSON holding the serialized material.
  15916. * @param {Object<string,Texture>} textures - A dictionary holding textures referenced by the material.
  15917. * @return {Material} A reference to this material.
  15918. */
  15919. fromJSON( json, textures ) {
  15920. if ( json.uuid !== undefined ) this.uuid = json.uuid;
  15921. if ( json.name !== undefined ) this.name = json.name;
  15922. if ( json.color !== undefined && this.color !== undefined ) this.color.setHex( json.color );
  15923. if ( json.roughness !== undefined ) this.roughness = json.roughness;
  15924. if ( json.metalness !== undefined ) this.metalness = json.metalness;
  15925. if ( json.sheen !== undefined ) this.sheen = json.sheen;
  15926. if ( json.sheenColor !== undefined ) this.sheenColor = new Color().setHex( json.sheenColor );
  15927. if ( json.sheenRoughness !== undefined ) this.sheenRoughness = json.sheenRoughness;
  15928. if ( json.emissive !== undefined && this.emissive !== undefined ) this.emissive.setHex( json.emissive );
  15929. if ( json.specular !== undefined && this.specular !== undefined ) this.specular.setHex( json.specular );
  15930. if ( json.specularIntensity !== undefined ) this.specularIntensity = json.specularIntensity;
  15931. if ( json.specularColor !== undefined && this.specularColor !== undefined ) this.specularColor.setHex( json.specularColor );
  15932. if ( json.shininess !== undefined ) this.shininess = json.shininess;
  15933. if ( json.clearcoat !== undefined ) this.clearcoat = json.clearcoat;
  15934. if ( json.clearcoatRoughness !== undefined ) this.clearcoatRoughness = json.clearcoatRoughness;
  15935. if ( json.dispersion !== undefined ) this.dispersion = json.dispersion;
  15936. if ( json.iridescence !== undefined ) this.iridescence = json.iridescence;
  15937. if ( json.iridescenceIOR !== undefined ) this.iridescenceIOR = json.iridescenceIOR;
  15938. if ( json.iridescenceThicknessRange !== undefined ) this.iridescenceThicknessRange = json.iridescenceThicknessRange;
  15939. if ( json.transmission !== undefined ) this.transmission = json.transmission;
  15940. if ( json.thickness !== undefined ) this.thickness = json.thickness;
  15941. if ( json.attenuationDistance !== undefined ) this.attenuationDistance = json.attenuationDistance;
  15942. if ( json.attenuationColor !== undefined && this.attenuationColor !== undefined ) this.attenuationColor.setHex( json.attenuationColor );
  15943. if ( json.anisotropy !== undefined ) this.anisotropy = json.anisotropy;
  15944. if ( json.anisotropyRotation !== undefined ) this.anisotropyRotation = json.anisotropyRotation;
  15945. if ( json.fog !== undefined ) this.fog = json.fog;
  15946. if ( json.flatShading !== undefined ) this.flatShading = json.flatShading;
  15947. if ( json.blending !== undefined ) this.blending = json.blending;
  15948. if ( json.combine !== undefined ) this.combine = json.combine;
  15949. if ( json.side !== undefined ) this.side = json.side;
  15950. if ( json.shadowSide !== undefined ) this.shadowSide = json.shadowSide;
  15951. if ( json.opacity !== undefined ) this.opacity = json.opacity;
  15952. if ( json.transparent !== undefined ) this.transparent = json.transparent;
  15953. if ( json.alphaTest !== undefined ) this.alphaTest = json.alphaTest;
  15954. if ( json.alphaHash !== undefined ) this.alphaHash = json.alphaHash;
  15955. if ( json.depthFunc !== undefined ) this.depthFunc = json.depthFunc;
  15956. if ( json.depthTest !== undefined ) this.depthTest = json.depthTest;
  15957. if ( json.depthWrite !== undefined ) this.depthWrite = json.depthWrite;
  15958. if ( json.colorWrite !== undefined ) this.colorWrite = json.colorWrite;
  15959. if ( json.blendSrc !== undefined ) this.blendSrc = json.blendSrc;
  15960. if ( json.blendDst !== undefined ) this.blendDst = json.blendDst;
  15961. if ( json.blendEquation !== undefined ) this.blendEquation = json.blendEquation;
  15962. if ( json.blendSrcAlpha !== undefined ) this.blendSrcAlpha = json.blendSrcAlpha;
  15963. if ( json.blendDstAlpha !== undefined ) this.blendDstAlpha = json.blendDstAlpha;
  15964. if ( json.blendEquationAlpha !== undefined ) this.blendEquationAlpha = json.blendEquationAlpha;
  15965. if ( json.blendColor !== undefined && this.blendColor !== undefined ) this.blendColor.setHex( json.blendColor );
  15966. if ( json.blendAlpha !== undefined ) this.blendAlpha = json.blendAlpha;
  15967. if ( json.stencilWriteMask !== undefined ) this.stencilWriteMask = json.stencilWriteMask;
  15968. if ( json.stencilFunc !== undefined ) this.stencilFunc = json.stencilFunc;
  15969. if ( json.stencilRef !== undefined ) this.stencilRef = json.stencilRef;
  15970. if ( json.stencilFuncMask !== undefined ) this.stencilFuncMask = json.stencilFuncMask;
  15971. if ( json.stencilFail !== undefined ) this.stencilFail = json.stencilFail;
  15972. if ( json.stencilZFail !== undefined ) this.stencilZFail = json.stencilZFail;
  15973. if ( json.stencilZPass !== undefined ) this.stencilZPass = json.stencilZPass;
  15974. if ( json.stencilWrite !== undefined ) this.stencilWrite = json.stencilWrite;
  15975. if ( json.wireframe !== undefined ) this.wireframe = json.wireframe;
  15976. if ( json.wireframeLinewidth !== undefined ) this.wireframeLinewidth = json.wireframeLinewidth;
  15977. if ( json.wireframeLinecap !== undefined ) this.wireframeLinecap = json.wireframeLinecap;
  15978. if ( json.wireframeLinejoin !== undefined ) this.wireframeLinejoin = json.wireframeLinejoin;
  15979. if ( json.rotation !== undefined ) this.rotation = json.rotation;
  15980. if ( json.linewidth !== undefined ) this.linewidth = json.linewidth;
  15981. if ( json.dashSize !== undefined ) this.dashSize = json.dashSize;
  15982. if ( json.gapSize !== undefined ) this.gapSize = json.gapSize;
  15983. if ( json.scale !== undefined ) this.scale = json.scale;
  15984. if ( json.polygonOffset !== undefined ) this.polygonOffset = json.polygonOffset;
  15985. if ( json.polygonOffsetFactor !== undefined ) this.polygonOffsetFactor = json.polygonOffsetFactor;
  15986. if ( json.polygonOffsetUnits !== undefined ) this.polygonOffsetUnits = json.polygonOffsetUnits;
  15987. if ( json.dithering !== undefined ) this.dithering = json.dithering;
  15988. if ( json.alphaToCoverage !== undefined ) this.alphaToCoverage = json.alphaToCoverage;
  15989. if ( json.premultipliedAlpha !== undefined ) this.premultipliedAlpha = json.premultipliedAlpha;
  15990. if ( json.forceSinglePass !== undefined ) this.forceSinglePass = json.forceSinglePass;
  15991. if ( json.allowOverride !== undefined ) this.allowOverride = json.allowOverride;
  15992. if ( json.visible !== undefined ) this.visible = json.visible;
  15993. if ( json.toneMapped !== undefined ) this.toneMapped = json.toneMapped;
  15994. if ( json.userData !== undefined ) this.userData = json.userData;
  15995. if ( json.vertexColors !== undefined ) {
  15996. if ( typeof json.vertexColors === 'number' ) {
  15997. this.vertexColors = json.vertexColors > 0;
  15998. } else {
  15999. this.vertexColors = json.vertexColors;
  16000. }
  16001. }
  16002. // for PointsMaterial
  16003. if ( json.size !== undefined ) this.size = json.size;
  16004. if ( json.sizeAttenuation !== undefined ) this.sizeAttenuation = json.sizeAttenuation;
  16005. // maps
  16006. if ( json.map !== undefined ) this.map = textures[ json.map ] || null;
  16007. if ( json.matcap !== undefined ) this.matcap = textures[ json.matcap ] || null;
  16008. if ( json.alphaMap !== undefined ) this.alphaMap = textures[ json.alphaMap ] || null;
  16009. if ( json.bumpMap !== undefined ) this.bumpMap = textures[ json.bumpMap ] || null;
  16010. if ( json.bumpScale !== undefined ) this.bumpScale = json.bumpScale;
  16011. if ( json.normalMap !== undefined ) this.normalMap = textures[ json.normalMap ] || null;
  16012. if ( json.normalMapType !== undefined ) this.normalMapType = json.normalMapType;
  16013. if ( json.normalScale !== undefined ) {
  16014. let normalScale = json.normalScale;
  16015. if ( Array.isArray( normalScale ) === false ) {
  16016. // Blender exporter used to export a scalar. See #7459
  16017. normalScale = [ normalScale, normalScale ];
  16018. }
  16019. this.normalScale = new Vector2().fromArray( normalScale );
  16020. }
  16021. if ( json.displacementMap !== undefined ) this.displacementMap = textures[ json.displacementMap ] || null;
  16022. if ( json.displacementScale !== undefined ) this.displacementScale = json.displacementScale;
  16023. if ( json.displacementBias !== undefined ) this.displacementBias = json.displacementBias;
  16024. if ( json.roughnessMap !== undefined ) this.roughnessMap = textures[ json.roughnessMap ] || null;
  16025. if ( json.metalnessMap !== undefined ) this.metalnessMap = textures[ json.metalnessMap ] || null;
  16026. if ( json.emissiveMap !== undefined ) this.emissiveMap = textures[ json.emissiveMap ] || null;
  16027. if ( json.emissiveIntensity !== undefined ) this.emissiveIntensity = json.emissiveIntensity;
  16028. if ( json.specularMap !== undefined ) this.specularMap = textures[ json.specularMap ] || null;
  16029. if ( json.specularIntensityMap !== undefined ) this.specularIntensityMap = textures[ json.specularIntensityMap ] || null;
  16030. if ( json.specularColorMap !== undefined ) this.specularColorMap = textures[ json.specularColorMap ] || null;
  16031. if ( json.envMap !== undefined ) this.envMap = textures[ json.envMap ] || null;
  16032. if ( json.envMapRotation !== undefined ) this.envMapRotation.fromArray( json.envMapRotation );
  16033. if ( json.envMapIntensity !== undefined ) this.envMapIntensity = json.envMapIntensity;
  16034. if ( json.reflectivity !== undefined ) this.reflectivity = json.reflectivity;
  16035. if ( json.refractionRatio !== undefined ) this.refractionRatio = json.refractionRatio;
  16036. if ( json.lightMap !== undefined ) this.lightMap = textures[ json.lightMap ] || null;
  16037. if ( json.lightMapIntensity !== undefined ) this.lightMapIntensity = json.lightMapIntensity;
  16038. if ( json.aoMap !== undefined ) this.aoMap = textures[ json.aoMap ] || null;
  16039. if ( json.aoMapIntensity !== undefined ) this.aoMapIntensity = json.aoMapIntensity;
  16040. if ( json.gradientMap !== undefined ) this.gradientMap = textures[ json.gradientMap ] || null;
  16041. if ( json.clearcoatMap !== undefined ) this.clearcoatMap = textures[ json.clearcoatMap ] || null;
  16042. if ( json.clearcoatRoughnessMap !== undefined ) this.clearcoatRoughnessMap = textures[ json.clearcoatRoughnessMap ] || null;
  16043. if ( json.clearcoatNormalMap !== undefined ) this.clearcoatNormalMap = textures[ json.clearcoatNormalMap ] || null;
  16044. if ( json.clearcoatNormalScale !== undefined ) this.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  16045. if ( json.iridescenceMap !== undefined ) this.iridescenceMap = textures[ json.iridescenceMap ] || null;
  16046. if ( json.iridescenceThicknessMap !== undefined ) this.iridescenceThicknessMap = textures[ json.iridescenceThicknessMap ] || null;
  16047. if ( json.transmissionMap !== undefined ) this.transmissionMap = textures[ json.transmissionMap ] || null;
  16048. if ( json.thicknessMap !== undefined ) this.thicknessMap = textures[ json.thicknessMap ] || null;
  16049. if ( json.anisotropyMap !== undefined ) this.anisotropyMap = textures[ json.anisotropyMap ] || null;
  16050. if ( json.sheenColorMap !== undefined ) this.sheenColorMap = textures[ json.sheenColorMap ] || null;
  16051. if ( json.sheenRoughnessMap !== undefined ) this.sheenRoughnessMap = textures[ json.sheenRoughnessMap ] || null;
  16052. return this;
  16053. }
  16054. /**
  16055. * Returns a new material with copied values from this instance.
  16056. *
  16057. * @return {Material} A clone of this instance.
  16058. */
  16059. clone() {
  16060. return new this.constructor().copy( this );
  16061. }
  16062. /**
  16063. * Copies the values of the given material to this instance.
  16064. *
  16065. * @param {Material} source - The material to copy.
  16066. * @return {Material} A reference to this instance.
  16067. */
  16068. copy( source ) {
  16069. this.name = source.name;
  16070. this.blending = source.blending;
  16071. this.side = source.side;
  16072. this.vertexColors = source.vertexColors;
  16073. this.opacity = source.opacity;
  16074. this.transparent = source.transparent;
  16075. this.blendSrc = source.blendSrc;
  16076. this.blendDst = source.blendDst;
  16077. this.blendEquation = source.blendEquation;
  16078. this.blendSrcAlpha = source.blendSrcAlpha;
  16079. this.blendDstAlpha = source.blendDstAlpha;
  16080. this.blendEquationAlpha = source.blendEquationAlpha;
  16081. this.blendColor.copy( source.blendColor );
  16082. this.blendAlpha = source.blendAlpha;
  16083. this.depthFunc = source.depthFunc;
  16084. this.depthTest = source.depthTest;
  16085. this.depthWrite = source.depthWrite;
  16086. this.stencilWriteMask = source.stencilWriteMask;
  16087. this.stencilFunc = source.stencilFunc;
  16088. this.stencilRef = source.stencilRef;
  16089. this.stencilFuncMask = source.stencilFuncMask;
  16090. this.stencilFail = source.stencilFail;
  16091. this.stencilZFail = source.stencilZFail;
  16092. this.stencilZPass = source.stencilZPass;
  16093. this.stencilWrite = source.stencilWrite;
  16094. const srcPlanes = source.clippingPlanes;
  16095. let dstPlanes = null;
  16096. if ( srcPlanes !== null ) {
  16097. const n = srcPlanes.length;
  16098. dstPlanes = new Array( n );
  16099. for ( let i = 0; i !== n; ++ i ) {
  16100. dstPlanes[ i ] = srcPlanes[ i ].clone();
  16101. }
  16102. }
  16103. this.clippingPlanes = dstPlanes;
  16104. this.clipIntersection = source.clipIntersection;
  16105. this.clipShadows = source.clipShadows;
  16106. this.shadowSide = source.shadowSide;
  16107. this.colorWrite = source.colorWrite;
  16108. this.precision = source.precision;
  16109. this.polygonOffset = source.polygonOffset;
  16110. this.polygonOffsetFactor = source.polygonOffsetFactor;
  16111. this.polygonOffsetUnits = source.polygonOffsetUnits;
  16112. this.dithering = source.dithering;
  16113. this.alphaTest = source.alphaTest;
  16114. this.alphaHash = source.alphaHash;
  16115. this.alphaToCoverage = source.alphaToCoverage;
  16116. this.premultipliedAlpha = source.premultipliedAlpha;
  16117. this.forceSinglePass = source.forceSinglePass;
  16118. this.allowOverride = source.allowOverride;
  16119. this.visible = source.visible;
  16120. this.toneMapped = source.toneMapped;
  16121. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  16122. return this;
  16123. }
  16124. /**
  16125. * Frees the GPU-related resources allocated by this instance. Call this
  16126. * method whenever this instance is no longer used in your app.
  16127. *
  16128. * @fires Material#dispose
  16129. */
  16130. dispose() {
  16131. /**
  16132. * Fires when the material has been disposed of.
  16133. *
  16134. * @event Material#dispose
  16135. * @type {Object}
  16136. */
  16137. this.dispatchEvent( { type: 'dispose' } );
  16138. }
  16139. /**
  16140. * Setting this property to `true` indicates the engine the material
  16141. * needs to be recompiled.
  16142. *
  16143. * @type {boolean}
  16144. * @default false
  16145. * @param {boolean} value
  16146. */
  16147. set needsUpdate( value ) {
  16148. if ( value === true ) this.version ++;
  16149. }
  16150. }
  16151. /**
  16152. * A material for rendering instances of {@link Sprite}.
  16153. *
  16154. * ```js
  16155. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  16156. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  16157. *
  16158. * const sprite = new THREE.Sprite( material );
  16159. * sprite.scale.set(200, 200, 1)
  16160. * scene.add( sprite );
  16161. * ```
  16162. *
  16163. * @augments Material
  16164. */
  16165. class SpriteMaterial extends Material {
  16166. /**
  16167. * Constructs a new sprite material.
  16168. *
  16169. * @param {Object} [parameters] - An object with one or more properties
  16170. * defining the material's appearance. Any property of the material
  16171. * (including any property from inherited materials) can be passed
  16172. * in here. Color values can be passed any type of value accepted
  16173. * by {@link Color#set}.
  16174. */
  16175. constructor( parameters ) {
  16176. super();
  16177. /**
  16178. * This flag can be used for type testing.
  16179. *
  16180. * @type {boolean}
  16181. * @readonly
  16182. * @default true
  16183. */
  16184. this.isSpriteMaterial = true;
  16185. this.type = 'SpriteMaterial';
  16186. /**
  16187. * Color of the material.
  16188. *
  16189. * @type {Color}
  16190. * @default (1,1,1)
  16191. */
  16192. this.color = new Color( 0xffffff );
  16193. /**
  16194. * The color map. May optionally include an alpha channel, typically combined
  16195. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  16196. * color is modulated by the diffuse `color`.
  16197. *
  16198. * `map` represents color data, and the texture must be assigned a
  16199. * {@link Texture#colorSpace}. Most `map` textures set
  16200. * `texture.colorSpace = SRGBColorSpace`.
  16201. *
  16202. * @type {?Texture}
  16203. * @default null
  16204. */
  16205. this.map = null;
  16206. /**
  16207. * The alpha map is a grayscale texture that controls the opacity across the
  16208. * surface (black: fully transparent; white: fully opaque).
  16209. *
  16210. * Only the color of the texture is used, ignoring the alpha channel if one
  16211. * exists. For RGB and RGBA textures, the renderer will use the green channel
  16212. * when sampling this texture due to the extra bit of precision provided for
  16213. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  16214. * luminance/alpha textures will also still work as expected.
  16215. *
  16216. * `alphaMap` represents non-color data. Any texture assigned must have
  16217. * `texture.colorSpace = NoColorSpace` (default).
  16218. *
  16219. * @type {?Texture}
  16220. * @default null
  16221. */
  16222. this.alphaMap = null;
  16223. /**
  16224. * The rotation of the sprite in radians.
  16225. *
  16226. * @type {number}
  16227. * @default 0
  16228. */
  16229. this.rotation = 0;
  16230. /**
  16231. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  16232. *
  16233. * @type {boolean}
  16234. * @default true
  16235. */
  16236. this.sizeAttenuation = true;
  16237. /**
  16238. * Overwritten since sprite materials are transparent
  16239. * by default.
  16240. *
  16241. * @type {boolean}
  16242. * @default true
  16243. */
  16244. this.transparent = true;
  16245. /**
  16246. * Whether the material is affected by fog or not.
  16247. *
  16248. * @type {boolean}
  16249. * @default true
  16250. */
  16251. this.fog = true;
  16252. this.setValues( parameters );
  16253. }
  16254. copy( source ) {
  16255. super.copy( source );
  16256. this.color.copy( source.color );
  16257. this.map = source.map;
  16258. this.alphaMap = source.alphaMap;
  16259. this.rotation = source.rotation;
  16260. this.sizeAttenuation = source.sizeAttenuation;
  16261. this.fog = source.fog;
  16262. return this;
  16263. }
  16264. }
  16265. let _geometry;
  16266. const _intersectPoint = /*@__PURE__*/ new Vector3();
  16267. const _worldScale = /*@__PURE__*/ new Vector3();
  16268. const _mvPosition = /*@__PURE__*/ new Vector3();
  16269. const _alignedPosition = /*@__PURE__*/ new Vector2();
  16270. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  16271. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  16272. const _vA$1 = /*@__PURE__*/ new Vector3();
  16273. const _vB$1 = /*@__PURE__*/ new Vector3();
  16274. const _vC$1 = /*@__PURE__*/ new Vector3();
  16275. const _uvA = /*@__PURE__*/ new Vector2();
  16276. const _uvB = /*@__PURE__*/ new Vector2();
  16277. const _uvC = /*@__PURE__*/ new Vector2();
  16278. /**
  16279. * A sprite is a plane that always faces towards the camera, generally with a
  16280. * partially transparent texture applied.
  16281. *
  16282. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  16283. * have no effect.
  16284. *
  16285. * ```js
  16286. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  16287. * const material = new THREE.SpriteMaterial( { map: map } );
  16288. *
  16289. * const sprite = new THREE.Sprite( material );
  16290. * scene.add( sprite );
  16291. * ```
  16292. *
  16293. * @augments Object3D
  16294. */
  16295. class Sprite extends Object3D {
  16296. /**
  16297. * Constructs a new sprite.
  16298. *
  16299. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  16300. */
  16301. constructor( material = new SpriteMaterial() ) {
  16302. super();
  16303. /**
  16304. * This flag can be used for type testing.
  16305. *
  16306. * @type {boolean}
  16307. * @readonly
  16308. * @default true
  16309. */
  16310. this.isSprite = true;
  16311. this.type = 'Sprite';
  16312. if ( _geometry === undefined ) {
  16313. _geometry = new BufferGeometry();
  16314. const float32Array = new Float32Array( [
  16315. -0.5, -0.5, 0, 0, 0,
  16316. 0.5, -0.5, 0, 1, 0,
  16317. 0.5, 0.5, 0, 1, 1,
  16318. -0.5, 0.5, 0, 0, 1
  16319. ] );
  16320. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16321. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16322. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16323. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16324. }
  16325. /**
  16326. * The sprite geometry.
  16327. *
  16328. * @type {BufferGeometry}
  16329. */
  16330. this.geometry = _geometry;
  16331. /**
  16332. * The sprite material.
  16333. *
  16334. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  16335. */
  16336. this.material = material;
  16337. /**
  16338. * The sprite's anchor point, and the point around which the sprite rotates.
  16339. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  16340. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  16341. *
  16342. * @type {Vector2}
  16343. * @default (0.5,0.5)
  16344. */
  16345. this.center = new Vector2( 0.5, 0.5 );
  16346. /**
  16347. * The number of instances of this sprite.
  16348. * Can only be used with {@link WebGPURenderer}.
  16349. *
  16350. * @type {number}
  16351. * @default 1
  16352. */
  16353. this.count = 1;
  16354. }
  16355. /**
  16356. * Computes intersection points between a casted ray and this sprite.
  16357. *
  16358. * @param {Raycaster} raycaster - The raycaster.
  16359. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16360. */
  16361. raycast( raycaster, intersects ) {
  16362. if ( raycaster.camera === null ) {
  16363. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16364. }
  16365. _worldScale.setFromMatrixScale( this.matrixWorld );
  16366. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16367. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16368. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16369. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16370. _worldScale.multiplyScalar( - _mvPosition.z );
  16371. }
  16372. const rotation = this.material.rotation;
  16373. let sin, cos;
  16374. if ( rotation !== 0 ) {
  16375. cos = Math.cos( rotation );
  16376. sin = Math.sin( rotation );
  16377. }
  16378. const center = this.center;
  16379. transformVertex( _vA$1.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16380. transformVertex( _vB$1.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16381. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16382. _uvA.set( 0, 0 );
  16383. _uvB.set( 1, 0 );
  16384. _uvC.set( 1, 1 );
  16385. // check first triangle
  16386. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16387. if ( intersect === null ) {
  16388. // check second triangle
  16389. transformVertex( _vB$1.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16390. _uvB.set( 0, 1 );
  16391. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16392. if ( intersect === null ) {
  16393. return;
  16394. }
  16395. }
  16396. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16397. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16398. intersects.push( {
  16399. distance: distance,
  16400. point: _intersectPoint.clone(),
  16401. uv: Triangle.getInterpolation( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA, _uvB, _uvC, new Vector2() ),
  16402. face: null,
  16403. object: this
  16404. } );
  16405. }
  16406. copy( source, recursive ) {
  16407. super.copy( source, recursive );
  16408. if ( source.center !== undefined ) this.center.copy( source.center );
  16409. this.material = source.material;
  16410. return this;
  16411. }
  16412. }
  16413. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16414. // compute position in camera space
  16415. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16416. // to check if rotation is not zero
  16417. if ( sin !== undefined ) {
  16418. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16419. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16420. } else {
  16421. _rotatedPosition.copy( _alignedPosition );
  16422. }
  16423. vertexPosition.copy( mvPosition );
  16424. vertexPosition.x += _rotatedPosition.x;
  16425. vertexPosition.y += _rotatedPosition.y;
  16426. // transform to world space
  16427. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16428. }
  16429. const _v1$2 = /*@__PURE__*/ new Vector3();
  16430. const _v2$1 = /*@__PURE__*/ new Vector3();
  16431. /**
  16432. * A component for providing a basic Level of Detail (LOD) mechanism.
  16433. *
  16434. * Every LOD level is associated with an object, and rendering can be switched
  16435. * between them at the distances specified. Typically you would create, say,
  16436. * three meshes, one for far away (low detail), one for mid range (medium
  16437. * detail) and one for close up (high detail).
  16438. *
  16439. * ```js
  16440. * const lod = new THREE.LOD();
  16441. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  16442. *
  16443. * //Create spheres with 3 levels of detail and create new LOD levels for them
  16444. * for( let i = 0; i < 3; i++ ) {
  16445. *
  16446. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  16447. * const mesh = new THREE.Mesh( geometry, material );
  16448. * lod.addLevel( mesh, i * 75 );
  16449. *
  16450. * }
  16451. *
  16452. * scene.add( lod );
  16453. * ```
  16454. *
  16455. * @augments Object3D
  16456. */
  16457. class LOD extends Object3D {
  16458. /**
  16459. * Constructs a new LOD.
  16460. */
  16461. constructor() {
  16462. super();
  16463. /**
  16464. * This flag can be used for type testing.
  16465. *
  16466. * @type {boolean}
  16467. * @readonly
  16468. * @default true
  16469. */
  16470. this.isLOD = true;
  16471. /**
  16472. * The current LOD index.
  16473. *
  16474. * @private
  16475. * @type {number}
  16476. * @default 0
  16477. */
  16478. this._currentLevel = 0;
  16479. this.type = 'LOD';
  16480. Object.defineProperties( this, {
  16481. /**
  16482. * This array holds the LOD levels.
  16483. *
  16484. * @name LOD#levels
  16485. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  16486. */
  16487. levels: {
  16488. enumerable: true,
  16489. value: []
  16490. }
  16491. } );
  16492. /**
  16493. * Whether the LOD object is updated automatically by the renderer per frame
  16494. * or not. If set to `false`, you have to call {@link LOD#update} in the
  16495. * render loop by yourself.
  16496. *
  16497. * @type {boolean}
  16498. * @default true
  16499. */
  16500. this.autoUpdate = true;
  16501. }
  16502. copy( source ) {
  16503. super.copy( source, false );
  16504. const levels = source.levels;
  16505. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16506. const level = levels[ i ];
  16507. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  16508. }
  16509. this.autoUpdate = source.autoUpdate;
  16510. return this;
  16511. }
  16512. /**
  16513. * Adds a mesh that will display at a certain distance and greater. Typically
  16514. * the further away the distance, the lower the detail on the mesh.
  16515. *
  16516. * @param {Object3D} object - The 3D object to display at this level.
  16517. * @param {number} [distance=0] - The distance at which to display this level of detail.
  16518. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  16519. * @return {LOD} A reference to this instance.
  16520. */
  16521. addLevel( object, distance = 0, hysteresis = 0 ) {
  16522. distance = Math.abs( distance );
  16523. const levels = this.levels;
  16524. let l;
  16525. for ( l = 0; l < levels.length; l ++ ) {
  16526. if ( distance < levels[ l ].distance ) {
  16527. break;
  16528. }
  16529. }
  16530. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  16531. this.add( object );
  16532. return this;
  16533. }
  16534. /**
  16535. * Removes an existing level, based on the distance from the camera.
  16536. * Returns `true` when the level has been removed. Otherwise `false`.
  16537. *
  16538. * @param {number} distance - Distance of the level to remove.
  16539. * @return {boolean} Whether the level has been removed or not.
  16540. */
  16541. removeLevel( distance ) {
  16542. const levels = this.levels;
  16543. for ( let i = 0; i < levels.length; i ++ ) {
  16544. if ( levels[ i ].distance === distance ) {
  16545. const removedElements = levels.splice( i, 1 );
  16546. this.remove( removedElements[ 0 ].object );
  16547. return true;
  16548. }
  16549. }
  16550. return false;
  16551. }
  16552. /**
  16553. * Returns the currently active LOD level index.
  16554. *
  16555. * @return {number} The current active LOD level index.
  16556. */
  16557. getCurrentLevel() {
  16558. return this._currentLevel;
  16559. }
  16560. /**
  16561. * Returns a reference to the first 3D object that is greater than
  16562. * the given distance.
  16563. *
  16564. * @param {number} distance - The LOD distance.
  16565. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  16566. */
  16567. getObjectForDistance( distance ) {
  16568. const levels = this.levels;
  16569. if ( levels.length > 0 ) {
  16570. let i, l;
  16571. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16572. let levelDistance = levels[ i ].distance;
  16573. if ( levels[ i ].object.visible ) {
  16574. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16575. }
  16576. if ( distance < levelDistance ) {
  16577. break;
  16578. }
  16579. }
  16580. return levels[ i - 1 ].object;
  16581. }
  16582. return null;
  16583. }
  16584. /**
  16585. * Computes intersection points between a casted ray and this LOD.
  16586. *
  16587. * @param {Raycaster} raycaster - The raycaster.
  16588. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16589. */
  16590. raycast( raycaster, intersects ) {
  16591. const levels = this.levels;
  16592. if ( levels.length > 0 ) {
  16593. _v1$2.setFromMatrixPosition( this.matrixWorld );
  16594. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  16595. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16596. }
  16597. }
  16598. /**
  16599. * Updates the LOD by computing which LOD level should be visible according
  16600. * to the current distance of the given camera.
  16601. *
  16602. * @param {Camera} camera - The camera the scene is rendered with.
  16603. */
  16604. update( camera ) {
  16605. const levels = this.levels;
  16606. if ( levels.length > 1 ) {
  16607. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  16608. _v2$1.setFromMatrixPosition( this.matrixWorld );
  16609. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  16610. levels[ 0 ].object.visible = true;
  16611. let i, l;
  16612. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16613. let levelDistance = levels[ i ].distance;
  16614. if ( levels[ i ].object.visible ) {
  16615. levelDistance -= levelDistance * levels[ i ].hysteresis;
  16616. }
  16617. if ( distance >= levelDistance ) {
  16618. levels[ i - 1 ].object.visible = false;
  16619. levels[ i ].object.visible = true;
  16620. } else {
  16621. break;
  16622. }
  16623. }
  16624. this._currentLevel = i - 1;
  16625. for ( ; i < l; i ++ ) {
  16626. levels[ i ].object.visible = false;
  16627. }
  16628. }
  16629. }
  16630. toJSON( meta ) {
  16631. const data = super.toJSON( meta );
  16632. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16633. data.object.levels = [];
  16634. const levels = this.levels;
  16635. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16636. const level = levels[ i ];
  16637. data.object.levels.push( {
  16638. object: level.object.uuid,
  16639. distance: level.distance,
  16640. hysteresis: level.hysteresis
  16641. } );
  16642. }
  16643. return data;
  16644. }
  16645. }
  16646. const _vector$7 = /*@__PURE__*/ new Vector3();
  16647. const _segCenter = /*@__PURE__*/ new Vector3();
  16648. const _segDir = /*@__PURE__*/ new Vector3();
  16649. const _diff = /*@__PURE__*/ new Vector3();
  16650. const _edge1 = /*@__PURE__*/ new Vector3();
  16651. const _edge2 = /*@__PURE__*/ new Vector3();
  16652. const _normal$1 = /*@__PURE__*/ new Vector3();
  16653. /**
  16654. * A ray that emits from an origin in a certain direction. The class is used by
  16655. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  16656. * mouse picking (working out what objects in the 3D space the mouse is over)
  16657. * amongst other things.
  16658. */
  16659. class Ray {
  16660. /**
  16661. * Constructs a new ray.
  16662. *
  16663. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  16664. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  16665. */
  16666. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  16667. /**
  16668. * The origin of the ray.
  16669. *
  16670. * @type {Vector3}
  16671. */
  16672. this.origin = origin;
  16673. /**
  16674. * The (normalized) direction of the ray.
  16675. *
  16676. * @type {Vector3}
  16677. */
  16678. this.direction = direction;
  16679. }
  16680. /**
  16681. * Sets the ray's components by copying the given values.
  16682. *
  16683. * @param {Vector3} origin - The origin.
  16684. * @param {Vector3} direction - The direction.
  16685. * @return {Ray} A reference to this ray.
  16686. */
  16687. set( origin, direction ) {
  16688. this.origin.copy( origin );
  16689. this.direction.copy( direction );
  16690. return this;
  16691. }
  16692. /**
  16693. * Copies the values of the given ray to this instance.
  16694. *
  16695. * @param {Ray} ray - The ray to copy.
  16696. * @return {Ray} A reference to this ray.
  16697. */
  16698. copy( ray ) {
  16699. this.origin.copy( ray.origin );
  16700. this.direction.copy( ray.direction );
  16701. return this;
  16702. }
  16703. /**
  16704. * Returns a vector that is located at a given distance along this ray.
  16705. *
  16706. * @param {number} t - The distance along the ray to retrieve a position for.
  16707. * @param {Vector3} target - The target vector that is used to store the method's result.
  16708. * @return {Vector3} A position on the ray.
  16709. */
  16710. at( t, target ) {
  16711. return target.copy( this.origin ).addScaledVector( this.direction, t );
  16712. }
  16713. /**
  16714. * Adjusts the direction of the ray to point at the given vector in world space.
  16715. *
  16716. * @param {Vector3} v - The target position.
  16717. * @return {Ray} A reference to this ray.
  16718. */
  16719. lookAt( v ) {
  16720. this.direction.copy( v ).sub( this.origin ).normalize();
  16721. return this;
  16722. }
  16723. /**
  16724. * Shift the origin of this ray along its direction by the given distance.
  16725. *
  16726. * @param {number} t - The distance along the ray to interpolate.
  16727. * @return {Ray} A reference to this ray.
  16728. */
  16729. recast( t ) {
  16730. this.origin.copy( this.at( t, _vector$7 ) );
  16731. return this;
  16732. }
  16733. /**
  16734. * Returns the point along this ray that is closest to the given point.
  16735. *
  16736. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  16737. * @param {Vector3} target - The target vector that is used to store the method's result.
  16738. * @return {Vector3} The closest point on this ray.
  16739. */
  16740. closestPointToPoint( point, target ) {
  16741. target.subVectors( point, this.origin );
  16742. const directionDistance = target.dot( this.direction );
  16743. if ( directionDistance < 0 ) {
  16744. return target.copy( this.origin );
  16745. }
  16746. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16747. }
  16748. /**
  16749. * Returns the distance of the closest approach between this ray and the given point.
  16750. *
  16751. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16752. * @return {number} The distance.
  16753. */
  16754. distanceToPoint( point ) {
  16755. return Math.sqrt( this.distanceSqToPoint( point ) );
  16756. }
  16757. /**
  16758. * Returns the squared distance of the closest approach between this ray and the given point.
  16759. *
  16760. * @param {Vector3} point - A point in 3D space to compute the distance to.
  16761. * @return {number} The squared distance.
  16762. */
  16763. distanceSqToPoint( point ) {
  16764. const directionDistance = _vector$7.subVectors( point, this.origin ).dot( this.direction );
  16765. // point behind the ray
  16766. if ( directionDistance < 0 ) {
  16767. return this.origin.distanceToSquared( point );
  16768. }
  16769. _vector$7.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  16770. return _vector$7.distanceToSquared( point );
  16771. }
  16772. /**
  16773. * Returns the squared distance between this ray and the given line segment.
  16774. *
  16775. * @param {Vector3} v0 - The start point of the line segment.
  16776. * @param {Vector3} v1 - The end point of the line segment.
  16777. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  16778. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  16779. * @return {number} The squared distance.
  16780. */
  16781. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  16782. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  16783. // It returns the min distance between the ray and the segment
  16784. // defined by v0 and v1
  16785. // It can also set two optional targets :
  16786. // - The closest point on the ray
  16787. // - The closest point on the segment
  16788. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  16789. _segDir.copy( v1 ).sub( v0 ).normalize();
  16790. _diff.copy( this.origin ).sub( _segCenter );
  16791. const segExtent = v0.distanceTo( v1 ) * 0.5;
  16792. const a01 = - this.direction.dot( _segDir );
  16793. const b0 = _diff.dot( this.direction );
  16794. const b1 = - _diff.dot( _segDir );
  16795. const c = _diff.lengthSq();
  16796. const det = Math.abs( 1 - a01 * a01 );
  16797. let s0, s1, sqrDist, extDet;
  16798. if ( det > 0 ) {
  16799. // The ray and segment are not parallel.
  16800. s0 = a01 * b1 - b0;
  16801. s1 = a01 * b0 - b1;
  16802. extDet = segExtent * det;
  16803. if ( s0 >= 0 ) {
  16804. if ( s1 >= - extDet ) {
  16805. if ( s1 <= extDet ) {
  16806. // region 0
  16807. // Minimum at interior points of ray and segment.
  16808. const invDet = 1 / det;
  16809. s0 *= invDet;
  16810. s1 *= invDet;
  16811. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  16812. } else {
  16813. // region 1
  16814. s1 = segExtent;
  16815. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16816. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16817. }
  16818. } else {
  16819. // region 5
  16820. s1 = - segExtent;
  16821. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16822. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16823. }
  16824. } else {
  16825. if ( s1 <= - extDet ) {
  16826. // region 4
  16827. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  16828. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16829. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16830. } else if ( s1 <= extDet ) {
  16831. // region 3
  16832. s0 = 0;
  16833. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16834. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  16835. } else {
  16836. // region 2
  16837. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  16838. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  16839. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16840. }
  16841. }
  16842. } else {
  16843. // Ray and segment are parallel.
  16844. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  16845. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  16846. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  16847. }
  16848. if ( optionalPointOnRay ) {
  16849. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  16850. }
  16851. if ( optionalPointOnSegment ) {
  16852. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  16853. }
  16854. return sqrDist;
  16855. }
  16856. /**
  16857. * Intersects this ray with the given sphere, returning the intersection
  16858. * point or `null` if there is no intersection.
  16859. *
  16860. * @param {Sphere} sphere - The sphere to intersect.
  16861. * @param {Vector3} target - The target vector that is used to store the method's result.
  16862. * @return {?Vector3} The intersection point.
  16863. */
  16864. intersectSphere( sphere, target ) {
  16865. _vector$7.subVectors( sphere.center, this.origin );
  16866. const tca = _vector$7.dot( this.direction );
  16867. const d2 = _vector$7.dot( _vector$7 ) - tca * tca;
  16868. const radius2 = sphere.radius * sphere.radius;
  16869. if ( d2 > radius2 ) return null;
  16870. const thc = Math.sqrt( radius2 - d2 );
  16871. // t0 = first intersect point - entrance on front of sphere
  16872. const t0 = tca - thc;
  16873. // t1 = second intersect point - exit point on back of sphere
  16874. const t1 = tca + thc;
  16875. // test to see if t1 is behind the ray - if so, return null
  16876. if ( t1 < 0 ) return null;
  16877. // test to see if t0 is behind the ray:
  16878. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  16879. // in order to always return an intersect point that is in front of the ray.
  16880. if ( t0 < 0 ) return this.at( t1, target );
  16881. // else t0 is in front of the ray, so return the first collision point scaled by t0
  16882. return this.at( t0, target );
  16883. }
  16884. /**
  16885. * Returns `true` if this ray intersects with the given sphere.
  16886. *
  16887. * @param {Sphere} sphere - The sphere to intersect.
  16888. * @return {boolean} Whether this ray intersects with the given sphere or not.
  16889. */
  16890. intersectsSphere( sphere ) {
  16891. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  16892. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  16893. }
  16894. /**
  16895. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  16896. * does not intersect with the plane.
  16897. *
  16898. * @param {Plane} plane - The plane to compute the distance to.
  16899. * @return {?number} Whether this ray intersects with the given sphere or not.
  16900. */
  16901. distanceToPlane( plane ) {
  16902. const denominator = plane.normal.dot( this.direction );
  16903. if ( denominator === 0 ) {
  16904. // line is coplanar, return origin
  16905. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  16906. return 0;
  16907. }
  16908. // Null is preferable to undefined since undefined means.... it is undefined
  16909. return null;
  16910. }
  16911. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  16912. // Return if the ray never intersects the plane
  16913. return t >= 0 ? t : null;
  16914. }
  16915. /**
  16916. * Intersects this ray with the given plane, returning the intersection
  16917. * point or `null` if there is no intersection.
  16918. *
  16919. * @param {Plane} plane - The plane to intersect.
  16920. * @param {Vector3} target - The target vector that is used to store the method's result.
  16921. * @return {?Vector3} The intersection point.
  16922. */
  16923. intersectPlane( plane, target ) {
  16924. const t = this.distanceToPlane( plane );
  16925. if ( t === null ) {
  16926. return null;
  16927. }
  16928. return this.at( t, target );
  16929. }
  16930. /**
  16931. * Returns `true` if this ray intersects with the given plane.
  16932. *
  16933. * @param {Plane} plane - The plane to intersect.
  16934. * @return {boolean} Whether this ray intersects with the given plane or not.
  16935. */
  16936. intersectsPlane( plane ) {
  16937. // check if the ray lies on the plane first
  16938. const distToPoint = plane.distanceToPoint( this.origin );
  16939. if ( distToPoint === 0 ) {
  16940. return true;
  16941. }
  16942. const denominator = plane.normal.dot( this.direction );
  16943. if ( denominator * distToPoint < 0 ) {
  16944. return true;
  16945. }
  16946. // ray origin is behind the plane (and is pointing behind it)
  16947. return false;
  16948. }
  16949. /**
  16950. * Intersects this ray with the given bounding box, returning the intersection
  16951. * point or `null` if there is no intersection.
  16952. *
  16953. * @param {Box3} box - The box to intersect.
  16954. * @param {Vector3} target - The target vector that is used to store the method's result.
  16955. * @return {?Vector3} The intersection point.
  16956. */
  16957. intersectBox( box, target ) {
  16958. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  16959. const invdirx = 1 / this.direction.x,
  16960. invdiry = 1 / this.direction.y,
  16961. invdirz = 1 / this.direction.z;
  16962. const origin = this.origin;
  16963. if ( invdirx >= 0 ) {
  16964. tmin = ( box.min.x - origin.x ) * invdirx;
  16965. tmax = ( box.max.x - origin.x ) * invdirx;
  16966. } else {
  16967. tmin = ( box.max.x - origin.x ) * invdirx;
  16968. tmax = ( box.min.x - origin.x ) * invdirx;
  16969. }
  16970. if ( invdiry >= 0 ) {
  16971. tymin = ( box.min.y - origin.y ) * invdiry;
  16972. tymax = ( box.max.y - origin.y ) * invdiry;
  16973. } else {
  16974. tymin = ( box.max.y - origin.y ) * invdiry;
  16975. tymax = ( box.min.y - origin.y ) * invdiry;
  16976. }
  16977. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  16978. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  16979. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  16980. if ( invdirz >= 0 ) {
  16981. tzmin = ( box.min.z - origin.z ) * invdirz;
  16982. tzmax = ( box.max.z - origin.z ) * invdirz;
  16983. } else {
  16984. tzmin = ( box.max.z - origin.z ) * invdirz;
  16985. tzmax = ( box.min.z - origin.z ) * invdirz;
  16986. }
  16987. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  16988. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  16989. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  16990. //return point closest to the ray (positive side)
  16991. if ( tmax < 0 ) return null;
  16992. return this.at( tmin >= 0 ? tmin : tmax, target );
  16993. }
  16994. /**
  16995. * Returns `true` if this ray intersects with the given box.
  16996. *
  16997. * @param {Box3} box - The box to intersect.
  16998. * @return {boolean} Whether this ray intersects with the given box or not.
  16999. */
  17000. intersectsBox( box ) {
  17001. return this.intersectBox( box, _vector$7 ) !== null;
  17002. }
  17003. /**
  17004. * Intersects this ray with the given triangle, returning the intersection
  17005. * point or `null` if there is no intersection.
  17006. *
  17007. * @param {Vector3} a - The first vertex of the triangle.
  17008. * @param {Vector3} b - The second vertex of the triangle.
  17009. * @param {Vector3} c - The third vertex of the triangle.
  17010. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  17011. * @param {Vector3} target - The target vector that is used to store the method's result.
  17012. * @return {?Vector3} The intersection point.
  17013. */
  17014. intersectTriangle( a, b, c, backfaceCulling, target ) {
  17015. // Compute the offset origin, edges, and normal.
  17016. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  17017. _edge1.subVectors( b, a );
  17018. _edge2.subVectors( c, a );
  17019. _normal$1.crossVectors( _edge1, _edge2 );
  17020. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  17021. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  17022. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  17023. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  17024. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  17025. let DdN = this.direction.dot( _normal$1 );
  17026. let sign;
  17027. if ( DdN > 0 ) {
  17028. if ( backfaceCulling ) return null;
  17029. sign = 1;
  17030. } else if ( DdN < 0 ) {
  17031. sign = -1;
  17032. DdN = - DdN;
  17033. } else {
  17034. return null;
  17035. }
  17036. _diff.subVectors( this.origin, a );
  17037. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  17038. // b1 < 0, no intersection
  17039. if ( DdQxE2 < 0 ) {
  17040. return null;
  17041. }
  17042. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  17043. // b2 < 0, no intersection
  17044. if ( DdE1xQ < 0 ) {
  17045. return null;
  17046. }
  17047. // b1+b2 > 1, no intersection
  17048. if ( DdQxE2 + DdE1xQ > DdN ) {
  17049. return null;
  17050. }
  17051. // Line intersects triangle, check if ray does.
  17052. const QdN = - sign * _diff.dot( _normal$1 );
  17053. // t < 0, no intersection
  17054. if ( QdN < 0 ) {
  17055. return null;
  17056. }
  17057. // Ray intersects triangle.
  17058. return this.at( QdN / DdN, target );
  17059. }
  17060. /**
  17061. * Transforms this ray with the given 4x4 transformation matrix.
  17062. *
  17063. * @param {Matrix4} matrix4 - The transformation matrix.
  17064. * @return {Ray} A reference to this ray.
  17065. */
  17066. applyMatrix4( matrix4 ) {
  17067. this.origin.applyMatrix4( matrix4 );
  17068. this.direction.transformDirection( matrix4 );
  17069. return this;
  17070. }
  17071. /**
  17072. * Returns `true` if this ray is equal with the given one.
  17073. *
  17074. * @param {Ray} ray - The ray to test for equality.
  17075. * @return {boolean} Whether this ray is equal with the given one.
  17076. */
  17077. equals( ray ) {
  17078. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  17079. }
  17080. /**
  17081. * Returns a new ray with copied values from this instance.
  17082. *
  17083. * @return {Ray} A clone of this instance.
  17084. */
  17085. clone() {
  17086. return new this.constructor().copy( this );
  17087. }
  17088. }
  17089. /**
  17090. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  17091. *
  17092. * This material is not affected by lights.
  17093. *
  17094. * @augments Material
  17095. * @demo scenes/material-browser.html#MeshBasicMaterial
  17096. */
  17097. class MeshBasicMaterial extends Material {
  17098. /**
  17099. * Constructs a new mesh basic material.
  17100. *
  17101. * @param {Object} [parameters] - An object with one or more properties
  17102. * defining the material's appearance. Any property of the material
  17103. * (including any property from inherited materials) can be passed
  17104. * in here. Color values can be passed any type of value accepted
  17105. * by {@link Color#set}.
  17106. */
  17107. constructor( parameters ) {
  17108. super();
  17109. /**
  17110. * This flag can be used for type testing.
  17111. *
  17112. * @type {boolean}
  17113. * @readonly
  17114. * @default true
  17115. */
  17116. this.isMeshBasicMaterial = true;
  17117. this.type = 'MeshBasicMaterial';
  17118. /**
  17119. * Color of the material.
  17120. *
  17121. * @type {Color}
  17122. * @default (1,1,1)
  17123. */
  17124. this.color = new Color( 0xffffff ); // diffuse
  17125. /**
  17126. * The color map. May optionally include an alpha channel, typically combined
  17127. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17128. * color is modulated by the diffuse `color`.
  17129. *
  17130. * `map` represents color data, and the texture must be assigned a
  17131. * {@link Texture#colorSpace}. Most `map` textures set
  17132. * `texture.colorSpace = SRGBColorSpace`.
  17133. *
  17134. * @type {?Texture}
  17135. * @default null
  17136. */
  17137. this.map = null;
  17138. /**
  17139. * The light map. Requires a second set of UVs.
  17140. *
  17141. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  17142. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  17143. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  17144. * such as `.exr` or `.hdr`.
  17145. *
  17146. * @type {?Texture}
  17147. * @default null
  17148. */
  17149. this.lightMap = null;
  17150. /**
  17151. * Intensity of the baked light.
  17152. *
  17153. * @type {number}
  17154. * @default 1
  17155. */
  17156. this.lightMapIntensity = 1.0;
  17157. /**
  17158. * The red channel of this texture is used as the ambient occlusion map.
  17159. * Requires a second set of UVs.
  17160. *
  17161. * `aoMap` represents non-color data. Any texture assigned must have
  17162. * `texture.colorSpace = NoColorSpace` (default).
  17163. *
  17164. * @type {?Texture}
  17165. * @default null
  17166. */
  17167. this.aoMap = null;
  17168. /**
  17169. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  17170. * disables ambient occlusion. Where intensity is `1` and the AO map's
  17171. * red channel is also `1`, ambient light is fully occluded on a surface.
  17172. *
  17173. * @type {number}
  17174. * @default 1
  17175. */
  17176. this.aoMapIntensity = 1.0;
  17177. /**
  17178. * Specular map used by the material.
  17179. *
  17180. * `specularMap` represents color data, and the texture must be assigned a
  17181. * {@link Texture#colorSpace}. Most `specularMap` textures set
  17182. * `texture.colorSpace = SRGBColorSpace`.
  17183. *
  17184. * @type {?Texture}
  17185. * @default null
  17186. */
  17187. this.specularMap = null;
  17188. /**
  17189. * The alpha map is a grayscale texture that controls the opacity across the
  17190. * surface (black: fully transparent; white: fully opaque).
  17191. *
  17192. * Only the color of the texture is used, ignoring the alpha channel if one
  17193. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17194. * when sampling this texture due to the extra bit of precision provided for
  17195. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17196. * luminance/alpha textures will also still work as expected.
  17197. *
  17198. * `alphaMap` represents non-color data. Any texture assigned must have
  17199. * `texture.colorSpace = NoColorSpace` (default).
  17200. *
  17201. * @type {?Texture}
  17202. * @default null
  17203. */
  17204. this.alphaMap = null;
  17205. /**
  17206. * The environment map.
  17207. *
  17208. * `envMap` represents luminance data, and the texture must be assigned
  17209. * a {@link Texture#colorSpace}. Most `envMap` textures set
  17210. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  17211. * such as `.exr` or `.hdr`.
  17212. *
  17213. * @type {?Texture}
  17214. * @default null
  17215. */
  17216. this.envMap = null;
  17217. /**
  17218. * The rotation of the environment map in radians.
  17219. *
  17220. * @type {Euler}
  17221. * @default (0,0,0)
  17222. */
  17223. this.envMapRotation = new Euler();
  17224. /**
  17225. * How to combine the result of the surface's color with the environment map, if any.
  17226. *
  17227. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  17228. * blend between the two colors.
  17229. *
  17230. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  17231. * @default MultiplyOperation
  17232. */
  17233. this.combine = MultiplyOperation;
  17234. /**
  17235. * How much the environment map affects the surface.
  17236. * The valid range is between `0` (no reflections) and `1` (full reflections).
  17237. *
  17238. * @type {number}
  17239. * @default 1
  17240. */
  17241. this.reflectivity = 1;
  17242. /**
  17243. * The index of refraction (IOR) of air (approximately 1) divided by the
  17244. * index of refraction of the material. It is used with environment mapping
  17245. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  17246. * The refraction ratio should not exceed `1`.
  17247. *
  17248. * @type {number}
  17249. * @default 0.98
  17250. */
  17251. this.refractionRatio = 0.98;
  17252. /**
  17253. * Renders the geometry as a wireframe.
  17254. *
  17255. * @type {boolean}
  17256. * @default false
  17257. */
  17258. this.wireframe = false;
  17259. /**
  17260. * Controls the thickness of the wireframe.
  17261. *
  17262. * Can only be used with {@link SVGRenderer}.
  17263. *
  17264. * @type {number}
  17265. * @default 1
  17266. */
  17267. this.wireframeLinewidth = 1;
  17268. /**
  17269. * Defines appearance of wireframe ends.
  17270. *
  17271. * Can only be used with {@link SVGRenderer}.
  17272. *
  17273. * @type {('round'|'bevel'|'miter')}
  17274. * @default 'round'
  17275. */
  17276. this.wireframeLinecap = 'round';
  17277. /**
  17278. * Defines appearance of wireframe joints.
  17279. *
  17280. * Can only be used with {@link SVGRenderer}.
  17281. *
  17282. * @type {('round'|'bevel'|'miter')}
  17283. * @default 'round'
  17284. */
  17285. this.wireframeLinejoin = 'round';
  17286. /**
  17287. * Whether the material is affected by fog or not.
  17288. *
  17289. * @type {boolean}
  17290. * @default true
  17291. */
  17292. this.fog = true;
  17293. this.setValues( parameters );
  17294. }
  17295. copy( source ) {
  17296. super.copy( source );
  17297. this.color.copy( source.color );
  17298. this.map = source.map;
  17299. this.lightMap = source.lightMap;
  17300. this.lightMapIntensity = source.lightMapIntensity;
  17301. this.aoMap = source.aoMap;
  17302. this.aoMapIntensity = source.aoMapIntensity;
  17303. this.specularMap = source.specularMap;
  17304. this.alphaMap = source.alphaMap;
  17305. this.envMap = source.envMap;
  17306. this.envMapRotation.copy( source.envMapRotation );
  17307. this.combine = source.combine;
  17308. this.reflectivity = source.reflectivity;
  17309. this.refractionRatio = source.refractionRatio;
  17310. this.wireframe = source.wireframe;
  17311. this.wireframeLinewidth = source.wireframeLinewidth;
  17312. this.wireframeLinecap = source.wireframeLinecap;
  17313. this.wireframeLinejoin = source.wireframeLinejoin;
  17314. this.fog = source.fog;
  17315. return this;
  17316. }
  17317. }
  17318. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  17319. const _ray$3 = /*@__PURE__*/ new Ray();
  17320. const _sphere$6 = /*@__PURE__*/ new Sphere();
  17321. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  17322. const _vA = /*@__PURE__*/ new Vector3();
  17323. const _vB = /*@__PURE__*/ new Vector3();
  17324. const _vC = /*@__PURE__*/ new Vector3();
  17325. const _tempA = /*@__PURE__*/ new Vector3();
  17326. const _morphA = /*@__PURE__*/ new Vector3();
  17327. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  17328. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  17329. /**
  17330. * Class representing triangular polygon mesh based objects.
  17331. *
  17332. * ```js
  17333. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  17334. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  17335. * const mesh = new THREE.Mesh( geometry, material );
  17336. * scene.add( mesh );
  17337. * ```
  17338. *
  17339. * @augments Object3D
  17340. */
  17341. class Mesh extends Object3D {
  17342. /**
  17343. * Constructs a new mesh.
  17344. *
  17345. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17346. * @param {Material|Array<Material>} [material] - The mesh material.
  17347. */
  17348. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  17349. super();
  17350. /**
  17351. * This flag can be used for type testing.
  17352. *
  17353. * @type {boolean}
  17354. * @readonly
  17355. * @default true
  17356. */
  17357. this.isMesh = true;
  17358. this.type = 'Mesh';
  17359. /**
  17360. * The mesh geometry.
  17361. *
  17362. * @type {BufferGeometry}
  17363. */
  17364. this.geometry = geometry;
  17365. /**
  17366. * The mesh material.
  17367. *
  17368. * @type {Material|Array<Material>}
  17369. * @default MeshBasicMaterial
  17370. */
  17371. this.material = material;
  17372. /**
  17373. * A dictionary representing the morph targets in the geometry. The key is the
  17374. * morph targets name, the value its attribute index. This member is `undefined`
  17375. * by default and only set when morph targets are detected in the geometry.
  17376. *
  17377. * @type {Object<string,number>|undefined}
  17378. * @default undefined
  17379. */
  17380. this.morphTargetDictionary = undefined;
  17381. /**
  17382. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17383. * is applied. This member is `undefined` by default and only set when morph targets are
  17384. * detected in the geometry.
  17385. *
  17386. * @type {Array<number>|undefined}
  17387. * @default undefined
  17388. */
  17389. this.morphTargetInfluences = undefined;
  17390. /**
  17391. * The number of instances of this mesh.
  17392. * Can only be used with {@link WebGPURenderer}.
  17393. *
  17394. * @type {number}
  17395. * @default 1
  17396. */
  17397. this.count = 1;
  17398. this.updateMorphTargets();
  17399. }
  17400. copy( source, recursive ) {
  17401. super.copy( source, recursive );
  17402. if ( source.morphTargetInfluences !== undefined ) {
  17403. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  17404. }
  17405. if ( source.morphTargetDictionary !== undefined ) {
  17406. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  17407. }
  17408. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17409. this.geometry = source.geometry;
  17410. return this;
  17411. }
  17412. /**
  17413. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  17414. * to make sure existing morph targets can influence this 3D object.
  17415. */
  17416. updateMorphTargets() {
  17417. const geometry = this.geometry;
  17418. const morphAttributes = geometry.morphAttributes;
  17419. const keys = Object.keys( morphAttributes );
  17420. if ( keys.length > 0 ) {
  17421. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17422. if ( morphAttribute !== undefined ) {
  17423. this.morphTargetInfluences = [];
  17424. this.morphTargetDictionary = {};
  17425. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17426. const name = morphAttribute[ m ].name || String( m );
  17427. this.morphTargetInfluences.push( 0 );
  17428. this.morphTargetDictionary[ name ] = m;
  17429. }
  17430. }
  17431. }
  17432. }
  17433. /**
  17434. * Returns the local-space position of the vertex at the given index, taking into
  17435. * account the current animation state of both morph targets and skinning.
  17436. *
  17437. * @param {number} index - The vertex index.
  17438. * @param {Vector3} target - The target object that is used to store the method's result.
  17439. * @return {Vector3} The vertex position in local space.
  17440. */
  17441. getVertexPosition( index, target ) {
  17442. const geometry = this.geometry;
  17443. const position = geometry.attributes.position;
  17444. const morphPosition = geometry.morphAttributes.position;
  17445. const morphTargetsRelative = geometry.morphTargetsRelative;
  17446. target.fromBufferAttribute( position, index );
  17447. const morphInfluences = this.morphTargetInfluences;
  17448. if ( morphPosition && morphInfluences ) {
  17449. _morphA.set( 0, 0, 0 );
  17450. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  17451. const influence = morphInfluences[ i ];
  17452. const morphAttribute = morphPosition[ i ];
  17453. if ( influence === 0 ) continue;
  17454. _tempA.fromBufferAttribute( morphAttribute, index );
  17455. if ( morphTargetsRelative ) {
  17456. _morphA.addScaledVector( _tempA, influence );
  17457. } else {
  17458. _morphA.addScaledVector( _tempA.sub( target ), influence );
  17459. }
  17460. }
  17461. target.add( _morphA );
  17462. }
  17463. return target;
  17464. }
  17465. /**
  17466. * Computes intersection points between a casted ray and this line.
  17467. *
  17468. * @param {Raycaster} raycaster - The raycaster.
  17469. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17470. */
  17471. raycast( raycaster, intersects ) {
  17472. const geometry = this.geometry;
  17473. const material = this.material;
  17474. const matrixWorld = this.matrixWorld;
  17475. if ( material === undefined ) return;
  17476. // test with bounding sphere in world space
  17477. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17478. _sphere$6.copy( geometry.boundingSphere );
  17479. _sphere$6.applyMatrix4( matrixWorld );
  17480. // check distance from ray origin to bounding sphere
  17481. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  17482. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  17483. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  17484. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  17485. }
  17486. // convert ray to local space of mesh
  17487. _inverseMatrix$3.copy( matrixWorld ).invert();
  17488. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  17489. // test with bounding box in local space
  17490. if ( geometry.boundingBox !== null ) {
  17491. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  17492. }
  17493. // test for intersections with geometry
  17494. this._computeIntersections( raycaster, intersects, _ray$3 );
  17495. }
  17496. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  17497. let intersection;
  17498. const geometry = this.geometry;
  17499. const material = this.material;
  17500. const index = geometry.index;
  17501. const position = geometry.attributes.position;
  17502. const uv = geometry.attributes.uv;
  17503. const uv1 = geometry.attributes.uv1;
  17504. const normal = geometry.attributes.normal;
  17505. const groups = geometry.groups;
  17506. const drawRange = geometry.drawRange;
  17507. if ( index !== null ) {
  17508. // indexed buffer geometry
  17509. if ( Array.isArray( material ) ) {
  17510. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17511. const group = groups[ i ];
  17512. const groupMaterial = material[ group.materialIndex ];
  17513. const start = Math.max( group.start, drawRange.start );
  17514. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17515. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17516. const a = index.getX( j );
  17517. const b = index.getX( j + 1 );
  17518. const c = index.getX( j + 2 );
  17519. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17520. if ( intersection ) {
  17521. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  17522. intersection.face.materialIndex = group.materialIndex;
  17523. intersects.push( intersection );
  17524. }
  17525. }
  17526. }
  17527. } else {
  17528. const start = Math.max( 0, drawRange.start );
  17529. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17530. for ( let i = start, il = end; i < il; i += 3 ) {
  17531. const a = index.getX( i );
  17532. const b = index.getX( i + 1 );
  17533. const c = index.getX( i + 2 );
  17534. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17535. if ( intersection ) {
  17536. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  17537. intersects.push( intersection );
  17538. }
  17539. }
  17540. }
  17541. } else if ( position !== undefined ) {
  17542. // non-indexed buffer geometry
  17543. if ( Array.isArray( material ) ) {
  17544. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  17545. const group = groups[ i ];
  17546. const groupMaterial = material[ group.materialIndex ];
  17547. const start = Math.max( group.start, drawRange.start );
  17548. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  17549. for ( let j = start, jl = end; j < jl; j += 3 ) {
  17550. const a = j;
  17551. const b = j + 1;
  17552. const c = j + 2;
  17553. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17554. if ( intersection ) {
  17555. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  17556. intersection.face.materialIndex = group.materialIndex;
  17557. intersects.push( intersection );
  17558. }
  17559. }
  17560. }
  17561. } else {
  17562. const start = Math.max( 0, drawRange.start );
  17563. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  17564. for ( let i = start, il = end; i < il; i += 3 ) {
  17565. const a = i;
  17566. const b = i + 1;
  17567. const c = i + 2;
  17568. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  17569. if ( intersection ) {
  17570. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  17571. intersects.push( intersection );
  17572. }
  17573. }
  17574. }
  17575. }
  17576. }
  17577. }
  17578. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  17579. let intersect;
  17580. if ( material.side === BackSide ) {
  17581. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  17582. } else {
  17583. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  17584. }
  17585. if ( intersect === null ) return null;
  17586. _intersectionPointWorld.copy( point );
  17587. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  17588. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  17589. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  17590. return {
  17591. distance: distance,
  17592. point: _intersectionPointWorld.clone(),
  17593. object: object
  17594. };
  17595. }
  17596. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  17597. object.getVertexPosition( a, _vA );
  17598. object.getVertexPosition( b, _vB );
  17599. object.getVertexPosition( c, _vC );
  17600. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  17601. if ( intersection ) {
  17602. const barycoord = new Vector3();
  17603. Triangle.getBarycoord( _intersectionPoint, _vA, _vB, _vC, barycoord );
  17604. if ( uv ) {
  17605. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  17606. }
  17607. if ( uv1 ) {
  17608. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  17609. }
  17610. if ( normal ) {
  17611. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  17612. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  17613. intersection.normal.multiplyScalar( -1 );
  17614. }
  17615. }
  17616. const face = {
  17617. a: a,
  17618. b: b,
  17619. c: c,
  17620. normal: new Vector3(),
  17621. materialIndex: 0
  17622. };
  17623. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  17624. intersection.face = face;
  17625. intersection.barycoord = barycoord;
  17626. }
  17627. return intersection;
  17628. }
  17629. const _baseVector = /*@__PURE__*/ new Vector4();
  17630. const _skinIndex = /*@__PURE__*/ new Vector4();
  17631. const _skinWeight = /*@__PURE__*/ new Vector4();
  17632. const _vector4 = /*@__PURE__*/ new Vector4();
  17633. const _matrix4 = /*@__PURE__*/ new Matrix4();
  17634. const _vertex = /*@__PURE__*/ new Vector3();
  17635. const _sphere$5 = /*@__PURE__*/ new Sphere();
  17636. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  17637. const _ray$2 = /*@__PURE__*/ new Ray();
  17638. /**
  17639. * A mesh that has a {@link Skeleton} that can then be used to animate the
  17640. * vertices of the geometry with skinning/skeleton animation.
  17641. *
  17642. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  17643. * as buffer attributes in its geometry. These attribute define which bones affect a single
  17644. * vertex to a certain extend.
  17645. *
  17646. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  17647. * or {@link FBXLoader } import respective models.
  17648. *
  17649. * @augments Mesh
  17650. * @demo scenes/bones-browser.html
  17651. */
  17652. class SkinnedMesh extends Mesh {
  17653. /**
  17654. * Constructs a new skinned mesh.
  17655. *
  17656. * @param {BufferGeometry} [geometry] - The mesh geometry.
  17657. * @param {Material|Array<Material>} [material] - The mesh material.
  17658. */
  17659. constructor( geometry, material ) {
  17660. super( geometry, material );
  17661. /**
  17662. * This flag can be used for type testing.
  17663. *
  17664. * @type {boolean}
  17665. * @readonly
  17666. * @default true
  17667. */
  17668. this.isSkinnedMesh = true;
  17669. this.type = 'SkinnedMesh';
  17670. /**
  17671. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  17672. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  17673. * across multiple skinned meshes.
  17674. *
  17675. * @type {(AttachedBindMode|DetachedBindMode)}
  17676. * @default AttachedBindMode
  17677. */
  17678. this.bindMode = AttachedBindMode;
  17679. /**
  17680. * The base matrix that is used for the bound bone transforms.
  17681. *
  17682. * @type {Matrix4}
  17683. */
  17684. this.bindMatrix = new Matrix4();
  17685. /**
  17686. * The base matrix that is used for resetting the bound bone transforms.
  17687. *
  17688. * @type {Matrix4}
  17689. */
  17690. this.bindMatrixInverse = new Matrix4();
  17691. /**
  17692. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  17693. *
  17694. * @type {?Box3}
  17695. * @default null
  17696. */
  17697. this.boundingBox = null;
  17698. /**
  17699. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  17700. *
  17701. * @type {?Sphere}
  17702. * @default null
  17703. */
  17704. this.boundingSphere = null;
  17705. }
  17706. /**
  17707. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  17708. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  17709. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  17710. * the current animation state.
  17711. */
  17712. computeBoundingBox() {
  17713. const geometry = this.geometry;
  17714. if ( this.boundingBox === null ) {
  17715. this.boundingBox = new Box3();
  17716. }
  17717. this.boundingBox.makeEmpty();
  17718. const positionAttribute = geometry.getAttribute( 'position' );
  17719. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17720. this.getVertexPosition( i, _vertex );
  17721. this.boundingBox.expandByPoint( _vertex );
  17722. }
  17723. }
  17724. /**
  17725. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  17726. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  17727. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  17728. * per frame in order to reflect the current animation state.
  17729. */
  17730. computeBoundingSphere() {
  17731. const geometry = this.geometry;
  17732. if ( this.boundingSphere === null ) {
  17733. this.boundingSphere = new Sphere();
  17734. }
  17735. this.boundingSphere.makeEmpty();
  17736. const positionAttribute = geometry.getAttribute( 'position' );
  17737. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  17738. this.getVertexPosition( i, _vertex );
  17739. this.boundingSphere.expandByPoint( _vertex );
  17740. }
  17741. }
  17742. copy( source, recursive ) {
  17743. super.copy( source, recursive );
  17744. this.bindMode = source.bindMode;
  17745. this.bindMatrix.copy( source.bindMatrix );
  17746. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17747. this.skeleton = source.skeleton;
  17748. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  17749. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  17750. return this;
  17751. }
  17752. raycast( raycaster, intersects ) {
  17753. const material = this.material;
  17754. const matrixWorld = this.matrixWorld;
  17755. if ( material === undefined ) return;
  17756. // test with bounding sphere in world space
  17757. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  17758. _sphere$5.copy( this.boundingSphere );
  17759. _sphere$5.applyMatrix4( matrixWorld );
  17760. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  17761. // convert ray to local space of skinned mesh
  17762. _inverseMatrix$2.copy( matrixWorld ).invert();
  17763. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  17764. // test with bounding box in local space
  17765. if ( this.boundingBox !== null ) {
  17766. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  17767. }
  17768. // test for intersections with geometry
  17769. this._computeIntersections( raycaster, intersects, _ray$2 );
  17770. }
  17771. getVertexPosition( index, target ) {
  17772. super.getVertexPosition( index, target );
  17773. this.applyBoneTransform( index, target );
  17774. return target;
  17775. }
  17776. /**
  17777. * Binds the given skeleton to the skinned mesh.
  17778. *
  17779. * @param {Skeleton} skeleton - The skeleton to bind.
  17780. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  17781. * the skinned mesh's world matrix will be used instead.
  17782. */
  17783. bind( skeleton, bindMatrix ) {
  17784. this.skeleton = skeleton;
  17785. if ( bindMatrix === undefined ) {
  17786. this.updateMatrixWorld( true );
  17787. this.skeleton.calculateInverses();
  17788. bindMatrix = this.matrixWorld;
  17789. }
  17790. this.bindMatrix.copy( bindMatrix );
  17791. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17792. }
  17793. /**
  17794. * This method sets the skinned mesh in the rest pose).
  17795. */
  17796. pose() {
  17797. this.skeleton.pose();
  17798. }
  17799. /**
  17800. * Normalizes the skin weights which are defined as a buffer attribute
  17801. * in the skinned mesh's geometry.
  17802. */
  17803. normalizeSkinWeights() {
  17804. const vector = new Vector4();
  17805. const skinWeight = this.geometry.attributes.skinWeight;
  17806. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17807. vector.fromBufferAttribute( skinWeight, i );
  17808. const scale = 1.0 / vector.manhattanLength();
  17809. if ( scale !== Infinity ) {
  17810. vector.multiplyScalar( scale );
  17811. } else {
  17812. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17813. }
  17814. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17815. }
  17816. }
  17817. updateMatrixWorld( force ) {
  17818. super.updateMatrixWorld( force );
  17819. if ( this.bindMode === AttachedBindMode ) {
  17820. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17821. } else if ( this.bindMode === DetachedBindMode ) {
  17822. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17823. } else {
  17824. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17825. }
  17826. }
  17827. /**
  17828. * Applies the bone transform associated with the given index to the given
  17829. * vector. Can be used to transform positions or direction vectors by providing
  17830. * a Vector4 with 1 or 0 in the w component respectively. Returns the updated vector.
  17831. *
  17832. * @param {number} index - The vertex index.
  17833. * @param {Vector3|Vector4} target - The target object that is used to store the method's result.
  17834. * @return {Vector3|Vector4} The updated vertex attribute data.
  17835. */
  17836. applyBoneTransform( index, target ) {
  17837. const skeleton = this.skeleton;
  17838. const geometry = this.geometry;
  17839. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17840. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17841. if ( target.isVector4 ) {
  17842. _baseVector.copy( target );
  17843. target.set( 0, 0, 0, 0 );
  17844. } else {
  17845. _baseVector.set( ...target, 1 );
  17846. target.set( 0, 0, 0 );
  17847. }
  17848. _baseVector.applyMatrix4( this.bindMatrix );
  17849. for ( let i = 0; i < 4; i ++ ) {
  17850. const weight = _skinWeight.getComponent( i );
  17851. if ( weight !== 0 ) {
  17852. const boneIndex = _skinIndex.getComponent( i );
  17853. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17854. target.addScaledVector( _vector4.copy( _baseVector ).applyMatrix4( _matrix4 ), weight );
  17855. }
  17856. }
  17857. if ( target.isVector4 ) {
  17858. // ensure the homogenous coordinate remains unchanged after vector operations
  17859. target.w = _baseVector.w;
  17860. }
  17861. return target.applyMatrix4( this.bindMatrixInverse );
  17862. }
  17863. }
  17864. /**
  17865. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  17866. * the {@link SkinnedMesh}.
  17867. *
  17868. * ```js
  17869. * const root = new THREE.Bone();
  17870. * const child = new THREE.Bone();
  17871. *
  17872. * root.add( child );
  17873. * child.position.y = 5;
  17874. * ```
  17875. *
  17876. * @augments Object3D
  17877. */
  17878. class Bone extends Object3D {
  17879. /**
  17880. * Constructs a new bone.
  17881. */
  17882. constructor() {
  17883. super();
  17884. /**
  17885. * This flag can be used for type testing.
  17886. *
  17887. * @type {boolean}
  17888. * @readonly
  17889. * @default true
  17890. */
  17891. this.isBone = true;
  17892. this.type = 'Bone';
  17893. }
  17894. }
  17895. /**
  17896. * Creates a texture directly from raw buffer data.
  17897. *
  17898. * The interpretation of the data depends on type and format: If the type is
  17899. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  17900. * texel data. If the format is `RGBAFormat`, data needs four values for
  17901. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  17902. *
  17903. * @augments Texture
  17904. */
  17905. class DataTexture extends Texture {
  17906. /**
  17907. * Constructs a new data texture.
  17908. *
  17909. * @param {?TypedArray} [data=null] - The buffer data.
  17910. * @param {number} [width=1] - The width of the texture.
  17911. * @param {number} [height=1] - The height of the texture.
  17912. * @param {number} [format=RGBAFormat] - The texture format.
  17913. * @param {number} [type=UnsignedByteType] - The texture type.
  17914. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  17915. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  17916. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  17917. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  17918. * @param {number} [minFilter=NearestFilter] - The min filter value.
  17919. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  17920. * @param {string} [colorSpace=NoColorSpace] - The color space.
  17921. */
  17922. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  17923. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17924. /**
  17925. * This flag can be used for type testing.
  17926. *
  17927. * @type {boolean}
  17928. * @readonly
  17929. * @default true
  17930. */
  17931. this.isDataTexture = true;
  17932. /**
  17933. * The image definition of a data texture.
  17934. *
  17935. * @type {{data:TypedArray,width:number,height:number}}
  17936. */
  17937. this.image = { data: data, width: width, height: height };
  17938. /**
  17939. * Whether to generate mipmaps (if possible) for a texture.
  17940. *
  17941. * Overwritten and set to `false` by default.
  17942. *
  17943. * @type {boolean}
  17944. * @default false
  17945. */
  17946. this.generateMipmaps = false;
  17947. /**
  17948. * If set to `true`, the texture is flipped along the vertical axis when
  17949. * uploaded to the GPU.
  17950. *
  17951. * Overwritten and set to `false` by default.
  17952. *
  17953. * @type {boolean}
  17954. * @default false
  17955. */
  17956. this.flipY = false;
  17957. /**
  17958. * Specifies the alignment requirements for the start of each pixel row in memory.
  17959. *
  17960. * Overwritten and set to `1` by default.
  17961. *
  17962. * @type {boolean}
  17963. * @default 1
  17964. */
  17965. this.unpackAlignment = 1;
  17966. }
  17967. }
  17968. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17969. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17970. /**
  17971. * Class for representing the armatures in `three.js`. The skeleton
  17972. * is defined by a hierarchy of bones.
  17973. *
  17974. * ```js
  17975. * const bones = [];
  17976. *
  17977. * const shoulder = new THREE.Bone();
  17978. * const elbow = new THREE.Bone();
  17979. * const hand = new THREE.Bone();
  17980. *
  17981. * shoulder.add( elbow );
  17982. * elbow.add( hand );
  17983. *
  17984. * bones.push( shoulder , elbow, hand);
  17985. *
  17986. * shoulder.position.y = -5;
  17987. * elbow.position.y = 0;
  17988. * hand.position.y = 5;
  17989. *
  17990. * const armSkeleton = new THREE.Skeleton( bones );
  17991. * ```
  17992. */
  17993. class Skeleton {
  17994. /**
  17995. * Constructs a new skeleton.
  17996. *
  17997. * @param {Array<Bone>} [bones] - An array of bones.
  17998. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  17999. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18000. */
  18001. constructor( bones = [], boneInverses = [] ) {
  18002. this.uuid = generateUUID();
  18003. /**
  18004. * An array of bones defining the skeleton.
  18005. *
  18006. * @type {Array<Bone>}
  18007. */
  18008. this.bones = bones.slice( 0 );
  18009. /**
  18010. * An array of bone inverse matrices.
  18011. *
  18012. * @type {Array<Matrix4>}
  18013. */
  18014. this.boneInverses = boneInverses;
  18015. /**
  18016. * An array buffer holding the bone data.
  18017. * Input data for {@link Skeleton#boneTexture}.
  18018. *
  18019. * @type {?Float32Array}
  18020. * @default null
  18021. */
  18022. this.boneMatrices = null;
  18023. /**
  18024. * A texture holding the bone data for use
  18025. * in the vertex shader.
  18026. *
  18027. * @type {?DataTexture}
  18028. * @default null
  18029. */
  18030. this.boneTexture = null;
  18031. this.init();
  18032. }
  18033. /**
  18034. * Initializes the skeleton. This method gets automatically called by the constructor
  18035. * but depending on how the skeleton is created it might be necessary to call this method
  18036. * manually.
  18037. */
  18038. init() {
  18039. const bones = this.bones;
  18040. const boneInverses = this.boneInverses;
  18041. this.boneMatrices = new Float32Array( bones.length * 16 );
  18042. // calculate inverse bone matrices if necessary
  18043. if ( boneInverses.length === 0 ) {
  18044. this.calculateInverses();
  18045. } else {
  18046. // handle special case
  18047. if ( bones.length !== boneInverses.length ) {
  18048. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18049. this.boneInverses = [];
  18050. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18051. this.boneInverses.push( new Matrix4() );
  18052. }
  18053. }
  18054. }
  18055. }
  18056. /**
  18057. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18058. * and fills it with new matrices.
  18059. */
  18060. calculateInverses() {
  18061. this.boneInverses.length = 0;
  18062. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18063. const inverse = new Matrix4();
  18064. if ( this.bones[ i ] ) {
  18065. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18066. }
  18067. this.boneInverses.push( inverse );
  18068. }
  18069. }
  18070. /**
  18071. * Resets the skeleton to the base pose.
  18072. */
  18073. pose() {
  18074. // recover the bind-time world matrices
  18075. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18076. const bone = this.bones[ i ];
  18077. if ( bone ) {
  18078. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18079. }
  18080. }
  18081. // compute the local matrices, positions, rotations and scales
  18082. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18083. const bone = this.bones[ i ];
  18084. if ( bone ) {
  18085. if ( bone.parent && bone.parent.isBone ) {
  18086. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18087. bone.matrix.multiply( bone.matrixWorld );
  18088. } else {
  18089. bone.matrix.copy( bone.matrixWorld );
  18090. }
  18091. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18092. }
  18093. }
  18094. }
  18095. /**
  18096. * Resets the skeleton to the base pose.
  18097. */
  18098. update() {
  18099. const bones = this.bones;
  18100. const boneInverses = this.boneInverses;
  18101. const boneMatrices = this.boneMatrices;
  18102. const boneTexture = this.boneTexture;
  18103. // flatten bone matrices to array
  18104. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18105. // compute the offset between the current and the original transform
  18106. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18107. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18108. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18109. }
  18110. if ( boneTexture !== null ) {
  18111. boneTexture.needsUpdate = true;
  18112. }
  18113. }
  18114. /**
  18115. * Returns a new skeleton with copied values from this instance.
  18116. *
  18117. * @return {Skeleton} A clone of this instance.
  18118. */
  18119. clone() {
  18120. return new Skeleton( this.bones, this.boneInverses );
  18121. }
  18122. /**
  18123. * Computes a data texture for passing bone data to the vertex shader.
  18124. *
  18125. * @return {Skeleton} A reference of this instance.
  18126. */
  18127. computeBoneTexture() {
  18128. // layout (1 matrix = 4 pixels)
  18129. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18130. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18131. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18132. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18133. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18134. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18135. size = Math.ceil( size / 4 ) * 4;
  18136. size = Math.max( size, 4 );
  18137. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18138. boneMatrices.set( this.boneMatrices ); // copy current values
  18139. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18140. boneTexture.needsUpdate = true;
  18141. this.boneMatrices = boneMatrices;
  18142. this.boneTexture = boneTexture;
  18143. return this;
  18144. }
  18145. /**
  18146. * Searches through the skeleton's bone array and returns the first with a
  18147. * matching name.
  18148. *
  18149. * @param {string} name - The name of the bone.
  18150. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18151. */
  18152. getBoneByName( name ) {
  18153. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18154. const bone = this.bones[ i ];
  18155. if ( bone.name === name ) {
  18156. return bone;
  18157. }
  18158. }
  18159. return undefined;
  18160. }
  18161. /**
  18162. * Frees the GPU-related resources allocated by this instance. Call this
  18163. * method whenever this instance is no longer used in your app.
  18164. */
  18165. dispose( ) {
  18166. if ( this.boneTexture !== null ) {
  18167. this.boneTexture.dispose();
  18168. this.boneTexture = null;
  18169. }
  18170. }
  18171. /**
  18172. * Setups the skeleton by the given JSON and bones.
  18173. *
  18174. * @param {Object} json - The skeleton as serialized JSON.
  18175. * @param {Object<string, Bone>} bones - An array of bones.
  18176. * @return {Skeleton} A reference of this instance.
  18177. */
  18178. fromJSON( json, bones ) {
  18179. this.uuid = json.uuid;
  18180. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18181. const uuid = json.bones[ i ];
  18182. let bone = bones[ uuid ];
  18183. if ( bone === undefined ) {
  18184. warn( 'Skeleton: No bone found with UUID:', uuid );
  18185. bone = new Bone();
  18186. }
  18187. this.bones.push( bone );
  18188. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18189. }
  18190. this.init();
  18191. return this;
  18192. }
  18193. /**
  18194. * Serializes the skeleton into JSON.
  18195. *
  18196. * @return {Object} A JSON object representing the serialized skeleton.
  18197. * @see {@link ObjectLoader#parse}
  18198. */
  18199. toJSON() {
  18200. const data = {
  18201. metadata: {
  18202. version: 4.7,
  18203. type: 'Skeleton',
  18204. generator: 'Skeleton.toJSON'
  18205. },
  18206. bones: [],
  18207. boneInverses: []
  18208. };
  18209. data.uuid = this.uuid;
  18210. const bones = this.bones;
  18211. const boneInverses = this.boneInverses;
  18212. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18213. const bone = bones[ i ];
  18214. data.bones.push( bone.uuid );
  18215. const boneInverse = boneInverses[ i ];
  18216. data.boneInverses.push( boneInverse.toArray() );
  18217. }
  18218. return data;
  18219. }
  18220. }
  18221. /**
  18222. * An instanced version of a buffer attribute.
  18223. *
  18224. * @augments BufferAttribute
  18225. */
  18226. class InstancedBufferAttribute extends BufferAttribute {
  18227. /**
  18228. * Constructs a new instanced buffer attribute.
  18229. *
  18230. * @param {TypedArray} array - The array holding the attribute data.
  18231. * @param {number} itemSize - The item size.
  18232. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18233. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18234. */
  18235. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18236. super( array, itemSize, normalized );
  18237. /**
  18238. * This flag can be used for type testing.
  18239. *
  18240. * @type {boolean}
  18241. * @readonly
  18242. * @default true
  18243. */
  18244. this.isInstancedBufferAttribute = true;
  18245. /**
  18246. * Defines how often a value of this buffer attribute should be repeated. A
  18247. * value of one means that each value of the instanced attribute is used for
  18248. * a single instance. A value of two means that each value is used for two
  18249. * consecutive instances (and so on).
  18250. *
  18251. * @type {number}
  18252. * @default 1
  18253. */
  18254. this.meshPerAttribute = meshPerAttribute;
  18255. }
  18256. copy( source ) {
  18257. super.copy( source );
  18258. this.meshPerAttribute = source.meshPerAttribute;
  18259. return this;
  18260. }
  18261. toJSON() {
  18262. const data = super.toJSON();
  18263. data.meshPerAttribute = this.meshPerAttribute;
  18264. data.isInstancedBufferAttribute = true;
  18265. return data;
  18266. }
  18267. }
  18268. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18269. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18270. const _instanceIntersects = [];
  18271. const _box3 = /*@__PURE__*/ new Box3();
  18272. const _identity = /*@__PURE__*/ new Matrix4();
  18273. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18274. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18275. /**
  18276. * A special version of a mesh with instanced rendering support. Use
  18277. * this class if you have to render a large number of objects with the same
  18278. * geometry and material(s) but with different world transformations. The usage
  18279. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18280. * improve the overall rendering performance in your application.
  18281. *
  18282. * @augments Mesh
  18283. */
  18284. class InstancedMesh extends Mesh {
  18285. /**
  18286. * Constructs a new instanced mesh.
  18287. *
  18288. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18289. * @param {Material|Array<Material>} [material] - The mesh material.
  18290. * @param {number} count - The number of instances.
  18291. */
  18292. constructor( geometry, material, count ) {
  18293. super( geometry, material );
  18294. /**
  18295. * This flag can be used for type testing.
  18296. *
  18297. * @type {boolean}
  18298. * @readonly
  18299. * @default true
  18300. */
  18301. this.isInstancedMesh = true;
  18302. /**
  18303. * Represents the local transformation of all instances. You have to set its
  18304. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18305. * via {@link InstancedMesh#setMatrixAt}.
  18306. *
  18307. * @type {InstancedBufferAttribute}
  18308. */
  18309. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18310. /**
  18311. * Represents the color of all instances. You have to set its
  18312. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18313. * via {@link InstancedMesh#setColorAt}.
  18314. *
  18315. * @type {?InstancedBufferAttribute}
  18316. * @default null
  18317. */
  18318. this.instanceColor = null;
  18319. /**
  18320. * Represents the morph target weights of all instances. You have to set its
  18321. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18322. * via {@link InstancedMesh#setMorphAt}.
  18323. *
  18324. * @type {?DataTexture}
  18325. * @default null
  18326. */
  18327. this.morphTexture = null;
  18328. /**
  18329. * The number of instances.
  18330. *
  18331. * @type {number}
  18332. */
  18333. this.count = count;
  18334. /**
  18335. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18336. *
  18337. * @type {?Box3}
  18338. * @default null
  18339. */
  18340. this.boundingBox = null;
  18341. /**
  18342. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18343. *
  18344. * @type {?Sphere}
  18345. * @default null
  18346. */
  18347. this.boundingSphere = null;
  18348. for ( let i = 0; i < count; i ++ ) {
  18349. this.setMatrixAt( i, _identity );
  18350. }
  18351. }
  18352. /**
  18353. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18354. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18355. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18356. */
  18357. computeBoundingBox() {
  18358. const geometry = this.geometry;
  18359. const count = this.count;
  18360. if ( this.boundingBox === null ) {
  18361. this.boundingBox = new Box3();
  18362. }
  18363. if ( geometry.boundingBox === null ) {
  18364. geometry.computeBoundingBox();
  18365. }
  18366. this.boundingBox.makeEmpty();
  18367. for ( let i = 0; i < count; i ++ ) {
  18368. this.getMatrixAt( i, _instanceLocalMatrix );
  18369. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18370. this.boundingBox.union( _box3 );
  18371. }
  18372. }
  18373. /**
  18374. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  18375. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  18376. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18377. */
  18378. computeBoundingSphere() {
  18379. const geometry = this.geometry;
  18380. const count = this.count;
  18381. if ( this.boundingSphere === null ) {
  18382. this.boundingSphere = new Sphere();
  18383. }
  18384. if ( geometry.boundingSphere === null ) {
  18385. geometry.computeBoundingSphere();
  18386. }
  18387. this.boundingSphere.makeEmpty();
  18388. for ( let i = 0; i < count; i ++ ) {
  18389. this.getMatrixAt( i, _instanceLocalMatrix );
  18390. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18391. this.boundingSphere.union( _sphere$4 );
  18392. }
  18393. }
  18394. copy( source, recursive ) {
  18395. super.copy( source, recursive );
  18396. this.instanceMatrix.copy( source.instanceMatrix );
  18397. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  18398. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18399. this.count = source.count;
  18400. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18401. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18402. return this;
  18403. }
  18404. /**
  18405. * Gets the color of the defined instance.
  18406. *
  18407. * @param {number} index - The instance index.
  18408. * @param {Color} color - The target object that is used to store the method's result.
  18409. * @return {Color} A reference to the target color.
  18410. */
  18411. getColorAt( index, color ) {
  18412. if ( this.instanceColor === null ) {
  18413. return color.setRGB( 1, 1, 1 );
  18414. } else {
  18415. return color.fromArray( this.instanceColor.array, index * 3 );
  18416. }
  18417. }
  18418. /**
  18419. * Gets the local transformation matrix of the defined instance.
  18420. *
  18421. * @param {number} index - The instance index.
  18422. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  18423. * @return {Matrix4} A reference to the target matrix.
  18424. */
  18425. getMatrixAt( index, matrix ) {
  18426. return matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18427. }
  18428. /**
  18429. * Gets the morph target weights of the defined instance.
  18430. *
  18431. * @param {number} index - The instance index.
  18432. * @param {Mesh} object - The target object that is used to store the method's result.
  18433. */
  18434. getMorphAt( index, object ) {
  18435. const objectInfluences = object.morphTargetInfluences;
  18436. const array = this.morphTexture.source.data.data;
  18437. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  18438. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  18439. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18440. objectInfluences[ i ] = array[ dataIndex + i ];
  18441. }
  18442. }
  18443. raycast( raycaster, intersects ) {
  18444. const matrixWorld = this.matrixWorld;
  18445. const raycastTimes = this.count;
  18446. _mesh$1.geometry = this.geometry;
  18447. _mesh$1.material = this.material;
  18448. if ( _mesh$1.material === undefined ) return;
  18449. // test with bounding sphere first
  18450. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18451. _sphere$4.copy( this.boundingSphere );
  18452. _sphere$4.applyMatrix4( matrixWorld );
  18453. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18454. // now test each instance
  18455. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18456. // calculate the world matrix for each instance
  18457. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18458. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18459. // the mesh represents this single instance
  18460. _mesh$1.matrixWorld = _instanceWorldMatrix;
  18461. _mesh$1.raycast( raycaster, _instanceIntersects );
  18462. // process the result of raycast
  18463. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18464. const intersect = _instanceIntersects[ i ];
  18465. intersect.instanceId = instanceId;
  18466. intersect.object = this;
  18467. intersects.push( intersect );
  18468. }
  18469. _instanceIntersects.length = 0;
  18470. }
  18471. }
  18472. /**
  18473. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  18474. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  18475. *
  18476. * @param {number} index - The instance index.
  18477. * @param {Color} color - The instance color.
  18478. * @return {InstancedMesh} A reference to this instanced mesh.
  18479. */
  18480. setColorAt( index, color ) {
  18481. if ( this.instanceColor === null ) {
  18482. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  18483. }
  18484. color.toArray( this.instanceColor.array, index * 3 );
  18485. return this;
  18486. }
  18487. /**
  18488. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  18489. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices.
  18490. *
  18491. * @param {number} index - The instance index.
  18492. * @param {Matrix4} matrix - The local transformation.
  18493. * @return {InstancedMesh} A reference to this instanced mesh.
  18494. */
  18495. setMatrixAt( index, matrix ) {
  18496. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18497. return this;
  18498. }
  18499. /**
  18500. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  18501. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  18502. *
  18503. * @param {number} index - The instance index.
  18504. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  18505. * of a single instance.
  18506. * @return {InstancedMesh} A reference to this instanced mesh.
  18507. */
  18508. setMorphAt( index, object ) {
  18509. const objectInfluences = object.morphTargetInfluences;
  18510. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  18511. if ( this.morphTexture === null ) {
  18512. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  18513. }
  18514. const array = this.morphTexture.source.data.data;
  18515. let morphInfluencesSum = 0;
  18516. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  18517. morphInfluencesSum += objectInfluences[ i ];
  18518. }
  18519. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  18520. const dataIndex = len * index;
  18521. array[ dataIndex ] = morphBaseInfluence;
  18522. array.set( objectInfluences, dataIndex + 1 );
  18523. return this;
  18524. }
  18525. updateMorphTargets() {
  18526. }
  18527. /**
  18528. * Frees the GPU-related resources allocated by this instance. Call this
  18529. * method whenever this instance is no longer used in your app.
  18530. */
  18531. dispose() {
  18532. this.dispatchEvent( { type: 'dispose' } );
  18533. if ( this.morphTexture !== null ) {
  18534. this.morphTexture.dispose();
  18535. this.morphTexture = null;
  18536. }
  18537. }
  18538. }
  18539. const _vector1 = /*@__PURE__*/ new Vector3();
  18540. const _vector2 = /*@__PURE__*/ new Vector3();
  18541. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  18542. /**
  18543. * A two dimensional surface that extends infinitely in 3D space, represented
  18544. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  18545. * by a unit length normal vector and a constant.
  18546. */
  18547. class Plane {
  18548. /**
  18549. * Constructs a new plane.
  18550. *
  18551. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  18552. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  18553. */
  18554. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  18555. /**
  18556. * This flag can be used for type testing.
  18557. *
  18558. * @type {boolean}
  18559. * @readonly
  18560. * @default true
  18561. */
  18562. this.isPlane = true;
  18563. /**
  18564. * A unit length vector defining the normal of the plane.
  18565. *
  18566. * @type {Vector3}
  18567. */
  18568. this.normal = normal;
  18569. /**
  18570. * The signed distance from the origin to the plane.
  18571. *
  18572. * @type {number}
  18573. * @default 0
  18574. */
  18575. this.constant = constant;
  18576. }
  18577. /**
  18578. * Sets the plane components by copying the given values.
  18579. *
  18580. * @param {Vector3} normal - The normal.
  18581. * @param {number} constant - The constant.
  18582. * @return {Plane} A reference to this plane.
  18583. */
  18584. set( normal, constant ) {
  18585. this.normal.copy( normal );
  18586. this.constant = constant;
  18587. return this;
  18588. }
  18589. /**
  18590. * Sets the plane components by defining `x`, `y`, `z` as the
  18591. * plane normal and `w` as the constant.
  18592. *
  18593. * @param {number} x - The value for the normal's x component.
  18594. * @param {number} y - The value for the normal's y component.
  18595. * @param {number} z - The value for the normal's z component.
  18596. * @param {number} w - The constant value.
  18597. * @return {Plane} A reference to this plane.
  18598. */
  18599. setComponents( x, y, z, w ) {
  18600. this.normal.set( x, y, z );
  18601. this.constant = w;
  18602. return this;
  18603. }
  18604. /**
  18605. * Sets the plane from the given normal and coplanar point (that is a point
  18606. * that lies onto the plane).
  18607. *
  18608. * @param {Vector3} normal - The normal.
  18609. * @param {Vector3} point - A coplanar point.
  18610. * @return {Plane} A reference to this plane.
  18611. */
  18612. setFromNormalAndCoplanarPoint( normal, point ) {
  18613. this.normal.copy( normal );
  18614. this.constant = - point.dot( this.normal );
  18615. return this;
  18616. }
  18617. /**
  18618. * Sets the plane from three coplanar points. The winding order is
  18619. * assumed to be counter-clockwise, and determines the direction of
  18620. * the plane normal.
  18621. *
  18622. * @param {Vector3} a - The first coplanar point.
  18623. * @param {Vector3} b - The second coplanar point.
  18624. * @param {Vector3} c - The third coplanar point.
  18625. * @return {Plane} A reference to this plane.
  18626. */
  18627. setFromCoplanarPoints( a, b, c ) {
  18628. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  18629. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  18630. this.setFromNormalAndCoplanarPoint( normal, a );
  18631. return this;
  18632. }
  18633. /**
  18634. * Copies the values of the given plane to this instance.
  18635. *
  18636. * @param {Plane} plane - The plane to copy.
  18637. * @return {Plane} A reference to this plane.
  18638. */
  18639. copy( plane ) {
  18640. this.normal.copy( plane.normal );
  18641. this.constant = plane.constant;
  18642. return this;
  18643. }
  18644. /**
  18645. * Normalizes the plane normal and adjusts the constant accordingly.
  18646. *
  18647. * @return {Plane} A reference to this plane.
  18648. */
  18649. normalize() {
  18650. // Note: will lead to a divide by zero if the plane is invalid.
  18651. const inverseNormalLength = 1.0 / this.normal.length();
  18652. this.normal.multiplyScalar( inverseNormalLength );
  18653. this.constant *= inverseNormalLength;
  18654. return this;
  18655. }
  18656. /**
  18657. * Negates both the plane normal and the constant.
  18658. *
  18659. * @return {Plane} A reference to this plane.
  18660. */
  18661. negate() {
  18662. this.constant *= -1;
  18663. this.normal.negate();
  18664. return this;
  18665. }
  18666. /**
  18667. * Returns the signed distance from the given point to this plane.
  18668. *
  18669. * @param {Vector3} point - The point to compute the distance for.
  18670. * @return {number} The signed distance.
  18671. */
  18672. distanceToPoint( point ) {
  18673. return this.normal.dot( point ) + this.constant;
  18674. }
  18675. /**
  18676. * Returns the signed distance from the given sphere to this plane.
  18677. *
  18678. * @param {Sphere} sphere - The sphere to compute the distance for.
  18679. * @return {number} The signed distance.
  18680. */
  18681. distanceToSphere( sphere ) {
  18682. return this.distanceToPoint( sphere.center ) - sphere.radius;
  18683. }
  18684. /**
  18685. * Projects a the given point onto the plane.
  18686. *
  18687. * @param {Vector3} point - The point to project.
  18688. * @param {Vector3} target - The target vector that is used to store the method's result.
  18689. * @return {Vector3} The projected point on the plane.
  18690. */
  18691. projectPoint( point, target ) {
  18692. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  18693. }
  18694. /**
  18695. * Returns the intersection point of the passed line and the plane. Returns
  18696. * `null` if the line does not intersect. Returns the line's starting point if
  18697. * the line is coplanar with the plane.
  18698. *
  18699. * @param {Line3} line - The line to compute the intersection for.
  18700. * @param {Vector3} target - The target vector that is used to store the method's result.
  18701. * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment.
  18702. * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected.
  18703. */
  18704. intersectLine( line, target, clampToLine = true ) {
  18705. const direction = line.delta( _vector1 );
  18706. const denominator = this.normal.dot( direction );
  18707. if ( denominator === 0 ) {
  18708. // line is coplanar, return origin
  18709. if ( this.distanceToPoint( line.start ) === 0 ) {
  18710. return target.copy( line.start );
  18711. }
  18712. // Unsure if this is the correct method to handle this case.
  18713. return null;
  18714. }
  18715. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  18716. if ( ( clampToLine === true ) && ( t < 0 || t > 1 ) ) {
  18717. return null;
  18718. }
  18719. return target.copy( line.start ).addScaledVector( direction, t );
  18720. }
  18721. /**
  18722. * Returns `true` if the given line segment intersects with (passes through) the plane.
  18723. *
  18724. * @param {Line3} line - The line to test.
  18725. * @return {boolean} Whether the given line segment intersects with the plane or not.
  18726. */
  18727. intersectsLine( line ) {
  18728. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  18729. const startSign = this.distanceToPoint( line.start );
  18730. const endSign = this.distanceToPoint( line.end );
  18731. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  18732. }
  18733. /**
  18734. * Returns `true` if the given bounding box intersects with the plane.
  18735. *
  18736. * @param {Box3} box - The bounding box to test.
  18737. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  18738. */
  18739. intersectsBox( box ) {
  18740. return box.intersectsPlane( this );
  18741. }
  18742. /**
  18743. * Returns `true` if the given bounding sphere intersects with the plane.
  18744. *
  18745. * @param {Sphere} sphere - The bounding sphere to test.
  18746. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  18747. */
  18748. intersectsSphere( sphere ) {
  18749. return sphere.intersectsPlane( this );
  18750. }
  18751. /**
  18752. * Returns a coplanar vector to the plane, by calculating the
  18753. * projection of the normal at the origin onto the plane.
  18754. *
  18755. * @param {Vector3} target - The target vector that is used to store the method's result.
  18756. * @return {Vector3} The coplanar point.
  18757. */
  18758. coplanarPoint( target ) {
  18759. return target.copy( this.normal ).multiplyScalar( - this.constant );
  18760. }
  18761. /**
  18762. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  18763. *
  18764. * The optional normal matrix can be pre-computed like so:
  18765. * ```js
  18766. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  18767. * ```
  18768. *
  18769. * @param {Matrix4} matrix - The transformation matrix.
  18770. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  18771. * @return {Plane} A reference to this plane.
  18772. */
  18773. applyMatrix4( matrix, optionalNormalMatrix ) {
  18774. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  18775. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  18776. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  18777. this.constant = - referencePoint.dot( normal );
  18778. return this;
  18779. }
  18780. /**
  18781. * Translates the plane by the distance defined by the given offset vector.
  18782. * Note that this only affects the plane constant and will not affect the normal vector.
  18783. *
  18784. * @param {Vector3} offset - The offset vector.
  18785. * @return {Plane} A reference to this plane.
  18786. */
  18787. translate( offset ) {
  18788. this.constant -= offset.dot( this.normal );
  18789. return this;
  18790. }
  18791. /**
  18792. * Returns `true` if this plane is equal with the given one.
  18793. *
  18794. * @param {Plane} plane - The plane to test for equality.
  18795. * @return {boolean} Whether this plane is equal with the given one.
  18796. */
  18797. equals( plane ) {
  18798. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  18799. }
  18800. /**
  18801. * Returns a new plane with copied values from this instance.
  18802. *
  18803. * @return {Plane} A clone of this instance.
  18804. */
  18805. clone() {
  18806. return new this.constructor().copy( this );
  18807. }
  18808. }
  18809. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18810. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  18811. const _vector$6 = /*@__PURE__*/ new Vector3();
  18812. /**
  18813. * Frustums are used to determine what is inside the camera's field of view.
  18814. * They help speed up the rendering process - objects which lie outside a camera's
  18815. * frustum can safely be excluded from rendering.
  18816. *
  18817. * This class is mainly intended for use internally by a renderer.
  18818. */
  18819. class Frustum {
  18820. /**
  18821. * Constructs a new frustum.
  18822. *
  18823. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18824. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18825. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18826. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18827. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18828. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18829. */
  18830. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  18831. /**
  18832. * This array holds the planes that enclose the frustum.
  18833. *
  18834. * @type {Array<Plane>}
  18835. */
  18836. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  18837. }
  18838. /**
  18839. * Sets the frustum planes by copying the given planes.
  18840. *
  18841. * @param {Plane} [p0] - The first plane that encloses the frustum.
  18842. * @param {Plane} [p1] - The second plane that encloses the frustum.
  18843. * @param {Plane} [p2] - The third plane that encloses the frustum.
  18844. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  18845. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  18846. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  18847. * @return {Frustum} A reference to this frustum.
  18848. */
  18849. set( p0, p1, p2, p3, p4, p5 ) {
  18850. const planes = this.planes;
  18851. planes[ 0 ].copy( p0 );
  18852. planes[ 1 ].copy( p1 );
  18853. planes[ 2 ].copy( p2 );
  18854. planes[ 3 ].copy( p3 );
  18855. planes[ 4 ].copy( p4 );
  18856. planes[ 5 ].copy( p5 );
  18857. return this;
  18858. }
  18859. /**
  18860. * Copies the values of the given frustum to this instance.
  18861. *
  18862. * @param {Frustum} frustum - The frustum to copy.
  18863. * @return {Frustum} A reference to this frustum.
  18864. */
  18865. copy( frustum ) {
  18866. const planes = this.planes;
  18867. for ( let i = 0; i < 6; i ++ ) {
  18868. planes[ i ].copy( frustum.planes[ i ] );
  18869. }
  18870. return this;
  18871. }
  18872. /**
  18873. * Sets the frustum planes from the given projection matrix.
  18874. *
  18875. * @param {Matrix4} m - The projection matrix.
  18876. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  18877. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  18878. * @return {Frustum} A reference to this frustum.
  18879. */
  18880. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  18881. const planes = this.planes;
  18882. const me = m.elements;
  18883. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  18884. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  18885. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  18886. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  18887. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  18888. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  18889. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  18890. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  18891. if ( reversedDepth ) {
  18892. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  18893. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  18894. } else {
  18895. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  18896. if ( coordinateSystem === WebGLCoordinateSystem ) {
  18897. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  18898. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  18899. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  18900. } else {
  18901. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  18902. }
  18903. }
  18904. return this;
  18905. }
  18906. /**
  18907. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  18908. *
  18909. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  18910. *
  18911. * @param {Object3D} object - The 3D object to test.
  18912. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  18913. */
  18914. intersectsObject( object ) {
  18915. if ( object.boundingSphere !== undefined ) {
  18916. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  18917. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  18918. } else {
  18919. const geometry = object.geometry;
  18920. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18921. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  18922. }
  18923. return this.intersectsSphere( _sphere$3 );
  18924. }
  18925. /**
  18926. * Returns `true` if the given sprite is intersecting this frustum.
  18927. *
  18928. * @param {Sprite} sprite - The sprite to test.
  18929. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  18930. */
  18931. intersectsSprite( sprite ) {
  18932. _sphere$3.center.set( 0, 0, 0 );
  18933. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  18934. _sphere$3.radius = 0.7071067811865476 + offset;
  18935. _sphere$3.applyMatrix4( sprite.matrixWorld );
  18936. return this.intersectsSphere( _sphere$3 );
  18937. }
  18938. /**
  18939. * Returns `true` if the given bounding sphere is intersecting this frustum.
  18940. *
  18941. * @param {Sphere} sphere - The bounding sphere to test.
  18942. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  18943. */
  18944. intersectsSphere( sphere ) {
  18945. const planes = this.planes;
  18946. const center = sphere.center;
  18947. const negRadius = - sphere.radius;
  18948. for ( let i = 0; i < 6; i ++ ) {
  18949. const distance = planes[ i ].distanceToPoint( center );
  18950. if ( distance < negRadius ) {
  18951. return false;
  18952. }
  18953. }
  18954. return true;
  18955. }
  18956. /**
  18957. * Returns `true` if the given bounding box is intersecting this frustum.
  18958. *
  18959. * @param {Box3} box - The bounding box to test.
  18960. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  18961. */
  18962. intersectsBox( box ) {
  18963. const planes = this.planes;
  18964. for ( let i = 0; i < 6; i ++ ) {
  18965. const plane = planes[ i ];
  18966. // corner at max distance
  18967. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  18968. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  18969. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  18970. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  18971. return false;
  18972. }
  18973. }
  18974. return true;
  18975. }
  18976. /**
  18977. * Returns `true` if the given point lies within the frustum.
  18978. *
  18979. * @param {Vector3} point - The point to test.
  18980. * @return {boolean} Whether the point lies within this frustum or not.
  18981. */
  18982. containsPoint( point ) {
  18983. const planes = this.planes;
  18984. for ( let i = 0; i < 6; i ++ ) {
  18985. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  18986. return false;
  18987. }
  18988. }
  18989. return true;
  18990. }
  18991. /**
  18992. * Returns a new frustum with copied values from this instance.
  18993. *
  18994. * @return {Frustum} A clone of this instance.
  18995. */
  18996. clone() {
  18997. return new this.constructor().copy( this );
  18998. }
  18999. }
  19000. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  19001. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19002. /**
  19003. * FrustumArray is used to determine if an object is visible in at least one camera
  19004. * from an array of cameras. This is particularly useful for multi-view renderers.
  19005. */
  19006. class FrustumArray {
  19007. /**
  19008. * Constructs a new frustum array.
  19009. *
  19010. */
  19011. constructor() {
  19012. /**
  19013. * The coordinate system to use.
  19014. *
  19015. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19016. * @default WebGLCoordinateSystem
  19017. */
  19018. this.coordinateSystem = WebGLCoordinateSystem;
  19019. }
  19020. /**
  19021. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19022. * from the camera array.
  19023. *
  19024. * @param {Object3D} object - The 3D object to test.
  19025. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19026. * @return {boolean} Whether the 3D object is visible in any camera.
  19027. */
  19028. intersectsObject( object, cameraArray ) {
  19029. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19030. return false;
  19031. }
  19032. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19033. const camera = cameraArray.cameras[ i ];
  19034. _projScreenMatrix$1.multiplyMatrices(
  19035. camera.projectionMatrix,
  19036. camera.matrixWorldInverse
  19037. );
  19038. _frustum$1.setFromProjectionMatrix(
  19039. _projScreenMatrix$1,
  19040. camera.coordinateSystem,
  19041. camera.reversedDepth
  19042. );
  19043. if ( _frustum$1.intersectsObject( object ) ) {
  19044. return true; // Object is visible in at least one camera
  19045. }
  19046. }
  19047. return false; // Not visible in any camera
  19048. }
  19049. /**
  19050. * Returns `true` if the given sprite is intersecting any frustum
  19051. * from the camera array.
  19052. *
  19053. * @param {Sprite} sprite - The sprite to test.
  19054. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19055. * @return {boolean} Whether the sprite is visible in any camera.
  19056. */
  19057. intersectsSprite( sprite, cameraArray ) {
  19058. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19059. return false;
  19060. }
  19061. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19062. const camera = cameraArray.cameras[ i ];
  19063. _projScreenMatrix$1.multiplyMatrices(
  19064. camera.projectionMatrix,
  19065. camera.matrixWorldInverse
  19066. );
  19067. _frustum$1.setFromProjectionMatrix(
  19068. _projScreenMatrix$1,
  19069. camera.coordinateSystem,
  19070. camera.reversedDepth
  19071. );
  19072. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19073. return true; // Sprite is visible in at least one camera
  19074. }
  19075. }
  19076. return false; // Not visible in any camera
  19077. }
  19078. /**
  19079. * Returns `true` if the given bounding sphere is intersecting any frustum
  19080. * from the camera array.
  19081. *
  19082. * @param {Sphere} sphere - The bounding sphere to test.
  19083. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19084. * @return {boolean} Whether the sphere is visible in any camera.
  19085. */
  19086. intersectsSphere( sphere, cameraArray ) {
  19087. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19088. return false;
  19089. }
  19090. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19091. const camera = cameraArray.cameras[ i ];
  19092. _projScreenMatrix$1.multiplyMatrices(
  19093. camera.projectionMatrix,
  19094. camera.matrixWorldInverse
  19095. );
  19096. _frustum$1.setFromProjectionMatrix(
  19097. _projScreenMatrix$1,
  19098. camera.coordinateSystem,
  19099. camera.reversedDepth
  19100. );
  19101. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19102. return true; // Sphere is visible in at least one camera
  19103. }
  19104. }
  19105. return false; // Not visible in any camera
  19106. }
  19107. /**
  19108. * Returns `true` if the given bounding box is intersecting any frustum
  19109. * from the camera array.
  19110. *
  19111. * @param {Box3} box - The bounding box to test.
  19112. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19113. * @return {boolean} Whether the box is visible in any camera.
  19114. */
  19115. intersectsBox( box, cameraArray ) {
  19116. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19117. return false;
  19118. }
  19119. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19120. const camera = cameraArray.cameras[ i ];
  19121. _projScreenMatrix$1.multiplyMatrices(
  19122. camera.projectionMatrix,
  19123. camera.matrixWorldInverse
  19124. );
  19125. _frustum$1.setFromProjectionMatrix(
  19126. _projScreenMatrix$1,
  19127. camera.coordinateSystem,
  19128. camera.reversedDepth
  19129. );
  19130. if ( _frustum$1.intersectsBox( box ) ) {
  19131. return true; // Box is visible in at least one camera
  19132. }
  19133. }
  19134. return false; // Not visible in any camera
  19135. }
  19136. /**
  19137. * Returns `true` if the given point lies within any frustum
  19138. * from the camera array.
  19139. *
  19140. * @param {Vector3} point - The point to test.
  19141. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19142. * @return {boolean} Whether the point is visible in any camera.
  19143. */
  19144. containsPoint( point, cameraArray ) {
  19145. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19146. return false;
  19147. }
  19148. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19149. const camera = cameraArray.cameras[ i ];
  19150. _projScreenMatrix$1.multiplyMatrices(
  19151. camera.projectionMatrix,
  19152. camera.matrixWorldInverse
  19153. );
  19154. _frustum$1.setFromProjectionMatrix(
  19155. _projScreenMatrix$1,
  19156. camera.coordinateSystem,
  19157. camera.reversedDepth
  19158. );
  19159. if ( _frustum$1.containsPoint( point ) ) {
  19160. return true; // Point is visible in at least one camera
  19161. }
  19162. }
  19163. return false; // Not visible in any camera
  19164. }
  19165. /**
  19166. * Returns a new frustum array with copied values from this instance.
  19167. *
  19168. * @return {FrustumArray} A clone of this instance.
  19169. */
  19170. clone() {
  19171. return new FrustumArray();
  19172. }
  19173. }
  19174. function ascIdSort( a, b ) {
  19175. return a - b;
  19176. }
  19177. function sortOpaque( a, b ) {
  19178. return a.z - b.z;
  19179. }
  19180. function sortTransparent( a, b ) {
  19181. return b.z - a.z;
  19182. }
  19183. class MultiDrawRenderList {
  19184. constructor() {
  19185. this.index = 0;
  19186. this.pool = [];
  19187. this.list = [];
  19188. }
  19189. push( start, count, z, index ) {
  19190. const pool = this.pool;
  19191. const list = this.list;
  19192. if ( this.index >= pool.length ) {
  19193. pool.push( {
  19194. start: -1,
  19195. count: -1,
  19196. z: -1,
  19197. index: -1,
  19198. } );
  19199. }
  19200. const item = pool[ this.index ];
  19201. list.push( item );
  19202. this.index ++;
  19203. item.start = start;
  19204. item.count = count;
  19205. item.z = z;
  19206. item.index = index;
  19207. }
  19208. reset() {
  19209. this.list.length = 0;
  19210. this.index = 0;
  19211. }
  19212. }
  19213. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19214. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19215. const _frustum = /*@__PURE__*/ new Frustum();
  19216. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19217. const _box$1 = /*@__PURE__*/ new Box3();
  19218. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19219. const _vector$5 = /*@__PURE__*/ new Vector3();
  19220. const _forward$1 = /*@__PURE__*/ new Vector3();
  19221. const _temp = /*@__PURE__*/ new Vector3();
  19222. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19223. const _mesh = /*@__PURE__*/ new Mesh();
  19224. const _batchIntersects = [];
  19225. // copies data from attribute "src" into "target" starting at "targetOffset"
  19226. function copyAttributeData( src, target, targetOffset = 0 ) {
  19227. const itemSize = target.itemSize;
  19228. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19229. // use the component getters and setters if the array data cannot
  19230. // be copied directly
  19231. const vertexCount = src.count;
  19232. for ( let i = 0; i < vertexCount; i ++ ) {
  19233. for ( let c = 0; c < itemSize; c ++ ) {
  19234. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19235. }
  19236. }
  19237. } else {
  19238. // faster copy approach using typed array set function
  19239. target.array.set( src.array, targetOffset * itemSize );
  19240. }
  19241. target.needsUpdate = true;
  19242. }
  19243. // safely copies array contents to a potentially smaller array
  19244. function copyArrayContents( src, target ) {
  19245. if ( src.constructor !== target.constructor ) {
  19246. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19247. const len = Math.min( src.length, target.length );
  19248. for ( let i = 0; i < len; i ++ ) {
  19249. target[ i ] = src[ i ];
  19250. }
  19251. } else {
  19252. // if the arrays use the same data layout we can use a fast block copy
  19253. const len = Math.min( src.length, target.length );
  19254. target.set( new src.constructor( src.buffer, 0, len ) );
  19255. }
  19256. }
  19257. /**
  19258. * A special version of a mesh with multi draw batch rendering support. Use
  19259. * this class if you have to render a large number of objects with the same
  19260. * material but with different geometries or world transformations. The usage of
  19261. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19262. * rendering performance in your application.
  19263. *
  19264. * ```js
  19265. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19266. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19267. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19268. *
  19269. * // initialize and add geometries into the batched mesh
  19270. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19271. * const boxGeometryId = batchedMesh.addGeometry( box );
  19272. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19273. *
  19274. * // create instances of those geometries
  19275. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19276. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19277. *
  19278. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19279. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19280. *
  19281. * // position the geometries
  19282. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19283. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19284. *
  19285. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19286. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19287. *
  19288. * scene.add( batchedMesh );
  19289. * ```
  19290. *
  19291. * @augments Mesh
  19292. */
  19293. class BatchedMesh extends Mesh {
  19294. /**
  19295. * Constructs a new batched mesh.
  19296. *
  19297. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19298. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19299. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19300. * @param {Material|Array<Material>} [material] - The mesh material.
  19301. */
  19302. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19303. super( new BufferGeometry(), material );
  19304. /**
  19305. * This flag can be used for type testing.
  19306. *
  19307. * @type {boolean}
  19308. * @readonly
  19309. * @default true
  19310. */
  19311. this.isBatchedMesh = true;
  19312. /**
  19313. * When set ot `true`, the individual objects of a batch are frustum culled.
  19314. *
  19315. * @type {boolean}
  19316. * @default true
  19317. */
  19318. this.perObjectFrustumCulled = true;
  19319. /**
  19320. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19321. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19322. * rendered front to back.
  19323. *
  19324. * @type {boolean}
  19325. * @default true
  19326. */
  19327. this.sortObjects = true;
  19328. /**
  19329. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19330. *
  19331. * @type {?Box3}
  19332. * @default null
  19333. */
  19334. this.boundingBox = null;
  19335. /**
  19336. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19337. *
  19338. * @type {?Sphere}
  19339. * @default null
  19340. */
  19341. this.boundingSphere = null;
  19342. /**
  19343. * Takes a sort a function that is run before render. The function takes a list of instances to
  19344. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19345. * sort with.
  19346. *
  19347. * @type {?Function}
  19348. * @default null
  19349. */
  19350. this.customSort = null;
  19351. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19352. this._instanceInfo = [];
  19353. this._geometryInfo = [];
  19354. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19355. this._availableInstanceIds = [];
  19356. this._availableGeometryIds = [];
  19357. // used to track where the next point is that geometry should be inserted
  19358. this._nextIndexStart = 0;
  19359. this._nextVertexStart = 0;
  19360. this._geometryCount = 0;
  19361. // flags
  19362. this._visibilityChanged = true;
  19363. this._geometryInitialized = false;
  19364. // cached user options
  19365. this._maxInstanceCount = maxInstanceCount;
  19366. this._maxVertexCount = maxVertexCount;
  19367. this._maxIndexCount = maxIndexCount;
  19368. // buffers for multi draw
  19369. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19370. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19371. this._multiDrawCount = 0;
  19372. // Local matrix per geometry by using data texture
  19373. this._matricesTexture = null;
  19374. this._indirectTexture = null;
  19375. this._colorsTexture = null;
  19376. this._initMatricesTexture();
  19377. this._initIndirectTexture();
  19378. }
  19379. /**
  19380. * The maximum number of individual instances that can be stored in the batch.
  19381. *
  19382. * @type {number}
  19383. * @readonly
  19384. */
  19385. get maxInstanceCount() {
  19386. return this._maxInstanceCount;
  19387. }
  19388. /**
  19389. * The instance count.
  19390. *
  19391. * @type {number}
  19392. * @readonly
  19393. */
  19394. get instanceCount() {
  19395. return this._instanceInfo.length - this._availableInstanceIds.length;
  19396. }
  19397. /**
  19398. * The number of unused vertices.
  19399. *
  19400. * @type {number}
  19401. * @readonly
  19402. */
  19403. get unusedVertexCount() {
  19404. return this._maxVertexCount - this._nextVertexStart;
  19405. }
  19406. /**
  19407. * The number of unused indices.
  19408. *
  19409. * @type {number}
  19410. * @readonly
  19411. */
  19412. get unusedIndexCount() {
  19413. return this._maxIndexCount - this._nextIndexStart;
  19414. }
  19415. _initMatricesTexture() {
  19416. // layout (1 matrix = 4 pixels)
  19417. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19418. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19419. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19420. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19421. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19422. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  19423. size = Math.ceil( size / 4 ) * 4;
  19424. size = Math.max( size, 4 );
  19425. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19426. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19427. this._matricesTexture = matricesTexture;
  19428. }
  19429. _initIndirectTexture() {
  19430. let size = Math.sqrt( this._maxInstanceCount );
  19431. size = Math.ceil( size );
  19432. const indirectArray = new Uint32Array( size * size );
  19433. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  19434. this._indirectTexture = indirectTexture;
  19435. }
  19436. _initColorsTexture() {
  19437. let size = Math.sqrt( this._maxInstanceCount );
  19438. size = Math.ceil( size );
  19439. // 4 floats per RGBA pixel initialized to white
  19440. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19441. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19442. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19443. this._colorsTexture = colorsTexture;
  19444. }
  19445. _initializeGeometry( reference ) {
  19446. const geometry = this.geometry;
  19447. const maxVertexCount = this._maxVertexCount;
  19448. const maxIndexCount = this._maxIndexCount;
  19449. if ( this._geometryInitialized === false ) {
  19450. for ( const attributeName in reference.attributes ) {
  19451. const srcAttribute = reference.getAttribute( attributeName );
  19452. const { array, itemSize, normalized } = srcAttribute;
  19453. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19454. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19455. geometry.setAttribute( attributeName, dstAttribute );
  19456. }
  19457. if ( reference.getIndex() !== null ) {
  19458. // Reserve last u16 index for primitive restart.
  19459. const indexArray = maxVertexCount > 65535
  19460. ? new Uint32Array( maxIndexCount )
  19461. : new Uint16Array( maxIndexCount );
  19462. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19463. }
  19464. this._geometryInitialized = true;
  19465. }
  19466. }
  19467. // Make sure the geometry is compatible with the existing combined geometry attributes
  19468. _validateGeometry( geometry ) {
  19469. // check to ensure the geometries are using consistent attributes and indices
  19470. const batchGeometry = this.geometry;
  19471. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19472. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  19473. }
  19474. for ( const attributeName in batchGeometry.attributes ) {
  19475. if ( ! geometry.hasAttribute( attributeName ) ) {
  19476. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19477. }
  19478. const srcAttribute = geometry.getAttribute( attributeName );
  19479. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19480. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19481. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19482. }
  19483. }
  19484. }
  19485. /**
  19486. * Validates the instance defined by the given ID.
  19487. *
  19488. * @param {number} instanceId - The instance to validate.
  19489. */
  19490. validateInstanceId( instanceId ) {
  19491. const instanceInfo = this._instanceInfo;
  19492. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  19493. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  19494. }
  19495. }
  19496. /**
  19497. * Validates the geometry defined by the given ID.
  19498. *
  19499. * @param {number} geometryId - The geometry to validate.
  19500. */
  19501. validateGeometryId( geometryId ) {
  19502. const geometryInfoList = this._geometryInfo;
  19503. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19504. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  19505. }
  19506. }
  19507. /**
  19508. * Takes a sort a function that is run before render. The function takes a list of instances to
  19509. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  19510. *
  19511. * @param {Function} func - The custom sort function.
  19512. * @return {BatchedMesh} A reference to this batched mesh.
  19513. */
  19514. setCustomSort( func ) {
  19515. this.customSort = func;
  19516. return this;
  19517. }
  19518. /**
  19519. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  19520. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  19521. * otherwise they are `null`.
  19522. */
  19523. computeBoundingBox() {
  19524. if ( this.boundingBox === null ) {
  19525. this.boundingBox = new Box3();
  19526. }
  19527. const boundingBox = this.boundingBox;
  19528. const instanceInfo = this._instanceInfo;
  19529. boundingBox.makeEmpty();
  19530. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19531. if ( instanceInfo[ i ].active === false ) continue;
  19532. const geometryId = instanceInfo[ i ].geometryIndex;
  19533. this.getMatrixAt( i, _matrix$1 );
  19534. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  19535. boundingBox.union( _box$1 );
  19536. }
  19537. }
  19538. /**
  19539. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  19540. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  19541. * otherwise they are `null`.
  19542. */
  19543. computeBoundingSphere() {
  19544. if ( this.boundingSphere === null ) {
  19545. this.boundingSphere = new Sphere();
  19546. }
  19547. const boundingSphere = this.boundingSphere;
  19548. const instanceInfo = this._instanceInfo;
  19549. boundingSphere.makeEmpty();
  19550. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19551. if ( instanceInfo[ i ].active === false ) continue;
  19552. const geometryId = instanceInfo[ i ].geometryIndex;
  19553. this.getMatrixAt( i, _matrix$1 );
  19554. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  19555. boundingSphere.union( _sphere$2 );
  19556. }
  19557. }
  19558. /**
  19559. * Adds a new instance to the batch using the geometry of the given ID and returns
  19560. * a new id referring to the new instance to be used by other functions.
  19561. *
  19562. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  19563. * @return {number} The instance ID.
  19564. */
  19565. addInstance( geometryId ) {
  19566. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  19567. // ensure we're not over geometry
  19568. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  19569. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  19570. }
  19571. const instanceInfo = {
  19572. visible: true,
  19573. active: true,
  19574. geometryIndex: geometryId,
  19575. };
  19576. let drawId = null;
  19577. // Prioritize using previously freed instance ids
  19578. if ( this._availableInstanceIds.length > 0 ) {
  19579. this._availableInstanceIds.sort( ascIdSort );
  19580. drawId = this._availableInstanceIds.shift();
  19581. this._instanceInfo[ drawId ] = instanceInfo;
  19582. } else {
  19583. drawId = this._instanceInfo.length;
  19584. this._instanceInfo.push( instanceInfo );
  19585. }
  19586. const matricesTexture = this._matricesTexture;
  19587. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  19588. matricesTexture.needsUpdate = true;
  19589. const colorsTexture = this._colorsTexture;
  19590. if ( colorsTexture ) {
  19591. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  19592. colorsTexture.needsUpdate = true;
  19593. }
  19594. this._visibilityChanged = true;
  19595. return drawId;
  19596. }
  19597. /**
  19598. * Adds the given geometry to the batch and returns the associated
  19599. * geometry id referring to it to be used in other functions.
  19600. *
  19601. * @param {BufferGeometry} geometry - The geometry to add.
  19602. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  19603. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  19604. * to set a new geometry at this index at a later time that is larger than the original geometry.
  19605. * Defaults to the length of the given geometry vertex buffer.
  19606. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  19607. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  19608. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  19609. * the length of the given geometry index buffer.
  19610. * @return {number} The geometry ID.
  19611. */
  19612. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  19613. this._initializeGeometry( geometry );
  19614. this._validateGeometry( geometry );
  19615. const geometryInfo = {
  19616. // geometry information
  19617. vertexStart: -1,
  19618. vertexCount: -1,
  19619. reservedVertexCount: -1,
  19620. indexStart: -1,
  19621. indexCount: -1,
  19622. reservedIndexCount: -1,
  19623. // draw range information
  19624. start: -1,
  19625. count: -1,
  19626. // state
  19627. boundingBox: null,
  19628. boundingSphere: null,
  19629. active: true,
  19630. };
  19631. const geometryInfoList = this._geometryInfo;
  19632. geometryInfo.vertexStart = this._nextVertexStart;
  19633. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  19634. const index = geometry.getIndex();
  19635. const hasIndex = index !== null;
  19636. if ( hasIndex ) {
  19637. geometryInfo.indexStart = this._nextIndexStart;
  19638. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  19639. }
  19640. if (
  19641. geometryInfo.indexStart !== -1 &&
  19642. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  19643. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  19644. ) {
  19645. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19646. }
  19647. // update id
  19648. let geometryId;
  19649. if ( this._availableGeometryIds.length > 0 ) {
  19650. this._availableGeometryIds.sort( ascIdSort );
  19651. geometryId = this._availableGeometryIds.shift();
  19652. geometryInfoList[ geometryId ] = geometryInfo;
  19653. } else {
  19654. geometryId = this._geometryCount;
  19655. this._geometryCount ++;
  19656. geometryInfoList.push( geometryInfo );
  19657. }
  19658. // update the geometry
  19659. this.setGeometryAt( geometryId, geometry );
  19660. // increment the next geometry position
  19661. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  19662. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  19663. return geometryId;
  19664. }
  19665. /**
  19666. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  19667. * is not enough space reserved for geometry. Calling this will change all instances that are
  19668. * rendering that geometry.
  19669. *
  19670. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  19671. * @param {BufferGeometry} geometry - The new geometry.
  19672. * @return {number} The geometry ID.
  19673. */
  19674. setGeometryAt( geometryId, geometry ) {
  19675. if ( geometryId >= this._geometryCount ) {
  19676. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  19677. }
  19678. this._validateGeometry( geometry );
  19679. const batchGeometry = this.geometry;
  19680. const hasIndex = batchGeometry.getIndex() !== null;
  19681. const dstIndex = batchGeometry.getIndex();
  19682. const srcIndex = geometry.getIndex();
  19683. const geometryInfo = this._geometryInfo[ geometryId ];
  19684. if (
  19685. hasIndex &&
  19686. srcIndex.count > geometryInfo.reservedIndexCount ||
  19687. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  19688. ) {
  19689. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  19690. }
  19691. // copy geometry buffer data over
  19692. const vertexStart = geometryInfo.vertexStart;
  19693. const reservedVertexCount = geometryInfo.reservedVertexCount;
  19694. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  19695. for ( const attributeName in batchGeometry.attributes ) {
  19696. // copy attribute data
  19697. const srcAttribute = geometry.getAttribute( attributeName );
  19698. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19699. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19700. // fill the rest in with zeroes
  19701. const itemSize = srcAttribute.itemSize;
  19702. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  19703. const index = vertexStart + i;
  19704. for ( let c = 0; c < itemSize; c ++ ) {
  19705. dstAttribute.setComponent( index, c, 0 );
  19706. }
  19707. }
  19708. dstAttribute.needsUpdate = true;
  19709. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  19710. }
  19711. // copy index
  19712. if ( hasIndex ) {
  19713. const indexStart = geometryInfo.indexStart;
  19714. const reservedIndexCount = geometryInfo.reservedIndexCount;
  19715. geometryInfo.indexCount = geometry.getIndex().count;
  19716. // copy index data over
  19717. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19718. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19719. }
  19720. // fill the rest in with zeroes
  19721. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  19722. dstIndex.setX( indexStart + i, vertexStart );
  19723. }
  19724. dstIndex.needsUpdate = true;
  19725. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  19726. }
  19727. // update the draw range
  19728. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19729. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  19730. // store the bounding boxes
  19731. geometryInfo.boundingBox = null;
  19732. if ( geometry.boundingBox !== null ) {
  19733. geometryInfo.boundingBox = geometry.boundingBox.clone();
  19734. }
  19735. geometryInfo.boundingSphere = null;
  19736. if ( geometry.boundingSphere !== null ) {
  19737. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  19738. }
  19739. this._visibilityChanged = true;
  19740. return geometryId;
  19741. }
  19742. /**
  19743. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  19744. * this geometry will also be removed as a side effect.
  19745. *
  19746. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  19747. * @return {BatchedMesh} A reference to this batched mesh.
  19748. */
  19749. deleteGeometry( geometryId ) {
  19750. const geometryInfoList = this._geometryInfo;
  19751. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  19752. return this;
  19753. }
  19754. // delete any instances associated with this geometry
  19755. const instanceInfo = this._instanceInfo;
  19756. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  19757. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  19758. this.deleteInstance( i );
  19759. }
  19760. }
  19761. geometryInfoList[ geometryId ].active = false;
  19762. this._availableGeometryIds.push( geometryId );
  19763. this._visibilityChanged = true;
  19764. return this;
  19765. }
  19766. /**
  19767. * Deletes an existing instance from the batch using the given ID.
  19768. *
  19769. * @param {number} instanceId - The ID of the instance to remove from the batch.
  19770. * @return {BatchedMesh} A reference to this batched mesh.
  19771. */
  19772. deleteInstance( instanceId ) {
  19773. this.validateInstanceId( instanceId );
  19774. this._instanceInfo[ instanceId ].active = false;
  19775. this._availableInstanceIds.push( instanceId );
  19776. this._visibilityChanged = true;
  19777. return this;
  19778. }
  19779. /**
  19780. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  19781. * previously deleted geometry, freeing up space to add new geometry.
  19782. *
  19783. * @return {BatchedMesh} A reference to this batched mesh.
  19784. */
  19785. optimize() {
  19786. // track the next indices to copy data to
  19787. let nextVertexStart = 0;
  19788. let nextIndexStart = 0;
  19789. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  19790. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  19791. const geometryInfoList = this._geometryInfo;
  19792. const indices = geometryInfoList
  19793. .map( ( e, i ) => i )
  19794. .sort( ( a, b ) => {
  19795. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  19796. } );
  19797. const geometry = this.geometry;
  19798. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  19799. // if a geometry range is inactive then don't copy anything
  19800. const index = indices[ i ];
  19801. const geometryInfo = geometryInfoList[ index ];
  19802. if ( geometryInfo.active === false ) {
  19803. continue;
  19804. }
  19805. // if a geometry contains an index buffer then shift it, as well
  19806. if ( geometry.index !== null ) {
  19807. if ( geometryInfo.indexStart !== nextIndexStart ) {
  19808. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  19809. const index = geometry.index;
  19810. const array = index.array;
  19811. // shift the index pointers based on how the vertex data will shift
  19812. // adjusting the index must happen first so the original vertex start value is available
  19813. const elementDelta = nextVertexStart - vertexStart;
  19814. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  19815. array[ j ] = array[ j ] + elementDelta;
  19816. }
  19817. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  19818. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  19819. index.needsUpdate = true;
  19820. geometryInfo.indexStart = nextIndexStart;
  19821. }
  19822. nextIndexStart += geometryInfo.reservedIndexCount;
  19823. }
  19824. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  19825. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  19826. const { vertexStart, reservedVertexCount } = geometryInfo;
  19827. const attributes = geometry.attributes;
  19828. for ( const key in attributes ) {
  19829. const attribute = attributes[ key ];
  19830. const { array, itemSize } = attribute;
  19831. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  19832. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  19833. attribute.needsUpdate = true;
  19834. }
  19835. geometryInfo.vertexStart = nextVertexStart;
  19836. }
  19837. nextVertexStart += geometryInfo.reservedVertexCount;
  19838. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  19839. }
  19840. this._nextIndexStart = nextIndexStart;
  19841. this._nextVertexStart = nextVertexStart;
  19842. this._visibilityChanged = true;
  19843. return this;
  19844. }
  19845. /**
  19846. * Returns the bounding box for the given geometry.
  19847. *
  19848. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  19849. * @param {Box3} target - The target object that is used to store the method's result.
  19850. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  19851. */
  19852. getBoundingBoxAt( geometryId, target ) {
  19853. if ( geometryId >= this._geometryCount ) {
  19854. return null;
  19855. }
  19856. // compute bounding box
  19857. const geometry = this.geometry;
  19858. const geometryInfo = this._geometryInfo[ geometryId ];
  19859. if ( geometryInfo.boundingBox === null ) {
  19860. const box = new Box3();
  19861. const index = geometry.index;
  19862. const position = geometry.attributes.position;
  19863. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19864. let iv = i;
  19865. if ( index ) {
  19866. iv = index.getX( iv );
  19867. }
  19868. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19869. }
  19870. geometryInfo.boundingBox = box;
  19871. }
  19872. target.copy( geometryInfo.boundingBox );
  19873. return target;
  19874. }
  19875. /**
  19876. * Returns the bounding sphere for the given geometry.
  19877. *
  19878. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  19879. * @param {Sphere} target - The target object that is used to store the method's result.
  19880. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  19881. */
  19882. getBoundingSphereAt( geometryId, target ) {
  19883. if ( geometryId >= this._geometryCount ) {
  19884. return null;
  19885. }
  19886. // compute bounding sphere
  19887. const geometry = this.geometry;
  19888. const geometryInfo = this._geometryInfo[ geometryId ];
  19889. if ( geometryInfo.boundingSphere === null ) {
  19890. const sphere = new Sphere();
  19891. this.getBoundingBoxAt( geometryId, _box$1 );
  19892. _box$1.getCenter( sphere.center );
  19893. const index = geometry.index;
  19894. const position = geometry.attributes.position;
  19895. let maxRadiusSq = 0;
  19896. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  19897. let iv = i;
  19898. if ( index ) {
  19899. iv = index.getX( iv );
  19900. }
  19901. _vector$5.fromBufferAttribute( position, iv );
  19902. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19903. }
  19904. sphere.radius = Math.sqrt( maxRadiusSq );
  19905. geometryInfo.boundingSphere = sphere;
  19906. }
  19907. target.copy( geometryInfo.boundingSphere );
  19908. return target;
  19909. }
  19910. /**
  19911. * Sets the given local transformation matrix to the defined instance.
  19912. * Negatively scaled matrices are not supported.
  19913. *
  19914. * @param {number} instanceId - The ID of an instance to set the matrix of.
  19915. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  19916. * @return {BatchedMesh} A reference to this batched mesh.
  19917. */
  19918. setMatrixAt( instanceId, matrix ) {
  19919. this.validateInstanceId( instanceId );
  19920. const matricesTexture = this._matricesTexture;
  19921. const matricesArray = this._matricesTexture.image.data;
  19922. matrix.toArray( matricesArray, instanceId * 16 );
  19923. matricesTexture.needsUpdate = true;
  19924. return this;
  19925. }
  19926. /**
  19927. * Returns the local transformation matrix of the defined instance.
  19928. *
  19929. * @param {number} instanceId - The ID of an instance to get the matrix of.
  19930. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19931. * @return {Matrix4} The instance's local transformation matrix.
  19932. */
  19933. getMatrixAt( instanceId, matrix ) {
  19934. this.validateInstanceId( instanceId );
  19935. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  19936. }
  19937. /**
  19938. * Sets the given color to the defined instance.
  19939. *
  19940. * @param {number} instanceId - The ID of an instance to set the color of.
  19941. * @param {Color|Vector4} color - The color to set the instance to. Use a `Vector4` to also define alpha.
  19942. * @return {BatchedMesh} A reference to this batched mesh.
  19943. */
  19944. setColorAt( instanceId, color ) {
  19945. this.validateInstanceId( instanceId );
  19946. if ( this._colorsTexture === null ) {
  19947. this._initColorsTexture();
  19948. }
  19949. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  19950. this._colorsTexture.needsUpdate = true;
  19951. return this;
  19952. }
  19953. /**
  19954. * Returns the color of the defined instance.
  19955. *
  19956. * @param {number} instanceId - The ID of an instance to get the color of.
  19957. * @param {Color|Vector4} color - The target object that is used to store the method's result.
  19958. * @return {Color|Vector4} The instance's color. Use a `Vector4` to also retrieve alpha.
  19959. */
  19960. getColorAt( instanceId, color ) {
  19961. this.validateInstanceId( instanceId );
  19962. if ( this._colorsTexture === null ) {
  19963. if ( color.isVector4 ) {
  19964. return color.set( 1, 1, 1, 1 );
  19965. } else {
  19966. return color.setRGB( 1, 1, 1 );
  19967. }
  19968. } else {
  19969. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  19970. }
  19971. }
  19972. /**
  19973. * Sets the visibility of the instance.
  19974. *
  19975. * @param {number} instanceId - The id of the instance to set the visibility of.
  19976. * @param {boolean} visible - Whether the instance is visible or not.
  19977. * @return {BatchedMesh} A reference to this batched mesh.
  19978. */
  19979. setVisibleAt( instanceId, visible ) {
  19980. this.validateInstanceId( instanceId );
  19981. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  19982. return this;
  19983. }
  19984. this._instanceInfo[ instanceId ].visible = visible;
  19985. this._visibilityChanged = true;
  19986. return this;
  19987. }
  19988. /**
  19989. * Returns the visibility state of the defined instance.
  19990. *
  19991. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  19992. * @return {boolean} Whether the instance is visible or not.
  19993. */
  19994. getVisibleAt( instanceId ) {
  19995. this.validateInstanceId( instanceId );
  19996. return this._instanceInfo[ instanceId ].visible;
  19997. }
  19998. /**
  19999. * Sets the geometry ID of the instance at the given index.
  20000. *
  20001. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20002. * @param {number} geometryId - The geometry ID to be use by the instance.
  20003. * @return {BatchedMesh} A reference to this batched mesh.
  20004. */
  20005. setGeometryIdAt( instanceId, geometryId ) {
  20006. this.validateInstanceId( instanceId );
  20007. this.validateGeometryId( geometryId );
  20008. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20009. return this;
  20010. }
  20011. /**
  20012. * Returns the geometry ID of the defined instance.
  20013. *
  20014. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20015. * @return {number} The instance's geometry ID.
  20016. */
  20017. getGeometryIdAt( instanceId ) {
  20018. this.validateInstanceId( instanceId );
  20019. return this._instanceInfo[ instanceId ].geometryIndex;
  20020. }
  20021. /**
  20022. * Get the range representing the subset of triangles related to the attached geometry,
  20023. * indicating the starting offset and count, or `null` if invalid.
  20024. *
  20025. * @param {number} geometryId - The id of the geometry to get the range of.
  20026. * @param {Object} [target] - The target object that is used to store the method's result.
  20027. * @return {{
  20028. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20029. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20030. * start:number,count:number
  20031. * }} The result object with range data.
  20032. */
  20033. getGeometryRangeAt( geometryId, target = {} ) {
  20034. this.validateGeometryId( geometryId );
  20035. const geometryInfo = this._geometryInfo[ geometryId ];
  20036. target.vertexStart = geometryInfo.vertexStart;
  20037. target.vertexCount = geometryInfo.vertexCount;
  20038. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20039. target.indexStart = geometryInfo.indexStart;
  20040. target.indexCount = geometryInfo.indexCount;
  20041. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20042. target.start = geometryInfo.start;
  20043. target.count = geometryInfo.count;
  20044. return target;
  20045. }
  20046. /**
  20047. * Resizes the necessary buffers to support the provided number of instances.
  20048. * If the provided arguments shrink the number of instances but there are not enough
  20049. * unused Ids at the end of the list then an error is thrown.
  20050. *
  20051. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20052. */
  20053. setInstanceCount( maxInstanceCount ) {
  20054. // shrink the available instances as much as possible
  20055. const availableInstanceIds = this._availableInstanceIds;
  20056. const instanceInfo = this._instanceInfo;
  20057. availableInstanceIds.sort( ascIdSort );
  20058. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20059. instanceInfo.pop();
  20060. availableInstanceIds.pop();
  20061. }
  20062. // throw an error if it can't be shrunk to the desired size
  20063. if ( maxInstanceCount < instanceInfo.length ) {
  20064. throw new Error( `THREE.BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20065. }
  20066. // copy the multi draw counts
  20067. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20068. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20069. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20070. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20071. this._multiDrawCounts = multiDrawCounts;
  20072. this._multiDrawStarts = multiDrawStarts;
  20073. this._maxInstanceCount = maxInstanceCount;
  20074. // update texture data for instance sampling
  20075. const indirectTexture = this._indirectTexture;
  20076. const matricesTexture = this._matricesTexture;
  20077. const colorsTexture = this._colorsTexture;
  20078. indirectTexture.dispose();
  20079. this._initIndirectTexture();
  20080. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20081. matricesTexture.dispose();
  20082. this._initMatricesTexture();
  20083. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20084. if ( colorsTexture ) {
  20085. colorsTexture.dispose();
  20086. this._initColorsTexture();
  20087. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20088. }
  20089. }
  20090. /**
  20091. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20092. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20093. * end of the geometry attributes then an error is thrown.
  20094. *
  20095. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20096. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20097. */
  20098. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20099. // Check if we can shrink to the requested vertex attribute size
  20100. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20101. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20102. if ( requiredVertexLength > maxVertexCount ) {
  20103. throw new Error( `THREE.BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20104. }
  20105. // Check if we can shrink to the requested index attribute size
  20106. if ( this.geometry.index ) {
  20107. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20108. if ( requiredIndexLength > maxIndexCount ) {
  20109. throw new Error( `THREE.BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20110. }
  20111. }
  20112. //
  20113. // dispose of the previous geometry
  20114. const oldGeometry = this.geometry;
  20115. oldGeometry.dispose();
  20116. // recreate the geometry needed based on the previous variant
  20117. this._maxVertexCount = maxVertexCount;
  20118. this._maxIndexCount = maxIndexCount;
  20119. if ( this._geometryInitialized ) {
  20120. this._geometryInitialized = false;
  20121. this.geometry = new BufferGeometry();
  20122. this._initializeGeometry( oldGeometry );
  20123. }
  20124. // copy data from the previous geometry
  20125. const geometry = this.geometry;
  20126. if ( oldGeometry.index ) {
  20127. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20128. }
  20129. for ( const key in oldGeometry.attributes ) {
  20130. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20131. }
  20132. }
  20133. raycast( raycaster, intersects ) {
  20134. const instanceInfo = this._instanceInfo;
  20135. const geometryInfoList = this._geometryInfo;
  20136. const matrixWorld = this.matrixWorld;
  20137. const batchGeometry = this.geometry;
  20138. // iterate over each geometry
  20139. _mesh.material = this.material;
  20140. _mesh.geometry.index = batchGeometry.index;
  20141. _mesh.geometry.attributes = batchGeometry.attributes;
  20142. if ( _mesh.geometry.boundingBox === null ) {
  20143. _mesh.geometry.boundingBox = new Box3();
  20144. }
  20145. if ( _mesh.geometry.boundingSphere === null ) {
  20146. _mesh.geometry.boundingSphere = new Sphere();
  20147. }
  20148. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20149. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20150. continue;
  20151. }
  20152. const geometryId = instanceInfo[ i ].geometryIndex;
  20153. const geometryInfo = geometryInfoList[ geometryId ];
  20154. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20155. // get the intersects
  20156. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20157. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20158. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20159. _mesh.raycast( raycaster, _batchIntersects );
  20160. // add batch id to the intersects
  20161. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20162. const intersect = _batchIntersects[ j ];
  20163. intersect.object = this;
  20164. intersect.batchId = i;
  20165. intersects.push( intersect );
  20166. }
  20167. _batchIntersects.length = 0;
  20168. }
  20169. _mesh.material = null;
  20170. _mesh.geometry.index = null;
  20171. _mesh.geometry.attributes = {};
  20172. _mesh.geometry.setDrawRange( 0, Infinity );
  20173. }
  20174. copy( source ) {
  20175. super.copy( source );
  20176. this.geometry = source.geometry.clone();
  20177. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20178. this.sortObjects = source.sortObjects;
  20179. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20180. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20181. this._geometryInfo = source._geometryInfo.map( info => ( {
  20182. ...info,
  20183. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20184. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20185. } ) );
  20186. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20187. this._availableInstanceIds = source._availableInstanceIds.slice();
  20188. this._availableGeometryIds = source._availableGeometryIds.slice();
  20189. this._nextIndexStart = source._nextIndexStart;
  20190. this._nextVertexStart = source._nextVertexStart;
  20191. this._geometryCount = source._geometryCount;
  20192. this._maxInstanceCount = source._maxInstanceCount;
  20193. this._maxVertexCount = source._maxVertexCount;
  20194. this._maxIndexCount = source._maxIndexCount;
  20195. this._geometryInitialized = source._geometryInitialized;
  20196. this._multiDrawCounts = source._multiDrawCounts.slice();
  20197. this._multiDrawStarts = source._multiDrawStarts.slice();
  20198. this._indirectTexture = source._indirectTexture.clone();
  20199. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20200. this._matricesTexture = source._matricesTexture.clone();
  20201. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20202. if ( this._colorsTexture !== null ) {
  20203. this._colorsTexture = source._colorsTexture.clone();
  20204. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20205. }
  20206. return this;
  20207. }
  20208. /**
  20209. * Frees the GPU-related resources allocated by this instance. Call this
  20210. * method whenever this instance is no longer used in your app.
  20211. */
  20212. dispose() {
  20213. // Assuming the geometry is not shared with other meshes
  20214. this.geometry.dispose();
  20215. this._matricesTexture.dispose();
  20216. this._matricesTexture = null;
  20217. this._indirectTexture.dispose();
  20218. this._indirectTexture = null;
  20219. if ( this._colorsTexture !== null ) {
  20220. this._colorsTexture.dispose();
  20221. this._colorsTexture = null;
  20222. }
  20223. }
  20224. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20225. // if visibility has not changed and frustum culling and object sorting is not required
  20226. // then skip iterating over all items
  20227. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20228. return;
  20229. }
  20230. // the indexed version of the multi draw function requires specifying the start
  20231. // offset in bytes.
  20232. const index = geometry.getIndex();
  20233. let bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20234. // the "wireframe" attribute implicitly creates a line attribute in the renderer, which is double
  20235. // the vertices to draw (3 lines per triangle) so we multiply the draw counts / starts and make
  20236. // assumptions about the index buffer byte size.
  20237. let multiDrawMultiplier = 1;
  20238. if ( material.wireframe ) {
  20239. multiDrawMultiplier = 2;
  20240. bytesPerElement = geometry.attributes.position.count > 65535 ? 4 : 2;
  20241. }
  20242. const instanceInfo = this._instanceInfo;
  20243. const multiDrawStarts = this._multiDrawStarts;
  20244. const multiDrawCounts = this._multiDrawCounts;
  20245. const geometryInfoList = this._geometryInfo;
  20246. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20247. const indirectTexture = this._indirectTexture;
  20248. const indirectArray = indirectTexture.image.data;
  20249. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20250. // prepare the frustum in the local frame
  20251. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20252. _matrix$1
  20253. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20254. .multiply( this.matrixWorld );
  20255. _frustum.setFromProjectionMatrix(
  20256. _matrix$1,
  20257. camera.coordinateSystem,
  20258. camera.reversedDepth
  20259. );
  20260. }
  20261. let multiDrawCount = 0;
  20262. if ( this.sortObjects ) {
  20263. // get the camera position in the local frame
  20264. _matrix$1.copy( this.matrixWorld ).invert();
  20265. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20266. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20267. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20268. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20269. const geometryId = instanceInfo[ i ].geometryIndex;
  20270. // get the bounds in world space
  20271. this.getMatrixAt( i, _matrix$1 );
  20272. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20273. // determine whether the batched geometry is within the frustum
  20274. let culled = false;
  20275. if ( perObjectFrustumCulled ) {
  20276. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20277. }
  20278. if ( ! culled ) {
  20279. // get the distance from camera used for sorting
  20280. const geometryInfo = geometryInfoList[ geometryId ];
  20281. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20282. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20283. }
  20284. }
  20285. }
  20286. // Sort the draw ranges and prep for rendering
  20287. const list = _renderList.list;
  20288. const customSort = this.customSort;
  20289. if ( customSort === null ) {
  20290. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20291. } else {
  20292. customSort.call( this, list, camera );
  20293. }
  20294. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20295. const item = list[ i ];
  20296. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement * multiDrawMultiplier;
  20297. multiDrawCounts[ multiDrawCount ] = item.count * multiDrawMultiplier;
  20298. indirectArray[ multiDrawCount ] = item.index;
  20299. multiDrawCount ++;
  20300. }
  20301. _renderList.reset();
  20302. } else {
  20303. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20304. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20305. const geometryId = instanceInfo[ i ].geometryIndex;
  20306. // determine whether the batched geometry is within the frustum
  20307. let culled = false;
  20308. if ( perObjectFrustumCulled ) {
  20309. // get the bounds in world space
  20310. this.getMatrixAt( i, _matrix$1 );
  20311. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20312. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20313. }
  20314. if ( ! culled ) {
  20315. const geometryInfo = geometryInfoList[ geometryId ];
  20316. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement * multiDrawMultiplier;
  20317. multiDrawCounts[ multiDrawCount ] = geometryInfo.count * multiDrawMultiplier;
  20318. indirectArray[ multiDrawCount ] = i;
  20319. multiDrawCount ++;
  20320. }
  20321. }
  20322. }
  20323. }
  20324. indirectTexture.needsUpdate = true;
  20325. this._multiDrawCount = multiDrawCount;
  20326. this._visibilityChanged = false;
  20327. }
  20328. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20329. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20330. }
  20331. }
  20332. /**
  20333. * A material for rendering line primitives.
  20334. *
  20335. * Materials define the appearance of renderable 3D objects.
  20336. *
  20337. * ```js
  20338. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20339. * ```
  20340. *
  20341. * @augments Material
  20342. */
  20343. class LineBasicMaterial extends Material {
  20344. /**
  20345. * Constructs a new line basic material.
  20346. *
  20347. * @param {Object} [parameters] - An object with one or more properties
  20348. * defining the material's appearance. Any property of the material
  20349. * (including any property from inherited materials) can be passed
  20350. * in here. Color values can be passed any type of value accepted
  20351. * by {@link Color#set}.
  20352. */
  20353. constructor( parameters ) {
  20354. super();
  20355. /**
  20356. * This flag can be used for type testing.
  20357. *
  20358. * @type {boolean}
  20359. * @readonly
  20360. * @default true
  20361. */
  20362. this.isLineBasicMaterial = true;
  20363. this.type = 'LineBasicMaterial';
  20364. /**
  20365. * Color of the material.
  20366. *
  20367. * @type {Color}
  20368. * @default (1,1,1)
  20369. */
  20370. this.color = new Color( 0xffffff );
  20371. /**
  20372. * Sets the color of the lines using data from a texture. The texture map
  20373. * color is modulated by the diffuse `color`.
  20374. *
  20375. * `map` represents color data, and the texture must be assigned a
  20376. * {@link Texture#colorSpace}. Most `map` textures set
  20377. * `texture.colorSpace = SRGBColorSpace`.
  20378. *
  20379. * @type {?Texture}
  20380. * @default null
  20381. */
  20382. this.map = null;
  20383. /**
  20384. * Controls line thickness or lines.
  20385. *
  20386. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20387. * ignore this setting and always render line primitives with a
  20388. * width of one pixel.
  20389. *
  20390. * @type {number}
  20391. * @default 1
  20392. */
  20393. this.linewidth = 1;
  20394. /**
  20395. * Defines appearance of line ends.
  20396. *
  20397. * Can only be used with {@link SVGRenderer}.
  20398. *
  20399. * @type {('butt'|'round'|'square')}
  20400. * @default 'round'
  20401. */
  20402. this.linecap = 'round';
  20403. /**
  20404. * Defines appearance of line joints.
  20405. *
  20406. * Can only be used with {@link SVGRenderer}.
  20407. *
  20408. * @type {('round'|'bevel'|'miter')}
  20409. * @default 'round'
  20410. */
  20411. this.linejoin = 'round';
  20412. /**
  20413. * Whether the material is affected by fog or not.
  20414. *
  20415. * @type {boolean}
  20416. * @default true
  20417. */
  20418. this.fog = true;
  20419. this.setValues( parameters );
  20420. }
  20421. copy( source ) {
  20422. super.copy( source );
  20423. this.color.copy( source.color );
  20424. this.map = source.map;
  20425. this.linewidth = source.linewidth;
  20426. this.linecap = source.linecap;
  20427. this.linejoin = source.linejoin;
  20428. this.fog = source.fog;
  20429. return this;
  20430. }
  20431. }
  20432. const _vStart = /*@__PURE__*/ new Vector3();
  20433. const _vEnd = /*@__PURE__*/ new Vector3();
  20434. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20435. const _ray$1 = /*@__PURE__*/ new Ray();
  20436. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20437. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20438. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20439. /**
  20440. * A continuous line. The line are rendered by connecting consecutive
  20441. * vertices with straight lines.
  20442. *
  20443. * ```js
  20444. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  20445. *
  20446. * const points = [];
  20447. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  20448. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  20449. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  20450. *
  20451. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  20452. *
  20453. * const line = new THREE.Line( geometry, material );
  20454. * scene.add( line );
  20455. * ```
  20456. *
  20457. * @augments Object3D
  20458. */
  20459. class Line extends Object3D {
  20460. /**
  20461. * Constructs a new line.
  20462. *
  20463. * @param {BufferGeometry} [geometry] - The line geometry.
  20464. * @param {Material|Array<Material>} [material] - The line material.
  20465. */
  20466. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20467. super();
  20468. /**
  20469. * This flag can be used for type testing.
  20470. *
  20471. * @type {boolean}
  20472. * @readonly
  20473. * @default true
  20474. */
  20475. this.isLine = true;
  20476. this.type = 'Line';
  20477. /**
  20478. * The line geometry.
  20479. *
  20480. * @type {BufferGeometry}
  20481. */
  20482. this.geometry = geometry;
  20483. /**
  20484. * The line material.
  20485. *
  20486. * @type {Material|Array<Material>}
  20487. * @default LineBasicMaterial
  20488. */
  20489. this.material = material;
  20490. /**
  20491. * A dictionary representing the morph targets in the geometry. The key is the
  20492. * morph targets name, the value its attribute index. This member is `undefined`
  20493. * by default and only set when morph targets are detected in the geometry.
  20494. *
  20495. * @type {Object<string,number>|undefined}
  20496. * @default undefined
  20497. */
  20498. this.morphTargetDictionary = undefined;
  20499. /**
  20500. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20501. * is applied. This member is `undefined` by default and only set when morph targets are
  20502. * detected in the geometry.
  20503. *
  20504. * @type {Array<number>|undefined}
  20505. * @default undefined
  20506. */
  20507. this.morphTargetInfluences = undefined;
  20508. this.updateMorphTargets();
  20509. }
  20510. copy( source, recursive ) {
  20511. super.copy( source, recursive );
  20512. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20513. this.geometry = source.geometry;
  20514. return this;
  20515. }
  20516. /**
  20517. * Computes an array of distance values which are necessary for rendering dashed lines.
  20518. * For each vertex in the geometry, the method calculates the cumulative length from the
  20519. * current point to the very beginning of the line.
  20520. *
  20521. * @return {Line} A reference to this line.
  20522. */
  20523. computeLineDistances() {
  20524. const geometry = this.geometry;
  20525. // we assume non-indexed geometry
  20526. if ( geometry.index === null ) {
  20527. const positionAttribute = geometry.attributes.position;
  20528. const lineDistances = [ 0 ];
  20529. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20530. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20531. _vEnd.fromBufferAttribute( positionAttribute, i );
  20532. lineDistances[ i ] = lineDistances[ i - 1 ];
  20533. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20534. }
  20535. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20536. } else {
  20537. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20538. }
  20539. return this;
  20540. }
  20541. /**
  20542. * Computes intersection points between a casted ray and this line.
  20543. *
  20544. * @param {Raycaster} raycaster - The raycaster.
  20545. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20546. */
  20547. raycast( raycaster, intersects ) {
  20548. const geometry = this.geometry;
  20549. const matrixWorld = this.matrixWorld;
  20550. const threshold = raycaster.params.Line.threshold;
  20551. const drawRange = geometry.drawRange;
  20552. // Checking boundingSphere distance to ray
  20553. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20554. _sphere$1.copy( geometry.boundingSphere );
  20555. _sphere$1.applyMatrix4( matrixWorld );
  20556. _sphere$1.radius += threshold;
  20557. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20558. //
  20559. _inverseMatrix$1.copy( matrixWorld ).invert();
  20560. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20561. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20562. const localThresholdSq = localThreshold * localThreshold;
  20563. const step = this.isLineSegments ? 2 : 1;
  20564. const index = geometry.index;
  20565. const attributes = geometry.attributes;
  20566. const positionAttribute = attributes.position;
  20567. if ( index !== null ) {
  20568. const start = Math.max( 0, drawRange.start );
  20569. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20570. for ( let i = start, l = end - 1; i < l; i += step ) {
  20571. const a = index.getX( i );
  20572. const b = index.getX( i + 1 );
  20573. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  20574. if ( intersect ) {
  20575. intersects.push( intersect );
  20576. }
  20577. }
  20578. if ( this.isLineLoop ) {
  20579. const a = index.getX( end - 1 );
  20580. const b = index.getX( start );
  20581. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  20582. if ( intersect ) {
  20583. intersects.push( intersect );
  20584. }
  20585. }
  20586. } else {
  20587. const start = Math.max( 0, drawRange.start );
  20588. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20589. for ( let i = start, l = end - 1; i < l; i += step ) {
  20590. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  20591. if ( intersect ) {
  20592. intersects.push( intersect );
  20593. }
  20594. }
  20595. if ( this.isLineLoop ) {
  20596. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  20597. if ( intersect ) {
  20598. intersects.push( intersect );
  20599. }
  20600. }
  20601. }
  20602. }
  20603. /**
  20604. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  20605. * to make sure existing morph targets can influence this 3D object.
  20606. */
  20607. updateMorphTargets() {
  20608. const geometry = this.geometry;
  20609. const morphAttributes = geometry.morphAttributes;
  20610. const keys = Object.keys( morphAttributes );
  20611. if ( keys.length > 0 ) {
  20612. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20613. if ( morphAttribute !== undefined ) {
  20614. this.morphTargetInfluences = [];
  20615. this.morphTargetDictionary = {};
  20616. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20617. const name = morphAttribute[ m ].name || String( m );
  20618. this.morphTargetInfluences.push( 0 );
  20619. this.morphTargetDictionary[ name ] = m;
  20620. }
  20621. }
  20622. }
  20623. }
  20624. }
  20625. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  20626. const positionAttribute = object.geometry.attributes.position;
  20627. _vStart.fromBufferAttribute( positionAttribute, a );
  20628. _vEnd.fromBufferAttribute( positionAttribute, b );
  20629. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20630. if ( distSq > thresholdSq ) return;
  20631. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20632. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20633. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20634. return {
  20635. distance: distance,
  20636. // What do we want? intersection point on the ray or on the segment??
  20637. // point: raycaster.ray.at( distance ),
  20638. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20639. index: i,
  20640. face: null,
  20641. faceIndex: null,
  20642. barycoord: null,
  20643. object: object
  20644. };
  20645. }
  20646. const _start = /*@__PURE__*/ new Vector3();
  20647. const _end = /*@__PURE__*/ new Vector3();
  20648. /**
  20649. * A series of lines drawn between pairs of vertices.
  20650. *
  20651. * @augments Line
  20652. */
  20653. class LineSegments extends Line {
  20654. /**
  20655. * Constructs a new line segments.
  20656. *
  20657. * @param {BufferGeometry} [geometry] - The line geometry.
  20658. * @param {Material|Array<Material>} [material] - The line material.
  20659. */
  20660. constructor( geometry, material ) {
  20661. super( geometry, material );
  20662. /**
  20663. * This flag can be used for type testing.
  20664. *
  20665. * @type {boolean}
  20666. * @readonly
  20667. * @default true
  20668. */
  20669. this.isLineSegments = true;
  20670. this.type = 'LineSegments';
  20671. }
  20672. computeLineDistances() {
  20673. const geometry = this.geometry;
  20674. // we assume non-indexed geometry
  20675. if ( geometry.index === null ) {
  20676. const positionAttribute = geometry.attributes.position;
  20677. const lineDistances = [];
  20678. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20679. _start.fromBufferAttribute( positionAttribute, i );
  20680. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20681. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20682. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20683. }
  20684. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20685. } else {
  20686. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20687. }
  20688. return this;
  20689. }
  20690. }
  20691. /**
  20692. * A continuous line. This is nearly the same as {@link Line} the only difference
  20693. * is that the last vertex is connected with the first vertex in order to close
  20694. * the line to form a loop.
  20695. *
  20696. * @augments Line
  20697. */
  20698. class LineLoop extends Line {
  20699. /**
  20700. * Constructs a new line loop.
  20701. *
  20702. * @param {BufferGeometry} [geometry] - The line geometry.
  20703. * @param {Material|Array<Material>} [material] - The line material.
  20704. */
  20705. constructor( geometry, material ) {
  20706. super( geometry, material );
  20707. /**
  20708. * This flag can be used for type testing.
  20709. *
  20710. * @type {boolean}
  20711. * @readonly
  20712. * @default true
  20713. */
  20714. this.isLineLoop = true;
  20715. this.type = 'LineLoop';
  20716. }
  20717. }
  20718. /**
  20719. * A material for rendering point primitives.
  20720. *
  20721. * Materials define the appearance of renderable 3D objects.
  20722. *
  20723. * ```js
  20724. * const vertices = [];
  20725. *
  20726. * for ( let i = 0; i < 10000; i ++ ) {
  20727. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  20728. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  20729. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  20730. *
  20731. * vertices.push( x, y, z );
  20732. * }
  20733. *
  20734. * const geometry = new THREE.BufferGeometry();
  20735. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  20736. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  20737. * const points = new THREE.Points( geometry, material );
  20738. * scene.add( points );
  20739. * ```
  20740. *
  20741. * @augments Material
  20742. */
  20743. class PointsMaterial extends Material {
  20744. /**
  20745. * Constructs a new points material.
  20746. *
  20747. * @param {Object} [parameters] - An object with one or more properties
  20748. * defining the material's appearance. Any property of the material
  20749. * (including any property from inherited materials) can be passed
  20750. * in here. Color values can be passed any type of value accepted
  20751. * by {@link Color#set}.
  20752. */
  20753. constructor( parameters ) {
  20754. super();
  20755. /**
  20756. * This flag can be used for type testing.
  20757. *
  20758. * @type {boolean}
  20759. * @readonly
  20760. * @default true
  20761. */
  20762. this.isPointsMaterial = true;
  20763. this.type = 'PointsMaterial';
  20764. /**
  20765. * Color of the material.
  20766. *
  20767. * @type {Color}
  20768. * @default (1,1,1)
  20769. */
  20770. this.color = new Color( 0xffffff );
  20771. /**
  20772. * The color map. May optionally include an alpha channel, typically combined
  20773. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  20774. * color is modulated by the diffuse `color`.
  20775. *
  20776. * `map` represents color data, and the texture must be assigned a
  20777. * {@link Texture#colorSpace}. Most `map` textures set
  20778. * `texture.colorSpace = SRGBColorSpace`.
  20779. *
  20780. * @type {?Texture}
  20781. * @default null
  20782. */
  20783. this.map = null;
  20784. /**
  20785. * The alpha map is a grayscale texture that controls the opacity across the
  20786. * surface (black: fully transparent; white: fully opaque).
  20787. *
  20788. * Only the color of the texture is used, ignoring the alpha channel if one
  20789. * exists. For RGB and RGBA textures, the renderer will use the green channel
  20790. * when sampling this texture due to the extra bit of precision provided for
  20791. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  20792. * luminance/alpha textures will also still work as expected.
  20793. *
  20794. * `alphaMap` represents non-color data. Any texture assigned must have
  20795. * `texture.colorSpace = NoColorSpace` (default).
  20796. *
  20797. * @type {?Texture}
  20798. * @default null
  20799. */
  20800. this.alphaMap = null;
  20801. /**
  20802. * Defines the size of the points in pixels.
  20803. *
  20804. * 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).
  20805. *
  20806. * @type {number}
  20807. * @default 1
  20808. */
  20809. this.size = 1;
  20810. /**
  20811. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  20812. *
  20813. * @type {boolean}
  20814. * @default true
  20815. */
  20816. this.sizeAttenuation = true;
  20817. /**
  20818. * Whether the material is affected by fog or not.
  20819. *
  20820. * @type {boolean}
  20821. * @default true
  20822. */
  20823. this.fog = true;
  20824. this.setValues( parameters );
  20825. }
  20826. copy( source ) {
  20827. super.copy( source );
  20828. this.color.copy( source.color );
  20829. this.map = source.map;
  20830. this.alphaMap = source.alphaMap;
  20831. this.size = source.size;
  20832. this.sizeAttenuation = source.sizeAttenuation;
  20833. this.fog = source.fog;
  20834. return this;
  20835. }
  20836. }
  20837. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20838. const _ray = /*@__PURE__*/ new Ray();
  20839. const _sphere = /*@__PURE__*/ new Sphere();
  20840. const _position$3 = /*@__PURE__*/ new Vector3();
  20841. /**
  20842. * A class for displaying points or point clouds.
  20843. *
  20844. * @augments Object3D
  20845. */
  20846. class Points extends Object3D {
  20847. /**
  20848. * Constructs a new point cloud.
  20849. *
  20850. * @param {BufferGeometry} [geometry] - The points geometry.
  20851. * @param {Material|Array<Material>} [material] - The points material.
  20852. */
  20853. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20854. super();
  20855. /**
  20856. * This flag can be used for type testing.
  20857. *
  20858. * @type {boolean}
  20859. * @readonly
  20860. * @default true
  20861. */
  20862. this.isPoints = true;
  20863. this.type = 'Points';
  20864. /**
  20865. * The points geometry.
  20866. *
  20867. * @type {BufferGeometry}
  20868. */
  20869. this.geometry = geometry;
  20870. /**
  20871. * The line material.
  20872. *
  20873. * @type {Material|Array<Material>}
  20874. * @default PointsMaterial
  20875. */
  20876. this.material = material;
  20877. /**
  20878. * A dictionary representing the morph targets in the geometry. The key is the
  20879. * morph targets name, the value its attribute index. This member is `undefined`
  20880. * by default and only set when morph targets are detected in the geometry.
  20881. *
  20882. * @type {Object<string,number>|undefined}
  20883. * @default undefined
  20884. */
  20885. this.morphTargetDictionary = undefined;
  20886. /**
  20887. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  20888. * is applied. This member is `undefined` by default and only set when morph targets are
  20889. * detected in the geometry.
  20890. *
  20891. * @type {Array<number>|undefined}
  20892. * @default undefined
  20893. */
  20894. this.morphTargetInfluences = undefined;
  20895. this.updateMorphTargets();
  20896. }
  20897. copy( source, recursive ) {
  20898. super.copy( source, recursive );
  20899. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20900. this.geometry = source.geometry;
  20901. return this;
  20902. }
  20903. /**
  20904. * Computes intersection points between a casted ray and this point cloud.
  20905. *
  20906. * @param {Raycaster} raycaster - The raycaster.
  20907. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  20908. */
  20909. raycast( raycaster, intersects ) {
  20910. const geometry = this.geometry;
  20911. const matrixWorld = this.matrixWorld;
  20912. const threshold = raycaster.params.Points.threshold;
  20913. const drawRange = geometry.drawRange;
  20914. // Checking boundingSphere distance to ray
  20915. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20916. _sphere.copy( geometry.boundingSphere );
  20917. _sphere.applyMatrix4( matrixWorld );
  20918. _sphere.radius += threshold;
  20919. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20920. //
  20921. _inverseMatrix.copy( matrixWorld ).invert();
  20922. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20923. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20924. const localThresholdSq = localThreshold * localThreshold;
  20925. const index = geometry.index;
  20926. const attributes = geometry.attributes;
  20927. const positionAttribute = attributes.position;
  20928. if ( index !== null ) {
  20929. const start = Math.max( 0, drawRange.start );
  20930. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20931. for ( let i = start, il = end; i < il; i ++ ) {
  20932. const a = index.getX( i );
  20933. _position$3.fromBufferAttribute( positionAttribute, a );
  20934. testPoint( _position$3, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20935. }
  20936. } else {
  20937. const start = Math.max( 0, drawRange.start );
  20938. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20939. for ( let i = start, l = end; i < l; i ++ ) {
  20940. _position$3.fromBufferAttribute( positionAttribute, i );
  20941. testPoint( _position$3, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20942. }
  20943. }
  20944. }
  20945. /**
  20946. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  20947. * to make sure existing morph targets can influence this 3D object.
  20948. */
  20949. updateMorphTargets() {
  20950. const geometry = this.geometry;
  20951. const morphAttributes = geometry.morphAttributes;
  20952. const keys = Object.keys( morphAttributes );
  20953. if ( keys.length > 0 ) {
  20954. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20955. if ( morphAttribute !== undefined ) {
  20956. this.morphTargetInfluences = [];
  20957. this.morphTargetDictionary = {};
  20958. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20959. const name = morphAttribute[ m ].name || String( m );
  20960. this.morphTargetInfluences.push( 0 );
  20961. this.morphTargetDictionary[ name ] = m;
  20962. }
  20963. }
  20964. }
  20965. }
  20966. }
  20967. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20968. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20969. if ( rayPointDistanceSq < localThresholdSq ) {
  20970. const intersectPoint = new Vector3();
  20971. _ray.closestPointToPoint( point, intersectPoint );
  20972. intersectPoint.applyMatrix4( matrixWorld );
  20973. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20974. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20975. intersects.push( {
  20976. distance: distance,
  20977. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20978. point: intersectPoint,
  20979. index: index,
  20980. face: null,
  20981. faceIndex: null,
  20982. barycoord: null,
  20983. object: object
  20984. } );
  20985. }
  20986. }
  20987. /**
  20988. * A texture for use with a video.
  20989. *
  20990. * ```js
  20991. * // assuming you have created a HTML video element with id="video"
  20992. * const video = document.getElementById( 'video' );
  20993. * const texture = new THREE.VideoTexture( video );
  20994. * ```
  20995. *
  20996. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  20997. * set to THREE.SRGBColorSpace.
  20998. *
  20999. * Note: After the initial use of a texture, its dimensions, format, and type
  21000. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21001. *
  21002. * @augments Texture
  21003. */
  21004. class VideoTexture extends Texture {
  21005. /**
  21006. * Constructs a new video texture.
  21007. *
  21008. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21009. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21010. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21011. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21012. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21013. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21014. * @param {number} [format=RGBAFormat] - The texture format.
  21015. * @param {number} [type=UnsignedByteType] - The texture type.
  21016. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21017. */
  21018. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21019. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21020. /**
  21021. * This flag can be used for type testing.
  21022. *
  21023. * @type {boolean}
  21024. * @readonly
  21025. * @default true
  21026. */
  21027. this.isVideoTexture = true;
  21028. /**
  21029. * Whether to generate mipmaps (if possible) for a texture.
  21030. *
  21031. * Overwritten and set to `false` by default.
  21032. *
  21033. * @type {boolean}
  21034. * @default false
  21035. */
  21036. this.generateMipmaps = false;
  21037. /**
  21038. * The video frame request callback identifier, which is a positive integer.
  21039. *
  21040. * Value of 0 represents no scheduled rVFC.
  21041. *
  21042. * @private
  21043. * @type {number}
  21044. */
  21045. this._requestVideoFrameCallbackId = 0;
  21046. const scope = this;
  21047. function updateVideo() {
  21048. scope.needsUpdate = true;
  21049. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21050. }
  21051. if ( 'requestVideoFrameCallback' in video ) {
  21052. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21053. }
  21054. }
  21055. clone() {
  21056. return new this.constructor( this.image ).copy( this );
  21057. }
  21058. /**
  21059. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21060. * to `true` every time a new frame is available.
  21061. *
  21062. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21063. */
  21064. update() {
  21065. const video = this.image;
  21066. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21067. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21068. this.needsUpdate = true;
  21069. }
  21070. }
  21071. dispose() {
  21072. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21073. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21074. this._requestVideoFrameCallbackId = 0;
  21075. }
  21076. super.dispose();
  21077. }
  21078. }
  21079. /**
  21080. * This class can be used as an alternative way to define video data. Instead of using
  21081. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21082. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21083. * video frames are decoded with the WebCodecs API.
  21084. *
  21085. * ```js
  21086. * const texture = new THREE.VideoFrameTexture();
  21087. * texture.setFrame( frame );
  21088. * ```
  21089. *
  21090. * @augments VideoTexture
  21091. */
  21092. class VideoFrameTexture extends VideoTexture {
  21093. /**
  21094. * Constructs a new video frame texture.
  21095. *
  21096. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21097. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21098. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21099. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21100. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21101. * @param {number} [format=RGBAFormat] - The texture format.
  21102. * @param {number} [type=UnsignedByteType] - The texture type.
  21103. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21104. */
  21105. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21106. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21107. /**
  21108. * This flag can be used for type testing.
  21109. *
  21110. * @type {boolean}
  21111. * @readonly
  21112. * @default true
  21113. */
  21114. this.isVideoFrameTexture = true;
  21115. }
  21116. /**
  21117. * This method overwritten with an empty implementation since
  21118. * this type of texture is updated via `setFrame()`.
  21119. */
  21120. update() {}
  21121. clone() {
  21122. return new this.constructor().copy( this ); // restoring Texture.clone()
  21123. }
  21124. /**
  21125. * Sets the current frame of the video. This will automatically update the texture
  21126. * so the data can be used for rendering.
  21127. *
  21128. * @param {VideoFrame} frame - The video frame.
  21129. */
  21130. setFrame( frame ) {
  21131. this.image = frame;
  21132. this.needsUpdate = true;
  21133. }
  21134. }
  21135. /**
  21136. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21137. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21138. * as a texture for further usage.
  21139. *
  21140. * ```js
  21141. * const pixelRatio = window.devicePixelRatio;
  21142. * const textureSize = 128 * pixelRatio;
  21143. *
  21144. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21145. *
  21146. * // calculate start position for copying part of the frame data
  21147. * const vector = new Vector2();
  21148. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21149. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21150. *
  21151. * renderer.render( scene, camera );
  21152. *
  21153. * // copy part of the rendered frame into the framebuffer texture
  21154. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21155. * ```
  21156. *
  21157. * @augments Texture
  21158. */
  21159. class FramebufferTexture extends Texture {
  21160. /**
  21161. * Constructs a new framebuffer texture.
  21162. *
  21163. * @param {number} [width] - The width of the texture.
  21164. * @param {number} [height] - The height of the texture.
  21165. */
  21166. constructor( width, height ) {
  21167. super( { width, height } );
  21168. /**
  21169. * This flag can be used for type testing.
  21170. *
  21171. * @type {boolean}
  21172. * @readonly
  21173. * @default true
  21174. */
  21175. this.isFramebufferTexture = true;
  21176. /**
  21177. * How the texture is sampled when a texel covers more than one pixel.
  21178. *
  21179. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21180. *
  21181. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21182. * @default NearestFilter
  21183. */
  21184. this.magFilter = NearestFilter;
  21185. /**
  21186. * How the texture is sampled when a texel covers less than one pixel.
  21187. *
  21188. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21189. *
  21190. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21191. * @default NearestFilter
  21192. */
  21193. this.minFilter = NearestFilter;
  21194. /**
  21195. * Whether to generate mipmaps (if possible) for a texture.
  21196. *
  21197. * Overwritten and set to `false` by default.
  21198. *
  21199. * @type {boolean}
  21200. * @default false
  21201. */
  21202. this.generateMipmaps = false;
  21203. this.needsUpdate = true;
  21204. }
  21205. }
  21206. /**
  21207. * Creates a texture based on data in compressed form.
  21208. *
  21209. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21210. *
  21211. * @augments Texture
  21212. */
  21213. class CompressedTexture extends Texture {
  21214. /**
  21215. * Constructs a new compressed texture.
  21216. *
  21217. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21218. * the data and dimensions.
  21219. * @param {number} width - The width of the texture.
  21220. * @param {number} height - The height of the texture.
  21221. * @param {number} [format=RGBAFormat] - The texture format.
  21222. * @param {number} [type=UnsignedByteType] - The texture type.
  21223. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21224. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21225. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21226. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21227. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21228. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21229. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21230. */
  21231. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21232. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21233. /**
  21234. * This flag can be used for type testing.
  21235. *
  21236. * @type {boolean}
  21237. * @readonly
  21238. * @default true
  21239. */
  21240. this.isCompressedTexture = true;
  21241. /**
  21242. * The image property of a compressed texture just defines its dimensions.
  21243. *
  21244. * @type {{width:number,height:number}}
  21245. */
  21246. this.image = { width: width, height: height };
  21247. /**
  21248. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21249. *
  21250. * @type {Array<Object>}
  21251. */
  21252. this.mipmaps = mipmaps;
  21253. /**
  21254. * If set to `true`, the texture is flipped along the vertical axis when
  21255. * uploaded to the GPU.
  21256. *
  21257. * Overwritten and set to `false` by default since it is not possible to
  21258. * flip compressed textures.
  21259. *
  21260. * @type {boolean}
  21261. * @default false
  21262. * @readonly
  21263. */
  21264. this.flipY = false;
  21265. /**
  21266. * Whether to generate mipmaps (if possible) for a texture.
  21267. *
  21268. * Overwritten and set to `false` by default since it is not
  21269. * possible to generate mipmaps for compressed data. Mipmaps
  21270. * must be embedded in the compressed texture file.
  21271. *
  21272. * @type {boolean}
  21273. * @default false
  21274. * @readonly
  21275. */
  21276. this.generateMipmaps = false;
  21277. }
  21278. }
  21279. /**
  21280. * Creates a texture 2D array based on data in compressed form.
  21281. *
  21282. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21283. *
  21284. * @augments CompressedTexture
  21285. */
  21286. class CompressedArrayTexture extends CompressedTexture {
  21287. /**
  21288. * Constructs a new compressed array texture.
  21289. *
  21290. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21291. * the data and dimensions.
  21292. * @param {number} width - The width of the texture.
  21293. * @param {number} height - The height of the texture.
  21294. * @param {number} depth - The depth of the texture.
  21295. * @param {number} [format=RGBAFormat] - The min filter value.
  21296. * @param {number} [type=UnsignedByteType] - The min filter value.
  21297. */
  21298. constructor( mipmaps, width, height, depth, format, type ) {
  21299. super( mipmaps, width, height, format, type );
  21300. /**
  21301. * This flag can be used for type testing.
  21302. *
  21303. * @type {boolean}
  21304. * @readonly
  21305. * @default true
  21306. */
  21307. this.isCompressedArrayTexture = true;
  21308. /**
  21309. * The image property of a compressed texture just defines its dimensions.
  21310. *
  21311. * @name CompressedArrayTexture#image
  21312. * @type {{width:number,height:number,depth:number}}
  21313. */
  21314. this.image.depth = depth;
  21315. /**
  21316. * This defines how the texture is wrapped in the depth and corresponds to
  21317. * *W* in UVW mapping.
  21318. *
  21319. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21320. * @default ClampToEdgeWrapping
  21321. */
  21322. this.wrapR = ClampToEdgeWrapping;
  21323. /**
  21324. * A set of all layers which need to be updated in the texture.
  21325. *
  21326. * @type {Set<number>}
  21327. */
  21328. this.layerUpdates = new Set();
  21329. }
  21330. /**
  21331. * Describes that a specific layer of the texture needs to be updated.
  21332. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21333. * entire compressed texture array is sent to the GPU. Marking specific
  21334. * layers will only transmit subsets of all mipmaps associated with a
  21335. * specific depth in the array which is often much more performant.
  21336. *
  21337. * @param {number} layerIndex - The layer index that should be updated.
  21338. */
  21339. addLayerUpdate( layerIndex ) {
  21340. this.layerUpdates.add( layerIndex );
  21341. }
  21342. /**
  21343. * Resets the layer updates registry.
  21344. */
  21345. clearLayerUpdates() {
  21346. this.layerUpdates.clear();
  21347. }
  21348. }
  21349. /**
  21350. * Creates a cube texture based on data in compressed form.
  21351. *
  21352. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21353. *
  21354. * @augments CompressedTexture
  21355. */
  21356. class CompressedCubeTexture extends CompressedTexture {
  21357. /**
  21358. * Constructs a new compressed texture.
  21359. *
  21360. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21361. * @param {number} [format=RGBAFormat] - The texture format.
  21362. * @param {number} [type=UnsignedByteType] - The texture type.
  21363. */
  21364. constructor( images, format, type ) {
  21365. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21366. /**
  21367. * This flag can be used for type testing.
  21368. *
  21369. * @type {boolean}
  21370. * @readonly
  21371. * @default true
  21372. */
  21373. this.isCompressedCubeTexture = true;
  21374. /**
  21375. * This flag can be used for type testing.
  21376. *
  21377. * @type {boolean}
  21378. * @readonly
  21379. * @default true
  21380. */
  21381. this.isCubeTexture = true;
  21382. this.image = images;
  21383. }
  21384. }
  21385. /**
  21386. * Creates a cube texture made up of six images.
  21387. *
  21388. * ```js
  21389. * const loader = new THREE.CubeTextureLoader();
  21390. * loader.setPath( 'textures/cube/pisa/' );
  21391. *
  21392. * const textureCube = loader.load( [
  21393. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  21394. * ] );
  21395. *
  21396. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  21397. * ```
  21398. *
  21399. * @augments Texture
  21400. */
  21401. class CubeTexture extends Texture {
  21402. /**
  21403. * Constructs a new cube texture.
  21404. *
  21405. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  21406. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21407. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21408. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21409. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21410. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21411. * @param {number} [format=RGBAFormat] - The texture format.
  21412. * @param {number} [type=UnsignedByteType] - The texture type.
  21413. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21414. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  21415. */
  21416. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  21417. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21418. /**
  21419. * This flag can be used for type testing.
  21420. *
  21421. * @type {boolean}
  21422. * @readonly
  21423. * @default true
  21424. */
  21425. this.isCubeTexture = true;
  21426. /**
  21427. * If set to `true`, the texture is flipped along the vertical axis when
  21428. * uploaded to the GPU.
  21429. *
  21430. * Overwritten and set to `false` by default.
  21431. *
  21432. * @type {boolean}
  21433. * @default false
  21434. */
  21435. this.flipY = false;
  21436. }
  21437. /**
  21438. * Alias for {@link CubeTexture#image}.
  21439. *
  21440. * @type {Array<Image>}
  21441. */
  21442. get images() {
  21443. return this.image;
  21444. }
  21445. set images( value ) {
  21446. this.image = value;
  21447. }
  21448. }
  21449. /**
  21450. * Creates a texture from a canvas element.
  21451. *
  21452. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21453. * to `true` immediately since a canvas can directly be used for rendering.
  21454. *
  21455. * @augments Texture
  21456. */
  21457. class CanvasTexture extends Texture {
  21458. /**
  21459. * Constructs a new texture.
  21460. *
  21461. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21462. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21463. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21464. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21465. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21466. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21467. * @param {number} [format=RGBAFormat] - The texture format.
  21468. * @param {number} [type=UnsignedByteType] - The texture type.
  21469. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21470. */
  21471. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21472. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21473. /**
  21474. * This flag can be used for type testing.
  21475. *
  21476. * @type {boolean}
  21477. * @readonly
  21478. * @default true
  21479. */
  21480. this.isCanvasTexture = true;
  21481. this.needsUpdate = true;
  21482. }
  21483. }
  21484. /**
  21485. * Creates a texture from an HTML element.
  21486. *
  21487. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21488. * to `true` immediately and listens for the parent canvas's paint events to trigger updates.
  21489. *
  21490. * @augments Texture
  21491. */
  21492. class HTMLTexture extends Texture {
  21493. /**
  21494. * Constructs a new texture.
  21495. *
  21496. * @param {HTMLElement} [element] - The HTML element.
  21497. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21498. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21499. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21500. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21501. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21502. * @param {number} [format=RGBAFormat] - The texture format.
  21503. * @param {number} [type=UnsignedByteType] - The texture type.
  21504. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21505. */
  21506. constructor( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21507. super( element, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21508. /**
  21509. * This flag can be used for type testing.
  21510. *
  21511. * @type {boolean}
  21512. * @readonly
  21513. * @default true
  21514. */
  21515. this.isHTMLTexture = true;
  21516. this.generateMipmaps = false;
  21517. this.needsUpdate = true;
  21518. const parent = element ? element.parentNode : null;
  21519. if ( parent !== null && 'requestPaint' in parent ) {
  21520. parent.onpaint = () => {
  21521. this.needsUpdate = true;
  21522. };
  21523. parent.requestPaint();
  21524. }
  21525. }
  21526. dispose() {
  21527. const parent = this.image ? this.image.parentNode : null;
  21528. if ( parent !== null && 'onpaint' in parent ) {
  21529. parent.onpaint = null;
  21530. }
  21531. super.dispose();
  21532. }
  21533. }
  21534. /**
  21535. * This class can be used to automatically save the depth information of a
  21536. * rendering into a texture.
  21537. *
  21538. * @augments Texture
  21539. */
  21540. class DepthTexture extends Texture {
  21541. /**
  21542. * Constructs a new depth texture.
  21543. *
  21544. * @param {number} width - The width of the texture.
  21545. * @param {number} height - The height of the texture.
  21546. * @param {number} [type=UnsignedIntType] - The texture type.
  21547. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21548. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21549. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21550. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21551. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21552. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21553. * @param {number} [format=DepthFormat] - The texture format.
  21554. * @param {number} [depth=1] - The depth of the texture.
  21555. */
  21556. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  21557. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  21558. throw new Error( 'THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  21559. }
  21560. const image = { width: width, height: height, depth: depth };
  21561. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21562. /**
  21563. * This flag can be used for type testing.
  21564. *
  21565. * @type {boolean}
  21566. * @readonly
  21567. * @default true
  21568. */
  21569. this.isDepthTexture = true;
  21570. /**
  21571. * If set to `true`, the texture is flipped along the vertical axis when
  21572. * uploaded to the GPU.
  21573. *
  21574. * Overwritten and set to `false` by default.
  21575. *
  21576. * @type {boolean}
  21577. * @default false
  21578. */
  21579. this.flipY = false;
  21580. /**
  21581. * Whether to generate mipmaps (if possible) for a texture.
  21582. *
  21583. * Overwritten and set to `false` by default.
  21584. *
  21585. * @type {boolean}
  21586. * @default false
  21587. */
  21588. this.generateMipmaps = false;
  21589. /**
  21590. * Code corresponding to the depth compare function.
  21591. *
  21592. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  21593. * @default null
  21594. */
  21595. this.compareFunction = null;
  21596. }
  21597. copy( source ) {
  21598. super.copy( source );
  21599. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  21600. this.compareFunction = source.compareFunction;
  21601. return this;
  21602. }
  21603. toJSON( meta ) {
  21604. const data = super.toJSON( meta );
  21605. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  21606. return data;
  21607. }
  21608. }
  21609. /**
  21610. * This class can be used to automatically save the depth information of a
  21611. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  21612. *
  21613. * @augments DepthTexture
  21614. */
  21615. class CubeDepthTexture extends DepthTexture {
  21616. /**
  21617. * Constructs a new cube depth texture.
  21618. *
  21619. * @param {number} size - The size (width and height) of each cube face.
  21620. * @param {number} [type=UnsignedIntType] - The texture type.
  21621. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  21622. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21623. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21624. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  21625. * @param {number} [minFilter=NearestFilter] - The min filter value.
  21626. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21627. * @param {number} [format=DepthFormat] - The texture format.
  21628. */
  21629. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  21630. // Create 6 identical image descriptors for the cube faces
  21631. const image = { width: size, height: size, depth: 1 };
  21632. const images = [ image, image, image, image, image, image ];
  21633. // Call DepthTexture constructor with width, height
  21634. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  21635. // Replace the single image with the array of 6 images
  21636. this.image = images;
  21637. /**
  21638. * This flag can be used for type testing.
  21639. *
  21640. * @type {boolean}
  21641. * @readonly
  21642. * @default true
  21643. */
  21644. this.isCubeDepthTexture = true;
  21645. /**
  21646. * Set to true for cube texture handling in WebGLTextures.
  21647. *
  21648. * @type {boolean}
  21649. * @readonly
  21650. * @default true
  21651. */
  21652. this.isCubeTexture = true;
  21653. }
  21654. /**
  21655. * Alias for {@link CubeDepthTexture#image}.
  21656. *
  21657. * @type {Array<Image>}
  21658. */
  21659. get images() {
  21660. return this.image;
  21661. }
  21662. set images( value ) {
  21663. this.image = value;
  21664. }
  21665. }
  21666. /**
  21667. * Represents a texture created externally with the same renderer context.
  21668. *
  21669. * This may be a texture from a protected media stream, device camera feed,
  21670. * or other data feeds like a depth sensor.
  21671. *
  21672. * Note that this class is only supported in {@link WebGLRenderer}, and in
  21673. * the {@link WebGPURenderer} WebGPU backend.
  21674. *
  21675. * @augments Texture
  21676. */
  21677. class ExternalTexture extends Texture {
  21678. /**
  21679. * Creates a new raw texture.
  21680. *
  21681. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  21682. */
  21683. constructor( sourceTexture = null ) {
  21684. super();
  21685. /**
  21686. * The external source texture.
  21687. *
  21688. * @type {?(WebGLTexture|GPUTexture)}
  21689. * @default null
  21690. */
  21691. this.sourceTexture = sourceTexture;
  21692. /**
  21693. * This flag can be used for type testing.
  21694. *
  21695. * @type {boolean}
  21696. * @readonly
  21697. * @default true
  21698. */
  21699. this.isExternalTexture = true;
  21700. }
  21701. copy( source ) {
  21702. super.copy( source );
  21703. this.sourceTexture = source.sourceTexture;
  21704. return this;
  21705. }
  21706. }
  21707. /**
  21708. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  21709. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  21710. * of the axes.
  21711. *
  21712. * ```js
  21713. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  21714. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21715. * const cube = new THREE.Mesh( geometry, material );
  21716. * scene.add( cube );
  21717. * ```
  21718. *
  21719. * @augments BufferGeometry
  21720. * @demo scenes/geometry-browser.html#BoxGeometry
  21721. */
  21722. class BoxGeometry extends BufferGeometry {
  21723. /**
  21724. * Constructs a new box geometry.
  21725. *
  21726. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  21727. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  21728. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  21729. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  21730. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  21731. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  21732. */
  21733. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  21734. super();
  21735. this.type = 'BoxGeometry';
  21736. /**
  21737. * Holds the constructor parameters that have been
  21738. * used to generate the geometry. Any modification
  21739. * after instantiation does not change the geometry.
  21740. *
  21741. * @type {Object}
  21742. */
  21743. this.parameters = {
  21744. width: width,
  21745. height: height,
  21746. depth: depth,
  21747. widthSegments: widthSegments,
  21748. heightSegments: heightSegments,
  21749. depthSegments: depthSegments
  21750. };
  21751. const scope = this;
  21752. // segments
  21753. widthSegments = Math.floor( widthSegments );
  21754. heightSegments = Math.floor( heightSegments );
  21755. depthSegments = Math.floor( depthSegments );
  21756. // buffers
  21757. const indices = [];
  21758. const vertices = [];
  21759. const normals = [];
  21760. const uvs = [];
  21761. // helper variables
  21762. let numberOfVertices = 0;
  21763. let groupStart = 0;
  21764. // build each side of the box geometry
  21765. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21766. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21767. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21768. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21769. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21770. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21771. // build geometry
  21772. this.setIndex( indices );
  21773. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21774. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21775. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21776. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21777. const segmentWidth = width / gridX;
  21778. const segmentHeight = height / gridY;
  21779. const widthHalf = width / 2;
  21780. const heightHalf = height / 2;
  21781. const depthHalf = depth / 2;
  21782. const gridX1 = gridX + 1;
  21783. const gridY1 = gridY + 1;
  21784. let vertexCounter = 0;
  21785. let groupCount = 0;
  21786. const vector = new Vector3();
  21787. // generate vertices, normals and uvs
  21788. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21789. const y = iy * segmentHeight - heightHalf;
  21790. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21791. const x = ix * segmentWidth - widthHalf;
  21792. // set values to correct vector component
  21793. vector[ u ] = x * udir;
  21794. vector[ v ] = y * vdir;
  21795. vector[ w ] = depthHalf;
  21796. // now apply vector to vertex buffer
  21797. vertices.push( vector.x, vector.y, vector.z );
  21798. // set values to correct vector component
  21799. vector[ u ] = 0;
  21800. vector[ v ] = 0;
  21801. vector[ w ] = depth > 0 ? 1 : -1;
  21802. // now apply vector to normal buffer
  21803. normals.push( vector.x, vector.y, vector.z );
  21804. // uvs
  21805. uvs.push( ix / gridX );
  21806. uvs.push( 1 - ( iy / gridY ) );
  21807. // counters
  21808. vertexCounter += 1;
  21809. }
  21810. }
  21811. // indices
  21812. // 1. you need three indices to draw a single face
  21813. // 2. a single segment consists of two faces
  21814. // 3. so we need to generate six (2*3) indices per segment
  21815. for ( let iy = 0; iy < gridY; iy ++ ) {
  21816. for ( let ix = 0; ix < gridX; ix ++ ) {
  21817. const a = numberOfVertices + ix + gridX1 * iy;
  21818. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21819. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21820. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21821. // faces
  21822. indices.push( a, b, d );
  21823. indices.push( b, c, d );
  21824. // increase counter
  21825. groupCount += 6;
  21826. }
  21827. }
  21828. // add a group to the geometry. this will ensure multi material support
  21829. scope.addGroup( groupStart, groupCount, materialIndex );
  21830. // calculate new start value for groups
  21831. groupStart += groupCount;
  21832. // update total number of vertices
  21833. numberOfVertices += vertexCounter;
  21834. }
  21835. }
  21836. copy( source ) {
  21837. super.copy( source );
  21838. this.parameters = Object.assign( {}, source.parameters );
  21839. return this;
  21840. }
  21841. /**
  21842. * Factory method for creating an instance of this class from the given
  21843. * JSON object.
  21844. *
  21845. * @param {Object} data - A JSON object representing the serialized geometry.
  21846. * @return {BoxGeometry} A new instance.
  21847. */
  21848. static fromJSON( data ) {
  21849. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  21850. }
  21851. }
  21852. /**
  21853. * A geometry class for representing a capsule.
  21854. *
  21855. * ```js
  21856. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  21857. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21858. * const capsule = new THREE.Mesh( geometry, material );
  21859. * scene.add( capsule );
  21860. * ```
  21861. *
  21862. * @augments BufferGeometry
  21863. * @demo scenes/geometry-browser.html#CapsuleGeometry
  21864. */
  21865. class CapsuleGeometry extends BufferGeometry {
  21866. /**
  21867. * Constructs a new capsule geometry.
  21868. *
  21869. * @param {number} [radius=1] - Radius of the capsule.
  21870. * @param {number} [height=1] - Height of the middle section.
  21871. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  21872. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  21873. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  21874. */
  21875. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  21876. super();
  21877. this.type = 'CapsuleGeometry';
  21878. /**
  21879. * Holds the constructor parameters that have been
  21880. * used to generate the geometry. Any modification
  21881. * after instantiation does not change the geometry.
  21882. *
  21883. * @type {Object}
  21884. */
  21885. this.parameters = {
  21886. radius: radius,
  21887. height: height,
  21888. capSegments: capSegments,
  21889. radialSegments: radialSegments,
  21890. heightSegments: heightSegments,
  21891. };
  21892. height = Math.max( 0, height );
  21893. capSegments = Math.max( 1, Math.floor( capSegments ) );
  21894. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  21895. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  21896. // buffers
  21897. const indices = [];
  21898. const vertices = [];
  21899. const normals = [];
  21900. const uvs = [];
  21901. // helper variables
  21902. const halfHeight = height / 2;
  21903. const capArcLength = ( Math.PI / 2 ) * radius;
  21904. const cylinderPartLength = height;
  21905. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  21906. const numVerticalSegments = capSegments * 2 + heightSegments;
  21907. const verticesPerRow = radialSegments + 1;
  21908. const normal = new Vector3();
  21909. const vertex = new Vector3();
  21910. // generate vertices, normals, and uvs
  21911. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  21912. let currentArcLength = 0;
  21913. let profileY = 0;
  21914. let profileRadius = 0;
  21915. let normalYComponent = 0;
  21916. if ( iy <= capSegments ) {
  21917. // bottom cap
  21918. const segmentProgress = iy / capSegments;
  21919. const angle = ( segmentProgress * Math.PI ) / 2;
  21920. profileY = - halfHeight - radius * Math.cos( angle );
  21921. profileRadius = radius * Math.sin( angle );
  21922. normalYComponent = - radius * Math.cos( angle );
  21923. currentArcLength = segmentProgress * capArcLength;
  21924. } else if ( iy <= capSegments + heightSegments ) {
  21925. // middle section
  21926. const segmentProgress = ( iy - capSegments ) / heightSegments;
  21927. profileY = - halfHeight + segmentProgress * height;
  21928. profileRadius = radius;
  21929. normalYComponent = 0;
  21930. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  21931. } else {
  21932. // top cap
  21933. const segmentProgress =
  21934. ( iy - capSegments - heightSegments ) / capSegments;
  21935. const angle = ( segmentProgress * Math.PI ) / 2;
  21936. profileY = halfHeight + radius * Math.sin( angle );
  21937. profileRadius = radius * Math.cos( angle );
  21938. normalYComponent = radius * Math.sin( angle );
  21939. currentArcLength =
  21940. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  21941. }
  21942. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  21943. // special case for the poles
  21944. let uOffset = 0;
  21945. if ( iy === 0 ) {
  21946. uOffset = 0.5 / radialSegments;
  21947. } else if ( iy === numVerticalSegments ) {
  21948. uOffset = -0.5 / radialSegments;
  21949. }
  21950. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  21951. const u = ix / radialSegments;
  21952. const theta = u * Math.PI * 2;
  21953. const sinTheta = Math.sin( theta );
  21954. const cosTheta = Math.cos( theta );
  21955. // vertex
  21956. vertex.x = - profileRadius * cosTheta;
  21957. vertex.y = profileY;
  21958. vertex.z = profileRadius * sinTheta;
  21959. vertices.push( vertex.x, vertex.y, vertex.z );
  21960. // normal
  21961. normal.set(
  21962. - profileRadius * cosTheta,
  21963. normalYComponent,
  21964. profileRadius * sinTheta
  21965. );
  21966. normal.normalize();
  21967. normals.push( normal.x, normal.y, normal.z );
  21968. // uv
  21969. uvs.push( u + uOffset, v );
  21970. }
  21971. if ( iy > 0 ) {
  21972. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  21973. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  21974. const i1 = prevIndexRow + ix;
  21975. const i2 = prevIndexRow + ix + 1;
  21976. const i3 = iy * verticesPerRow + ix;
  21977. const i4 = iy * verticesPerRow + ix + 1;
  21978. indices.push( i1, i2, i3 );
  21979. indices.push( i2, i4, i3 );
  21980. }
  21981. }
  21982. }
  21983. // build geometry
  21984. this.setIndex( indices );
  21985. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21986. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21987. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21988. }
  21989. copy( source ) {
  21990. super.copy( source );
  21991. this.parameters = Object.assign( {}, source.parameters );
  21992. return this;
  21993. }
  21994. /**
  21995. * Factory method for creating an instance of this class from the given
  21996. * JSON object.
  21997. *
  21998. * @param {Object} data - A JSON object representing the serialized geometry.
  21999. * @return {CapsuleGeometry} A new instance.
  22000. */
  22001. static fromJSON( data ) {
  22002. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22003. }
  22004. }
  22005. /**
  22006. * A simple shape of Euclidean geometry. It is constructed from a
  22007. * number of triangular segments that are oriented around a central point and
  22008. * extend as far out as a given radius. It is built counter-clockwise from a
  22009. * start angle and a given central angle. It can also be used to create
  22010. * regular polygons, where the number of segments determines the number of
  22011. * sides.
  22012. *
  22013. * ```js
  22014. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22015. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22016. * const circle = new THREE.Mesh( geometry, material );
  22017. * scene.add( circle )
  22018. * ```
  22019. *
  22020. * @augments BufferGeometry
  22021. * @demo scenes/geometry-browser.html#CircleGeometry
  22022. */
  22023. class CircleGeometry extends BufferGeometry {
  22024. /**
  22025. * Constructs a new circle geometry.
  22026. *
  22027. * @param {number} [radius=1] - Radius of the circle.
  22028. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22029. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22030. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22031. * of the circular sector in radians. The default value results in a complete circle.
  22032. */
  22033. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22034. super();
  22035. this.type = 'CircleGeometry';
  22036. /**
  22037. * Holds the constructor parameters that have been
  22038. * used to generate the geometry. Any modification
  22039. * after instantiation does not change the geometry.
  22040. *
  22041. * @type {Object}
  22042. */
  22043. this.parameters = {
  22044. radius: radius,
  22045. segments: segments,
  22046. thetaStart: thetaStart,
  22047. thetaLength: thetaLength
  22048. };
  22049. segments = Math.max( 3, segments );
  22050. // buffers
  22051. const indices = [];
  22052. const vertices = [];
  22053. const normals = [];
  22054. const uvs = [];
  22055. // helper variables
  22056. const vertex = new Vector3();
  22057. const uv = new Vector2();
  22058. // center point
  22059. vertices.push( 0, 0, 0 );
  22060. normals.push( 0, 0, 1 );
  22061. uvs.push( 0.5, 0.5 );
  22062. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22063. const segment = thetaStart + s / segments * thetaLength;
  22064. // vertex
  22065. vertex.x = radius * Math.cos( segment );
  22066. vertex.y = radius * Math.sin( segment );
  22067. vertices.push( vertex.x, vertex.y, vertex.z );
  22068. // normal
  22069. normals.push( 0, 0, 1 );
  22070. // uvs
  22071. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22072. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22073. uvs.push( uv.x, uv.y );
  22074. }
  22075. // indices
  22076. for ( let i = 1; i <= segments; i ++ ) {
  22077. indices.push( i, i + 1, 0 );
  22078. }
  22079. // build geometry
  22080. this.setIndex( indices );
  22081. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22082. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22083. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22084. }
  22085. copy( source ) {
  22086. super.copy( source );
  22087. this.parameters = Object.assign( {}, source.parameters );
  22088. return this;
  22089. }
  22090. /**
  22091. * Factory method for creating an instance of this class from the given
  22092. * JSON object.
  22093. *
  22094. * @param {Object} data - A JSON object representing the serialized geometry.
  22095. * @return {CircleGeometry} A new instance.
  22096. */
  22097. static fromJSON( data ) {
  22098. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22099. }
  22100. }
  22101. /**
  22102. * A geometry class for representing a cylinder.
  22103. *
  22104. * ```js
  22105. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22106. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22107. * const cylinder = new THREE.Mesh( geometry, material );
  22108. * scene.add( cylinder );
  22109. * ```
  22110. *
  22111. * @augments BufferGeometry
  22112. * @demo scenes/geometry-browser.html#CylinderGeometry
  22113. */
  22114. class CylinderGeometry extends BufferGeometry {
  22115. /**
  22116. * Constructs a new cylinder geometry.
  22117. *
  22118. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22119. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22120. * @param {number} [height=1] - Height of the cylinder.
  22121. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22122. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22123. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22124. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22125. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22126. * The default value results in a complete cylinder.
  22127. */
  22128. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22129. super();
  22130. this.type = 'CylinderGeometry';
  22131. /**
  22132. * Holds the constructor parameters that have been
  22133. * used to generate the geometry. Any modification
  22134. * after instantiation does not change the geometry.
  22135. *
  22136. * @type {Object}
  22137. */
  22138. this.parameters = {
  22139. radiusTop: radiusTop,
  22140. radiusBottom: radiusBottom,
  22141. height: height,
  22142. radialSegments: radialSegments,
  22143. heightSegments: heightSegments,
  22144. openEnded: openEnded,
  22145. thetaStart: thetaStart,
  22146. thetaLength: thetaLength
  22147. };
  22148. const scope = this;
  22149. radialSegments = Math.floor( radialSegments );
  22150. heightSegments = Math.floor( heightSegments );
  22151. // buffers
  22152. const indices = [];
  22153. const vertices = [];
  22154. const normals = [];
  22155. const uvs = [];
  22156. // helper variables
  22157. let index = 0;
  22158. const indexArray = [];
  22159. const halfHeight = height / 2;
  22160. let groupStart = 0;
  22161. // generate geometry
  22162. generateTorso();
  22163. if ( openEnded === false ) {
  22164. if ( radiusTop > 0 ) generateCap( true );
  22165. if ( radiusBottom > 0 ) generateCap( false );
  22166. }
  22167. // build geometry
  22168. this.setIndex( indices );
  22169. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22170. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22171. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22172. function generateTorso() {
  22173. const normal = new Vector3();
  22174. const vertex = new Vector3();
  22175. let groupCount = 0;
  22176. // this will be used to calculate the normal
  22177. const slope = ( radiusBottom - radiusTop ) / height;
  22178. // generate vertices, normals and uvs
  22179. for ( let y = 0; y <= heightSegments; y ++ ) {
  22180. const indexRow = [];
  22181. const v = y / heightSegments;
  22182. // calculate the radius of the current row
  22183. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22184. for ( let x = 0; x <= radialSegments; x ++ ) {
  22185. const u = x / radialSegments;
  22186. const theta = u * thetaLength + thetaStart;
  22187. const sinTheta = Math.sin( theta );
  22188. const cosTheta = Math.cos( theta );
  22189. // vertex
  22190. vertex.x = radius * sinTheta;
  22191. vertex.y = - v * height + halfHeight;
  22192. vertex.z = radius * cosTheta;
  22193. vertices.push( vertex.x, vertex.y, vertex.z );
  22194. // normal
  22195. normal.set( sinTheta, slope, cosTheta ).normalize();
  22196. normals.push( normal.x, normal.y, normal.z );
  22197. // uv
  22198. uvs.push( u, 1 - v );
  22199. // save index of vertex in respective row
  22200. indexRow.push( index ++ );
  22201. }
  22202. // now save vertices of the row in our index array
  22203. indexArray.push( indexRow );
  22204. }
  22205. // generate indices
  22206. for ( let x = 0; x < radialSegments; x ++ ) {
  22207. for ( let y = 0; y < heightSegments; y ++ ) {
  22208. // we use the index array to access the correct indices
  22209. const a = indexArray[ y ][ x ];
  22210. const b = indexArray[ y + 1 ][ x ];
  22211. const c = indexArray[ y + 1 ][ x + 1 ];
  22212. const d = indexArray[ y ][ x + 1 ];
  22213. // faces
  22214. if ( radiusTop > 0 || y !== 0 ) {
  22215. indices.push( a, b, d );
  22216. groupCount += 3;
  22217. }
  22218. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22219. indices.push( b, c, d );
  22220. groupCount += 3;
  22221. }
  22222. }
  22223. }
  22224. // add a group to the geometry. this will ensure multi material support
  22225. scope.addGroup( groupStart, groupCount, 0 );
  22226. // calculate new start value for groups
  22227. groupStart += groupCount;
  22228. }
  22229. function generateCap( top ) {
  22230. // save the index of the first center vertex
  22231. const centerIndexStart = index;
  22232. const uv = new Vector2();
  22233. const vertex = new Vector3();
  22234. let groupCount = 0;
  22235. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22236. const sign = ( top === true ) ? 1 : -1;
  22237. // first we generate the center vertex data of the cap.
  22238. // because the geometry needs one set of uvs per face,
  22239. // we must generate a center vertex per face/segment
  22240. for ( let x = 1; x <= radialSegments; x ++ ) {
  22241. // vertex
  22242. vertices.push( 0, halfHeight * sign, 0 );
  22243. // normal
  22244. normals.push( 0, sign, 0 );
  22245. // uv
  22246. uvs.push( 0.5, 0.5 );
  22247. // increase index
  22248. index ++;
  22249. }
  22250. // save the index of the last center vertex
  22251. const centerIndexEnd = index;
  22252. // now we generate the surrounding vertices, normals and uvs
  22253. for ( let x = 0; x <= radialSegments; x ++ ) {
  22254. const u = x / radialSegments;
  22255. const theta = u * thetaLength + thetaStart;
  22256. const cosTheta = Math.cos( theta );
  22257. const sinTheta = Math.sin( theta );
  22258. // vertex
  22259. vertex.x = radius * sinTheta;
  22260. vertex.y = halfHeight * sign;
  22261. vertex.z = radius * cosTheta;
  22262. vertices.push( vertex.x, vertex.y, vertex.z );
  22263. // normal
  22264. normals.push( 0, sign, 0 );
  22265. // uv
  22266. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22267. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22268. uvs.push( uv.x, uv.y );
  22269. // increase index
  22270. index ++;
  22271. }
  22272. // generate indices
  22273. for ( let x = 0; x < radialSegments; x ++ ) {
  22274. const c = centerIndexStart + x;
  22275. const i = centerIndexEnd + x;
  22276. if ( top === true ) {
  22277. // face top
  22278. indices.push( i, i + 1, c );
  22279. } else {
  22280. // face bottom
  22281. indices.push( i + 1, i, c );
  22282. }
  22283. groupCount += 3;
  22284. }
  22285. // add a group to the geometry. this will ensure multi material support
  22286. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22287. // calculate new start value for groups
  22288. groupStart += groupCount;
  22289. }
  22290. }
  22291. copy( source ) {
  22292. super.copy( source );
  22293. this.parameters = Object.assign( {}, source.parameters );
  22294. return this;
  22295. }
  22296. /**
  22297. * Factory method for creating an instance of this class from the given
  22298. * JSON object.
  22299. *
  22300. * @param {Object} data - A JSON object representing the serialized geometry.
  22301. * @return {CylinderGeometry} A new instance.
  22302. */
  22303. static fromJSON( data ) {
  22304. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22305. }
  22306. }
  22307. /**
  22308. * A geometry class for representing a cone.
  22309. *
  22310. * ```js
  22311. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22312. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22313. * const cone = new THREE.Mesh(geometry, material );
  22314. * scene.add( cone );
  22315. * ```
  22316. *
  22317. * @augments CylinderGeometry
  22318. * @demo scenes/geometry-browser.html#ConeGeometry
  22319. */
  22320. class ConeGeometry extends CylinderGeometry {
  22321. /**
  22322. * Constructs a new cone geometry.
  22323. *
  22324. * @param {number} [radius=1] - Radius of the cone base.
  22325. * @param {number} [height=1] - Height of the cone.
  22326. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22327. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22328. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22329. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22330. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22331. * The default value results in a complete cone.
  22332. */
  22333. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22334. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22335. this.type = 'ConeGeometry';
  22336. /**
  22337. * Holds the constructor parameters that have been
  22338. * used to generate the geometry. Any modification
  22339. * after instantiation does not change the geometry.
  22340. *
  22341. * @type {Object}
  22342. */
  22343. this.parameters = {
  22344. radius: radius,
  22345. height: height,
  22346. radialSegments: radialSegments,
  22347. heightSegments: heightSegments,
  22348. openEnded: openEnded,
  22349. thetaStart: thetaStart,
  22350. thetaLength: thetaLength
  22351. };
  22352. }
  22353. /**
  22354. * Factory method for creating an instance of this class from the given
  22355. * JSON object.
  22356. *
  22357. * @param {Object} data - A JSON object representing the serialized geometry.
  22358. * @return {ConeGeometry} A new instance.
  22359. */
  22360. static fromJSON( data ) {
  22361. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22362. }
  22363. }
  22364. /**
  22365. * A polyhedron is a solid in three dimensions with flat faces. This class
  22366. * will take an array of vertices, project them onto a sphere, and then
  22367. * divide them up to the desired level of detail.
  22368. *
  22369. * @augments BufferGeometry
  22370. */
  22371. class PolyhedronGeometry extends BufferGeometry {
  22372. /**
  22373. * Constructs a new polyhedron geometry.
  22374. *
  22375. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22376. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22377. * @param {number} [radius=1] - The radius of the shape.
  22378. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22379. */
  22380. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22381. super();
  22382. this.type = 'PolyhedronGeometry';
  22383. /**
  22384. * Holds the constructor parameters that have been
  22385. * used to generate the geometry. Any modification
  22386. * after instantiation does not change the geometry.
  22387. *
  22388. * @type {Object}
  22389. */
  22390. this.parameters = {
  22391. vertices: vertices,
  22392. indices: indices,
  22393. radius: radius,
  22394. detail: detail
  22395. };
  22396. // default buffer data
  22397. const vertexBuffer = [];
  22398. const uvBuffer = [];
  22399. // the subdivision creates the vertex buffer data
  22400. subdivide( detail );
  22401. // all vertices should lie on a conceptual sphere with a given radius
  22402. applyRadius( radius );
  22403. // finally, create the uv data
  22404. generateUVs();
  22405. // build non-indexed geometry
  22406. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22407. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22408. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22409. if ( detail === 0 ) {
  22410. this.computeVertexNormals(); // flat normals
  22411. } else {
  22412. this.normalizeNormals(); // smooth normals
  22413. }
  22414. // helper functions
  22415. function subdivide( detail ) {
  22416. const a = new Vector3();
  22417. const b = new Vector3();
  22418. const c = new Vector3();
  22419. // iterate over all faces and apply a subdivision with the given detail value
  22420. for ( let i = 0; i < indices.length; i += 3 ) {
  22421. // get the vertices of the face
  22422. getVertexByIndex( indices[ i + 0 ], a );
  22423. getVertexByIndex( indices[ i + 1 ], b );
  22424. getVertexByIndex( indices[ i + 2 ], c );
  22425. // perform subdivision
  22426. subdivideFace( a, b, c, detail );
  22427. }
  22428. }
  22429. function subdivideFace( a, b, c, detail ) {
  22430. const cols = detail + 1;
  22431. // we use this multidimensional array as a data structure for creating the subdivision
  22432. const v = [];
  22433. // construct all of the vertices for this subdivision
  22434. for ( let i = 0; i <= cols; i ++ ) {
  22435. v[ i ] = [];
  22436. const aj = a.clone().lerp( c, i / cols );
  22437. const bj = b.clone().lerp( c, i / cols );
  22438. const rows = cols - i;
  22439. for ( let j = 0; j <= rows; j ++ ) {
  22440. if ( j === 0 && i === cols ) {
  22441. v[ i ][ j ] = aj;
  22442. } else {
  22443. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22444. }
  22445. }
  22446. }
  22447. // construct all of the faces
  22448. for ( let i = 0; i < cols; i ++ ) {
  22449. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22450. const k = Math.floor( j / 2 );
  22451. if ( j % 2 === 0 ) {
  22452. pushVertex( v[ i ][ k + 1 ] );
  22453. pushVertex( v[ i + 1 ][ k ] );
  22454. pushVertex( v[ i ][ k ] );
  22455. } else {
  22456. pushVertex( v[ i ][ k + 1 ] );
  22457. pushVertex( v[ i + 1 ][ k + 1 ] );
  22458. pushVertex( v[ i + 1 ][ k ] );
  22459. }
  22460. }
  22461. }
  22462. }
  22463. function applyRadius( radius ) {
  22464. const vertex = new Vector3();
  22465. // iterate over the entire buffer and apply the radius to each vertex
  22466. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22467. vertex.x = vertexBuffer[ i + 0 ];
  22468. vertex.y = vertexBuffer[ i + 1 ];
  22469. vertex.z = vertexBuffer[ i + 2 ];
  22470. vertex.normalize().multiplyScalar( radius );
  22471. vertexBuffer[ i + 0 ] = vertex.x;
  22472. vertexBuffer[ i + 1 ] = vertex.y;
  22473. vertexBuffer[ i + 2 ] = vertex.z;
  22474. }
  22475. }
  22476. function generateUVs() {
  22477. const vertex = new Vector3();
  22478. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22479. vertex.x = vertexBuffer[ i + 0 ];
  22480. vertex.y = vertexBuffer[ i + 1 ];
  22481. vertex.z = vertexBuffer[ i + 2 ];
  22482. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22483. const v = inclination( vertex ) / Math.PI + 0.5;
  22484. uvBuffer.push( u, 1 - v );
  22485. }
  22486. correctUVs();
  22487. correctSeam();
  22488. }
  22489. function correctSeam() {
  22490. // handle case when face straddles the seam, see #3269
  22491. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22492. // uv data of a single face
  22493. const x0 = uvBuffer[ i + 0 ];
  22494. const x1 = uvBuffer[ i + 2 ];
  22495. const x2 = uvBuffer[ i + 4 ];
  22496. const max = Math.max( x0, x1, x2 );
  22497. const min = Math.min( x0, x1, x2 );
  22498. // 0.9 is somewhat arbitrary
  22499. if ( max > 0.9 && min < 0.1 ) {
  22500. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22501. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22502. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22503. }
  22504. }
  22505. }
  22506. function pushVertex( vertex ) {
  22507. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22508. }
  22509. function getVertexByIndex( index, vertex ) {
  22510. const stride = index * 3;
  22511. vertex.x = vertices[ stride + 0 ];
  22512. vertex.y = vertices[ stride + 1 ];
  22513. vertex.z = vertices[ stride + 2 ];
  22514. }
  22515. function correctUVs() {
  22516. const a = new Vector3();
  22517. const b = new Vector3();
  22518. const c = new Vector3();
  22519. const centroid = new Vector3();
  22520. const uvA = new Vector2();
  22521. const uvB = new Vector2();
  22522. const uvC = new Vector2();
  22523. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22524. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22525. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22526. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22527. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22528. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22529. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22530. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22531. const azi = azimuth( centroid );
  22532. correctUV( uvA, j + 0, a, azi );
  22533. correctUV( uvB, j + 2, b, azi );
  22534. correctUV( uvC, j + 4, c, azi );
  22535. }
  22536. }
  22537. function correctUV( uv, stride, vector, azimuth ) {
  22538. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22539. uvBuffer[ stride ] = uv.x - 1;
  22540. }
  22541. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22542. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22543. }
  22544. }
  22545. // Angle around the Y axis, counter-clockwise when looking from above.
  22546. function azimuth( vector ) {
  22547. return Math.atan2( vector.z, - vector.x );
  22548. }
  22549. // Angle above the XZ plane.
  22550. function inclination( vector ) {
  22551. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22552. }
  22553. }
  22554. copy( source ) {
  22555. super.copy( source );
  22556. this.parameters = Object.assign( {}, source.parameters );
  22557. return this;
  22558. }
  22559. /**
  22560. * Factory method for creating an instance of this class from the given
  22561. * JSON object.
  22562. *
  22563. * @param {Object} data - A JSON object representing the serialized geometry.
  22564. * @return {PolyhedronGeometry} A new instance.
  22565. */
  22566. static fromJSON( data ) {
  22567. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  22568. }
  22569. }
  22570. /**
  22571. * A geometry class for representing a dodecahedron.
  22572. *
  22573. * ```js
  22574. * const geometry = new THREE.DodecahedronGeometry();
  22575. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22576. * const dodecahedron = new THREE.Mesh( geometry, material );
  22577. * scene.add( dodecahedron );
  22578. * ```
  22579. *
  22580. * @augments PolyhedronGeometry
  22581. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  22582. */
  22583. class DodecahedronGeometry extends PolyhedronGeometry {
  22584. /**
  22585. * Constructs a new dodecahedron geometry.
  22586. *
  22587. * @param {number} [radius=1] - Radius of the dodecahedron.
  22588. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22589. */
  22590. constructor( radius = 1, detail = 0 ) {
  22591. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22592. const r = 1 / t;
  22593. const vertices = [
  22594. // (±1, ±1, ±1)
  22595. -1, -1, -1, -1, -1, 1,
  22596. -1, 1, -1, -1, 1, 1,
  22597. 1, -1, -1, 1, -1, 1,
  22598. 1, 1, -1, 1, 1, 1,
  22599. // (0, ±1/φ, ±φ)
  22600. 0, - r, - t, 0, - r, t,
  22601. 0, r, - t, 0, r, t,
  22602. // (±1/φ, ±φ, 0)
  22603. - r, - t, 0, - r, t, 0,
  22604. r, - t, 0, r, t, 0,
  22605. // (±φ, 0, ±1/φ)
  22606. - t, 0, - r, t, 0, - r,
  22607. - t, 0, r, t, 0, r
  22608. ];
  22609. const indices = [
  22610. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22611. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22612. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22613. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22614. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22615. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22616. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22617. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22618. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22619. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22620. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22621. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22622. ];
  22623. super( vertices, indices, radius, detail );
  22624. this.type = 'DodecahedronGeometry';
  22625. /**
  22626. * Holds the constructor parameters that have been
  22627. * used to generate the geometry. Any modification
  22628. * after instantiation does not change the geometry.
  22629. *
  22630. * @type {Object}
  22631. */
  22632. this.parameters = {
  22633. radius: radius,
  22634. detail: detail
  22635. };
  22636. }
  22637. /**
  22638. * Factory method for creating an instance of this class from the given
  22639. * JSON object.
  22640. *
  22641. * @param {Object} data - A JSON object representing the serialized geometry.
  22642. * @return {DodecahedronGeometry} A new instance.
  22643. */
  22644. static fromJSON( data ) {
  22645. return new DodecahedronGeometry( data.radius, data.detail );
  22646. }
  22647. }
  22648. const _v0 = /*@__PURE__*/ new Vector3();
  22649. const _v1$1 = /*@__PURE__*/ new Vector3();
  22650. const _normal = /*@__PURE__*/ new Vector3();
  22651. const _triangle = /*@__PURE__*/ new Triangle();
  22652. /**
  22653. * Can be used as a helper object to view the edges of a geometry.
  22654. *
  22655. * ```js
  22656. * const geometry = new THREE.BoxGeometry();
  22657. * const edges = new THREE.EdgesGeometry( geometry );
  22658. * const line = new THREE.LineSegments( edges );
  22659. * scene.add( line );
  22660. * ```
  22661. *
  22662. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22663. *
  22664. * @augments BufferGeometry
  22665. */
  22666. class EdgesGeometry extends BufferGeometry {
  22667. /**
  22668. * Constructs a new edges geometry.
  22669. *
  22670. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22671. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22672. * between the face normals of the adjoining faces exceeds this value.
  22673. */
  22674. constructor( geometry = null, thresholdAngle = 1 ) {
  22675. super();
  22676. this.type = 'EdgesGeometry';
  22677. /**
  22678. * Holds the constructor parameters that have been
  22679. * used to generate the geometry. Any modification
  22680. * after instantiation does not change the geometry.
  22681. *
  22682. * @type {Object}
  22683. */
  22684. this.parameters = {
  22685. geometry: geometry,
  22686. thresholdAngle: thresholdAngle
  22687. };
  22688. if ( geometry !== null ) {
  22689. const precisionPoints = 4;
  22690. const precision = Math.pow( 10, precisionPoints );
  22691. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22692. const indexAttr = geometry.getIndex();
  22693. const positionAttr = geometry.getAttribute( 'position' );
  22694. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22695. const indexArr = [ 0, 0, 0 ];
  22696. const vertKeys = [ 'a', 'b', 'c' ];
  22697. const hashes = new Array( 3 );
  22698. const edgeData = {};
  22699. const vertices = [];
  22700. for ( let i = 0; i < indexCount; i += 3 ) {
  22701. if ( indexAttr ) {
  22702. indexArr[ 0 ] = indexAttr.getX( i );
  22703. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22704. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22705. } else {
  22706. indexArr[ 0 ] = i;
  22707. indexArr[ 1 ] = i + 1;
  22708. indexArr[ 2 ] = i + 2;
  22709. }
  22710. const { a, b, c } = _triangle;
  22711. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22712. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22713. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22714. _triangle.getNormal( _normal );
  22715. // create hashes for the edge from the vertices
  22716. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22717. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22718. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22719. // skip degenerate triangles
  22720. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22721. continue;
  22722. }
  22723. // iterate over every edge
  22724. for ( let j = 0; j < 3; j ++ ) {
  22725. // get the first and next vertex making up the edge
  22726. const jNext = ( j + 1 ) % 3;
  22727. const vecHash0 = hashes[ j ];
  22728. const vecHash1 = hashes[ jNext ];
  22729. const v0 = _triangle[ vertKeys[ j ] ];
  22730. const v1 = _triangle[ vertKeys[ jNext ] ];
  22731. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22732. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22733. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22734. // if we found a sibling edge add it into the vertex array if
  22735. // it meets the angle threshold and delete the edge from the map.
  22736. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22737. vertices.push( v0.x, v0.y, v0.z );
  22738. vertices.push( v1.x, v1.y, v1.z );
  22739. }
  22740. edgeData[ reverseHash ] = null;
  22741. } else if ( ! ( hash in edgeData ) ) {
  22742. // if we've already got an edge here then skip adding a new one
  22743. edgeData[ hash ] = {
  22744. index0: indexArr[ j ],
  22745. index1: indexArr[ jNext ],
  22746. normal: _normal.clone(),
  22747. };
  22748. }
  22749. }
  22750. }
  22751. // iterate over all remaining, unmatched edges and add them to the vertex array
  22752. for ( const key in edgeData ) {
  22753. if ( edgeData[ key ] ) {
  22754. const { index0, index1 } = edgeData[ key ];
  22755. _v0.fromBufferAttribute( positionAttr, index0 );
  22756. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22757. vertices.push( _v0.x, _v0.y, _v0.z );
  22758. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22759. }
  22760. }
  22761. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22762. }
  22763. }
  22764. copy( source ) {
  22765. super.copy( source );
  22766. this.parameters = Object.assign( {}, source.parameters );
  22767. return this;
  22768. }
  22769. }
  22770. /**
  22771. * An abstract base class for creating an analytic curve object that contains methods
  22772. * for interpolation.
  22773. *
  22774. * @abstract
  22775. */
  22776. class Curve {
  22777. /**
  22778. * Constructs a new curve.
  22779. */
  22780. constructor() {
  22781. /**
  22782. * The type property is used for detecting the object type
  22783. * in context of serialization/deserialization.
  22784. *
  22785. * @type {string}
  22786. * @readonly
  22787. */
  22788. this.type = 'Curve';
  22789. /**
  22790. * This value determines the amount of divisions when calculating the
  22791. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  22792. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  22793. * recommended to increase the value of this property if the curve is very large.
  22794. *
  22795. * @type {number}
  22796. * @default 200
  22797. */
  22798. this.arcLengthDivisions = 200;
  22799. /**
  22800. * Must be set to `true` if the curve parameters have changed.
  22801. *
  22802. * @type {boolean}
  22803. * @default false
  22804. */
  22805. this.needsUpdate = false;
  22806. /**
  22807. * An internal cache that holds precomputed curve length values.
  22808. *
  22809. * @private
  22810. * @type {?Array<number>}
  22811. * @default null
  22812. */
  22813. this.cacheArcLengths = null;
  22814. }
  22815. /**
  22816. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22817. * for the given interpolation factor.
  22818. *
  22819. * @abstract
  22820. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22821. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22822. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22823. */
  22824. getPoint( /* t, optionalTarget */ ) {
  22825. warn( 'Curve: .getPoint() not implemented.' );
  22826. }
  22827. /**
  22828. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  22829. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  22830. * of the curve which equidistant samples.
  22831. *
  22832. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  22833. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22834. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  22835. */
  22836. getPointAt( u, optionalTarget ) {
  22837. const t = this.getUtoTmapping( u );
  22838. return this.getPoint( t, optionalTarget );
  22839. }
  22840. /**
  22841. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  22842. * the curve shape.
  22843. *
  22844. * @param {number} [divisions=5] - The number of divisions.
  22845. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22846. */
  22847. getPoints( divisions = 5 ) {
  22848. const points = [];
  22849. for ( let d = 0; d <= divisions; d ++ ) {
  22850. points.push( this.getPoint( d / divisions ) );
  22851. }
  22852. return points;
  22853. }
  22854. // Get sequence of points using getPointAt( u )
  22855. /**
  22856. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  22857. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  22858. * curve.
  22859. *
  22860. * @param {number} [divisions=5] - The number of divisions.
  22861. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  22862. */
  22863. getSpacedPoints( divisions = 5 ) {
  22864. const points = [];
  22865. for ( let d = 0; d <= divisions; d ++ ) {
  22866. points.push( this.getPointAt( d / divisions ) );
  22867. }
  22868. return points;
  22869. }
  22870. /**
  22871. * Returns the total arc length of the curve.
  22872. *
  22873. * @return {number} The length of the curve.
  22874. */
  22875. getLength() {
  22876. const lengths = this.getLengths();
  22877. return lengths[ lengths.length - 1 ];
  22878. }
  22879. /**
  22880. * Returns an array of cumulative segment lengths of the curve.
  22881. *
  22882. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  22883. * @return {Array<number>} An array holding the cumulative segment lengths.
  22884. */
  22885. getLengths( divisions = this.arcLengthDivisions ) {
  22886. if ( this.cacheArcLengths &&
  22887. ( this.cacheArcLengths.length === divisions + 1 ) &&
  22888. ! this.needsUpdate ) {
  22889. return this.cacheArcLengths;
  22890. }
  22891. this.needsUpdate = false;
  22892. const cache = [];
  22893. let current, last = this.getPoint( 0 );
  22894. let sum = 0;
  22895. cache.push( 0 );
  22896. for ( let p = 1; p <= divisions; p ++ ) {
  22897. current = this.getPoint( p / divisions );
  22898. sum += current.distanceTo( last );
  22899. cache.push( sum );
  22900. last = current;
  22901. }
  22902. this.cacheArcLengths = cache;
  22903. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22904. }
  22905. /**
  22906. * Update the cumulative segment distance cache. The method must be called
  22907. * every time curve parameters are changed. If an updated curve is part of a
  22908. * composed curve like {@link CurvePath}, this method must be called on the
  22909. * composed curve, too.
  22910. */
  22911. updateArcLengths() {
  22912. this.needsUpdate = true;
  22913. this.getLengths();
  22914. }
  22915. /**
  22916. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  22917. * interpolation factor in the same range that can be ued to sample equidistant points
  22918. * from a curve.
  22919. *
  22920. * @param {number} u - The interpolation factor.
  22921. * @param {?number} distance - An optional distance on the curve.
  22922. * @return {number} The updated interpolation factor.
  22923. */
  22924. getUtoTmapping( u, distance = null ) {
  22925. const arcLengths = this.getLengths();
  22926. let i = 0;
  22927. const il = arcLengths.length;
  22928. let targetArcLength; // The targeted u distance value to get
  22929. if ( distance ) {
  22930. targetArcLength = distance;
  22931. } else {
  22932. targetArcLength = u * arcLengths[ il - 1 ];
  22933. }
  22934. // binary search for the index with largest value smaller than target u distance
  22935. let low = 0, high = il - 1, comparison;
  22936. while ( low <= high ) {
  22937. 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
  22938. comparison = arcLengths[ i ] - targetArcLength;
  22939. if ( comparison < 0 ) {
  22940. low = i + 1;
  22941. } else if ( comparison > 0 ) {
  22942. high = i - 1;
  22943. } else {
  22944. high = i;
  22945. break;
  22946. // DONE
  22947. }
  22948. }
  22949. i = high;
  22950. if ( arcLengths[ i ] === targetArcLength ) {
  22951. return i / ( il - 1 );
  22952. }
  22953. // we could get finer grain at lengths, or use simple interpolation between two points
  22954. const lengthBefore = arcLengths[ i ];
  22955. const lengthAfter = arcLengths[ i + 1 ];
  22956. const segmentLength = lengthAfter - lengthBefore;
  22957. // determine where we are between the 'before' and 'after' points
  22958. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  22959. // add that fractional amount to t
  22960. const t = ( i + segmentFraction ) / ( il - 1 );
  22961. return t;
  22962. }
  22963. /**
  22964. * Returns a unit vector tangent for the given interpolation factor.
  22965. * If the derived curve does not implement its tangent derivation,
  22966. * two points a small delta apart will be used to find its gradient
  22967. * which seems to give a reasonable approximation.
  22968. *
  22969. * @param {number} t - The interpolation factor.
  22970. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22971. * @return {(Vector2|Vector3)} The tangent vector.
  22972. */
  22973. getTangent( t, optionalTarget ) {
  22974. const delta = 0.0001;
  22975. let t1 = t - delta;
  22976. let t2 = t + delta;
  22977. // Capping in case of danger
  22978. if ( t1 < 0 ) t1 = 0;
  22979. if ( t2 > 1 ) t2 = 1;
  22980. const pt1 = this.getPoint( t1 );
  22981. const pt2 = this.getPoint( t2 );
  22982. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  22983. tangent.copy( pt2 ).sub( pt1 ).normalize();
  22984. return tangent;
  22985. }
  22986. /**
  22987. * Same as {@link Curve#getTangent} but with equidistant samples.
  22988. *
  22989. * @param {number} u - The interpolation factor.
  22990. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  22991. * @return {(Vector2|Vector3)} The tangent vector.
  22992. * @see {@link Curve#getPointAt}
  22993. */
  22994. getTangentAt( u, optionalTarget ) {
  22995. const t = this.getUtoTmapping( u );
  22996. return this.getTangent( t, optionalTarget );
  22997. }
  22998. /**
  22999. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23000. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23001. *
  23002. * @param {number} segments - The number of segments.
  23003. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23004. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23005. */
  23006. computeFrenetFrames( segments, closed = false ) {
  23007. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23008. const normal = new Vector3();
  23009. const tangents = [];
  23010. const normals = [];
  23011. const binormals = [];
  23012. const vec = new Vector3();
  23013. const mat = new Matrix4();
  23014. // compute the tangent vectors for each segment on the curve
  23015. for ( let i = 0; i <= segments; i ++ ) {
  23016. const u = i / segments;
  23017. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23018. }
  23019. // select an initial normal vector perpendicular to the first tangent vector,
  23020. // and in the direction of the minimum tangent xyz component
  23021. normals[ 0 ] = new Vector3();
  23022. binormals[ 0 ] = new Vector3();
  23023. let min = Number.MAX_VALUE;
  23024. const tx = Math.abs( tangents[ 0 ].x );
  23025. const ty = Math.abs( tangents[ 0 ].y );
  23026. const tz = Math.abs( tangents[ 0 ].z );
  23027. if ( tx <= min ) {
  23028. min = tx;
  23029. normal.set( 1, 0, 0 );
  23030. }
  23031. if ( ty <= min ) {
  23032. min = ty;
  23033. normal.set( 0, 1, 0 );
  23034. }
  23035. if ( tz <= min ) {
  23036. normal.set( 0, 0, 1 );
  23037. }
  23038. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23039. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23040. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23041. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23042. for ( let i = 1; i <= segments; i ++ ) {
  23043. normals[ i ] = normals[ i - 1 ].clone();
  23044. binormals[ i ] = binormals[ i - 1 ].clone();
  23045. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23046. if ( vec.length() > Number.EPSILON ) {
  23047. vec.normalize();
  23048. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23049. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23050. }
  23051. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23052. }
  23053. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23054. if ( closed === true ) {
  23055. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23056. theta /= segments;
  23057. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23058. theta = - theta;
  23059. }
  23060. for ( let i = 1; i <= segments; i ++ ) {
  23061. // twist a little...
  23062. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23063. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23064. }
  23065. }
  23066. return {
  23067. tangents: tangents,
  23068. normals: normals,
  23069. binormals: binormals
  23070. };
  23071. }
  23072. /**
  23073. * Returns a new curve with copied values from this instance.
  23074. *
  23075. * @return {Curve} A clone of this instance.
  23076. */
  23077. clone() {
  23078. return new this.constructor().copy( this );
  23079. }
  23080. /**
  23081. * Copies the values of the given curve to this instance.
  23082. *
  23083. * @param {Curve} source - The curve to copy.
  23084. * @return {Curve} A reference to this curve.
  23085. */
  23086. copy( source ) {
  23087. this.arcLengthDivisions = source.arcLengthDivisions;
  23088. return this;
  23089. }
  23090. /**
  23091. * Serializes the curve into JSON.
  23092. *
  23093. * @return {Object} A JSON object representing the serialized curve.
  23094. * @see {@link ObjectLoader#parse}
  23095. */
  23096. toJSON() {
  23097. const data = {
  23098. metadata: {
  23099. version: 4.7,
  23100. type: 'Curve',
  23101. generator: 'Curve.toJSON'
  23102. }
  23103. };
  23104. data.arcLengthDivisions = this.arcLengthDivisions;
  23105. data.type = this.type;
  23106. return data;
  23107. }
  23108. /**
  23109. * Deserializes the curve from the given JSON.
  23110. *
  23111. * @param {Object} json - The JSON holding the serialized curve.
  23112. * @return {Curve} A reference to this curve.
  23113. */
  23114. fromJSON( json ) {
  23115. this.arcLengthDivisions = json.arcLengthDivisions;
  23116. return this;
  23117. }
  23118. }
  23119. /**
  23120. * A curve representing an ellipse.
  23121. *
  23122. * ```js
  23123. * const curve = new THREE.EllipseCurve(
  23124. * 0, 0,
  23125. * 10, 10,
  23126. * 0, 2 * Math.PI,
  23127. * false,
  23128. * 0
  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 ellipse = new THREE.Line( geometry, material );
  23138. * ```
  23139. *
  23140. * @augments Curve
  23141. */
  23142. class EllipseCurve extends Curve {
  23143. /**
  23144. * Constructs a new ellipse curve.
  23145. *
  23146. * @param {number} [aX=0] - The X center of the ellipse.
  23147. * @param {number} [aY=0] - The Y center of the ellipse.
  23148. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23149. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23150. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23151. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23152. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23153. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23154. */
  23155. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23156. super();
  23157. /**
  23158. * This flag can be used for type testing.
  23159. *
  23160. * @type {boolean}
  23161. * @readonly
  23162. * @default true
  23163. */
  23164. this.isEllipseCurve = true;
  23165. this.type = 'EllipseCurve';
  23166. /**
  23167. * The X center of the ellipse.
  23168. *
  23169. * @type {number}
  23170. * @default 0
  23171. */
  23172. this.aX = aX;
  23173. /**
  23174. * The Y center of the ellipse.
  23175. *
  23176. * @type {number}
  23177. * @default 0
  23178. */
  23179. this.aY = aY;
  23180. /**
  23181. * The radius of the ellipse in the x direction.
  23182. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23183. *
  23184. * @type {number}
  23185. * @default 1
  23186. */
  23187. this.xRadius = xRadius;
  23188. /**
  23189. * The radius of the ellipse in the y direction.
  23190. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23191. *
  23192. * @type {number}
  23193. * @default 1
  23194. */
  23195. this.yRadius = yRadius;
  23196. /**
  23197. * The start angle of the curve in radians starting from the positive X axis.
  23198. *
  23199. * @type {number}
  23200. * @default 0
  23201. */
  23202. this.aStartAngle = aStartAngle;
  23203. /**
  23204. * The end angle of the curve in radians starting from the positive X axis.
  23205. *
  23206. * @type {number}
  23207. * @default Math.PI*2
  23208. */
  23209. this.aEndAngle = aEndAngle;
  23210. /**
  23211. * Whether the ellipse is drawn clockwise or not.
  23212. *
  23213. * @type {boolean}
  23214. * @default false
  23215. */
  23216. this.aClockwise = aClockwise;
  23217. /**
  23218. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23219. *
  23220. * @type {number}
  23221. * @default 0
  23222. */
  23223. this.aRotation = aRotation;
  23224. }
  23225. /**
  23226. * Returns a point on the curve.
  23227. *
  23228. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23229. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23230. * @return {Vector2} The position on the curve.
  23231. */
  23232. getPoint( t, optionalTarget = new Vector2() ) {
  23233. const point = optionalTarget;
  23234. const twoPi = Math.PI * 2;
  23235. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23236. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23237. // ensures that deltaAngle is 0 .. 2 PI
  23238. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23239. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23240. if ( deltaAngle < Number.EPSILON ) {
  23241. if ( samePoints ) {
  23242. deltaAngle = 0;
  23243. } else {
  23244. deltaAngle = twoPi;
  23245. }
  23246. }
  23247. if ( this.aClockwise === true && ! samePoints ) {
  23248. if ( deltaAngle === twoPi ) {
  23249. deltaAngle = - twoPi;
  23250. } else {
  23251. deltaAngle = deltaAngle - twoPi;
  23252. }
  23253. }
  23254. const angle = this.aStartAngle + t * deltaAngle;
  23255. let x = this.aX + this.xRadius * Math.cos( angle );
  23256. let y = this.aY + this.yRadius * Math.sin( angle );
  23257. if ( this.aRotation !== 0 ) {
  23258. const cos = Math.cos( this.aRotation );
  23259. const sin = Math.sin( this.aRotation );
  23260. const tx = x - this.aX;
  23261. const ty = y - this.aY;
  23262. // Rotate the point about the center of the ellipse.
  23263. x = tx * cos - ty * sin + this.aX;
  23264. y = tx * sin + ty * cos + this.aY;
  23265. }
  23266. return point.set( x, y );
  23267. }
  23268. copy( source ) {
  23269. super.copy( source );
  23270. this.aX = source.aX;
  23271. this.aY = source.aY;
  23272. this.xRadius = source.xRadius;
  23273. this.yRadius = source.yRadius;
  23274. this.aStartAngle = source.aStartAngle;
  23275. this.aEndAngle = source.aEndAngle;
  23276. this.aClockwise = source.aClockwise;
  23277. this.aRotation = source.aRotation;
  23278. return this;
  23279. }
  23280. toJSON() {
  23281. const data = super.toJSON();
  23282. data.aX = this.aX;
  23283. data.aY = this.aY;
  23284. data.xRadius = this.xRadius;
  23285. data.yRadius = this.yRadius;
  23286. data.aStartAngle = this.aStartAngle;
  23287. data.aEndAngle = this.aEndAngle;
  23288. data.aClockwise = this.aClockwise;
  23289. data.aRotation = this.aRotation;
  23290. return data;
  23291. }
  23292. fromJSON( json ) {
  23293. super.fromJSON( json );
  23294. this.aX = json.aX;
  23295. this.aY = json.aY;
  23296. this.xRadius = json.xRadius;
  23297. this.yRadius = json.yRadius;
  23298. this.aStartAngle = json.aStartAngle;
  23299. this.aEndAngle = json.aEndAngle;
  23300. this.aClockwise = json.aClockwise;
  23301. this.aRotation = json.aRotation;
  23302. return this;
  23303. }
  23304. }
  23305. /**
  23306. * A curve representing an arc.
  23307. *
  23308. * @augments EllipseCurve
  23309. */
  23310. class ArcCurve extends EllipseCurve {
  23311. /**
  23312. * Constructs a new arc curve.
  23313. *
  23314. * @param {number} [aX=0] - The X center of the ellipse.
  23315. * @param {number} [aY=0] - The Y center of the ellipse.
  23316. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23317. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23318. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23319. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23320. */
  23321. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23322. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23323. /**
  23324. * This flag can be used for type testing.
  23325. *
  23326. * @type {boolean}
  23327. * @readonly
  23328. * @default true
  23329. */
  23330. this.isArcCurve = true;
  23331. this.type = 'ArcCurve';
  23332. }
  23333. }
  23334. function CubicPoly() {
  23335. /**
  23336. * Centripetal CatmullRom Curve - which is useful for avoiding
  23337. * cusps and self-intersections in non-uniform catmull rom curves.
  23338. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23339. *
  23340. * curve.type accepts centripetal(default), chordal and catmullrom
  23341. * curve.tension is used for catmullrom which defaults to 0.5
  23342. */
  23343. /*
  23344. Based on an optimized c++ solution in
  23345. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23346. - http://ideone.com/NoEbVM
  23347. This CubicPoly class could be used for reusing some variables and calculations,
  23348. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23349. which can be placed in CurveUtils.
  23350. */
  23351. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23352. /*
  23353. * Compute coefficients for a cubic polynomial
  23354. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23355. * such that
  23356. * p(0) = x0, p(1) = x1
  23357. * and
  23358. * p'(0) = t0, p'(1) = t1.
  23359. */
  23360. function init( x0, x1, t0, t1 ) {
  23361. c0 = x0;
  23362. c1 = t0;
  23363. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23364. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23365. }
  23366. return {
  23367. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23368. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23369. },
  23370. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23371. // compute tangents when parameterized in [t1,t2]
  23372. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23373. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23374. // rescale tangents for parametrization in [0,1]
  23375. t1 *= dt1;
  23376. t2 *= dt1;
  23377. init( x1, x2, t1, t2 );
  23378. },
  23379. calc: function ( t ) {
  23380. const t2 = t * t;
  23381. const t3 = t2 * t;
  23382. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23383. }
  23384. };
  23385. }
  23386. //
  23387. const tmp = /*@__PURE__*/ new Vector3();
  23388. const tmp2 = /*@__PURE__*/ new Vector3();
  23389. const px = /*@__PURE__*/ new CubicPoly();
  23390. const py = /*@__PURE__*/ new CubicPoly();
  23391. const pz = /*@__PURE__*/ new CubicPoly();
  23392. /**
  23393. * A curve representing a Catmull-Rom spline.
  23394. *
  23395. * ```js
  23396. * //Create a closed wavey loop
  23397. * const curve = new THREE.CatmullRomCurve3( [
  23398. * new THREE.Vector3( -10, 0, 10 ),
  23399. * new THREE.Vector3( -5, 5, 5 ),
  23400. * new THREE.Vector3( 0, 0, 0 ),
  23401. * new THREE.Vector3( 5, -5, 5 ),
  23402. * new THREE.Vector3( 10, 0, 10 )
  23403. * ] );
  23404. *
  23405. * const points = curve.getPoints( 50 );
  23406. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23407. *
  23408. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23409. *
  23410. * // Create the final object to add to the scene
  23411. * const curveObject = new THREE.Line( geometry, material );
  23412. * ```
  23413. *
  23414. * @augments Curve
  23415. */
  23416. class CatmullRomCurve3 extends Curve {
  23417. /**
  23418. * Constructs a new Catmull-Rom curve.
  23419. *
  23420. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23421. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23422. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23423. * @param {number} [tension=0.5] - Tension of the curve.
  23424. */
  23425. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23426. super();
  23427. /**
  23428. * This flag can be used for type testing.
  23429. *
  23430. * @type {boolean}
  23431. * @readonly
  23432. * @default true
  23433. */
  23434. this.isCatmullRomCurve3 = true;
  23435. this.type = 'CatmullRomCurve3';
  23436. /**
  23437. * An array of 3D points defining the curve.
  23438. *
  23439. * @type {Array<Vector3>}
  23440. */
  23441. this.points = points;
  23442. /**
  23443. * Whether the curve is closed or not.
  23444. *
  23445. * @type {boolean}
  23446. * @default false
  23447. */
  23448. this.closed = closed;
  23449. /**
  23450. * The curve type.
  23451. *
  23452. * @type {('centripetal'|'chordal'|'catmullrom')}
  23453. * @default 'centripetal'
  23454. */
  23455. this.curveType = curveType;
  23456. /**
  23457. * Tension of the curve.
  23458. *
  23459. * @type {number}
  23460. * @default 0.5
  23461. */
  23462. this.tension = tension;
  23463. }
  23464. /**
  23465. * Returns a point on the curve.
  23466. *
  23467. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23468. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23469. * @return {Vector3} The position on the curve.
  23470. */
  23471. getPoint( t, optionalTarget = new Vector3() ) {
  23472. const point = optionalTarget;
  23473. const points = this.points;
  23474. const l = points.length;
  23475. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23476. let intPoint = Math.floor( p );
  23477. let weight = p - intPoint;
  23478. if ( this.closed ) {
  23479. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23480. } else if ( weight === 0 && intPoint === l - 1 ) {
  23481. intPoint = l - 2;
  23482. weight = 1;
  23483. }
  23484. let p0, p3; // 4 points (p1 & p2 defined below)
  23485. if ( this.closed || intPoint > 0 ) {
  23486. p0 = points[ ( intPoint - 1 ) % l ];
  23487. } else {
  23488. // extrapolate first point
  23489. tmp2.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23490. p0 = tmp2;
  23491. }
  23492. const p1 = points[ intPoint % l ];
  23493. const p2 = points[ ( intPoint + 1 ) % l ];
  23494. if ( this.closed || intPoint + 2 < l ) {
  23495. p3 = points[ ( intPoint + 2 ) % l ];
  23496. } else {
  23497. // extrapolate last point
  23498. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23499. p3 = tmp;
  23500. }
  23501. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23502. // init Centripetal / Chordal Catmull-Rom
  23503. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23504. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23505. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23506. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23507. // safety check for repeated points
  23508. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23509. if ( dt0 < 1e-4 ) dt0 = dt1;
  23510. if ( dt2 < 1e-4 ) dt2 = dt1;
  23511. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23512. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23513. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23514. } else if ( this.curveType === 'catmullrom' ) {
  23515. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23516. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23517. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23518. }
  23519. point.set(
  23520. px.calc( weight ),
  23521. py.calc( weight ),
  23522. pz.calc( weight )
  23523. );
  23524. return point;
  23525. }
  23526. copy( source ) {
  23527. super.copy( source );
  23528. this.points = [];
  23529. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23530. const point = source.points[ i ];
  23531. this.points.push( point.clone() );
  23532. }
  23533. this.closed = source.closed;
  23534. this.curveType = source.curveType;
  23535. this.tension = source.tension;
  23536. return this;
  23537. }
  23538. toJSON() {
  23539. const data = super.toJSON();
  23540. data.points = [];
  23541. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23542. const point = this.points[ i ];
  23543. data.points.push( point.toArray() );
  23544. }
  23545. data.closed = this.closed;
  23546. data.curveType = this.curveType;
  23547. data.tension = this.tension;
  23548. return data;
  23549. }
  23550. fromJSON( json ) {
  23551. super.fromJSON( json );
  23552. this.points = [];
  23553. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23554. const point = json.points[ i ];
  23555. this.points.push( new Vector3().fromArray( point ) );
  23556. }
  23557. this.closed = json.closed;
  23558. this.curveType = json.curveType;
  23559. this.tension = json.tension;
  23560. return this;
  23561. }
  23562. }
  23563. /**
  23564. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  23565. *
  23566. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23567. *
  23568. * @module Interpolations
  23569. */
  23570. /**
  23571. * Computes a point on a Catmull-Rom spline.
  23572. *
  23573. * @param {number} t - The interpolation factor.
  23574. * @param {number} p0 - The first control point.
  23575. * @param {number} p1 - The second control point.
  23576. * @param {number} p2 - The third control point.
  23577. * @param {number} p3 - The fourth control point.
  23578. * @return {number} The calculated point on a Catmull-Rom spline.
  23579. */
  23580. function CatmullRom( t, p0, p1, p2, p3 ) {
  23581. const v0 = ( p2 - p0 ) * 0.5;
  23582. const v1 = ( p3 - p1 ) * 0.5;
  23583. const t2 = t * t;
  23584. const t3 = t * t2;
  23585. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23586. }
  23587. //
  23588. function QuadraticBezierP0( t, p ) {
  23589. const k = 1 - t;
  23590. return k * k * p;
  23591. }
  23592. function QuadraticBezierP1( t, p ) {
  23593. return 2 * ( 1 - t ) * t * p;
  23594. }
  23595. function QuadraticBezierP2( t, p ) {
  23596. return t * t * p;
  23597. }
  23598. /**
  23599. * Computes a point on a Quadratic Bezier curve.
  23600. *
  23601. * @param {number} t - The interpolation factor.
  23602. * @param {number} p0 - The first control point.
  23603. * @param {number} p1 - The second control point.
  23604. * @param {number} p2 - The third control point.
  23605. * @return {number} The calculated point on a Quadratic Bezier curve.
  23606. */
  23607. function QuadraticBezier( t, p0, p1, p2 ) {
  23608. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23609. QuadraticBezierP2( t, p2 );
  23610. }
  23611. //
  23612. function CubicBezierP0( t, p ) {
  23613. const k = 1 - t;
  23614. return k * k * k * p;
  23615. }
  23616. function CubicBezierP1( t, p ) {
  23617. const k = 1 - t;
  23618. return 3 * k * k * t * p;
  23619. }
  23620. function CubicBezierP2( t, p ) {
  23621. return 3 * ( 1 - t ) * t * t * p;
  23622. }
  23623. function CubicBezierP3( t, p ) {
  23624. return t * t * t * p;
  23625. }
  23626. /**
  23627. * Computes a point on a Cubic Bezier curve.
  23628. *
  23629. * @param {number} t - The interpolation factor.
  23630. * @param {number} p0 - The first control point.
  23631. * @param {number} p1 - The second control point.
  23632. * @param {number} p2 - The third control point.
  23633. * @param {number} p3 - The fourth control point.
  23634. * @return {number} The calculated point on a Cubic Bezier curve.
  23635. */
  23636. function CubicBezier( t, p0, p1, p2, p3 ) {
  23637. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23638. CubicBezierP3( t, p3 );
  23639. }
  23640. /**
  23641. * A curve representing a 2D Cubic Bezier curve.
  23642. *
  23643. * ```js
  23644. * const curve = new THREE.CubicBezierCurve(
  23645. * new THREE.Vector2( - 0, 0 ),
  23646. * new THREE.Vector2( - 5, 15 ),
  23647. * new THREE.Vector2( 20, 15 ),
  23648. * new THREE.Vector2( 10, 0 )
  23649. * );
  23650. *
  23651. * const points = curve.getPoints( 50 );
  23652. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23653. *
  23654. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23655. *
  23656. * // Create the final object to add to the scene
  23657. * const curveObject = new THREE.Line( geometry, material );
  23658. * ```
  23659. *
  23660. * @augments Curve
  23661. */
  23662. class CubicBezierCurve extends Curve {
  23663. /**
  23664. * Constructs a new Cubic Bezier curve.
  23665. *
  23666. * @param {Vector2} [v0] - The start point.
  23667. * @param {Vector2} [v1] - The first control point.
  23668. * @param {Vector2} [v2] - The second control point.
  23669. * @param {Vector2} [v3] - The end point.
  23670. */
  23671. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23672. super();
  23673. /**
  23674. * This flag can be used for type testing.
  23675. *
  23676. * @type {boolean}
  23677. * @readonly
  23678. * @default true
  23679. */
  23680. this.isCubicBezierCurve = true;
  23681. this.type = 'CubicBezierCurve';
  23682. /**
  23683. * The start point.
  23684. *
  23685. * @type {Vector2}
  23686. */
  23687. this.v0 = v0;
  23688. /**
  23689. * The first control point.
  23690. *
  23691. * @type {Vector2}
  23692. */
  23693. this.v1 = v1;
  23694. /**
  23695. * The second control point.
  23696. *
  23697. * @type {Vector2}
  23698. */
  23699. this.v2 = v2;
  23700. /**
  23701. * The end point.
  23702. *
  23703. * @type {Vector2}
  23704. */
  23705. this.v3 = v3;
  23706. }
  23707. /**
  23708. * Returns a point on the curve.
  23709. *
  23710. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23711. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23712. * @return {Vector2} The position on the curve.
  23713. */
  23714. getPoint( t, optionalTarget = new Vector2() ) {
  23715. const point = optionalTarget;
  23716. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23717. point.set(
  23718. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23719. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23720. );
  23721. return point;
  23722. }
  23723. copy( source ) {
  23724. super.copy( source );
  23725. this.v0.copy( source.v0 );
  23726. this.v1.copy( source.v1 );
  23727. this.v2.copy( source.v2 );
  23728. this.v3.copy( source.v3 );
  23729. return this;
  23730. }
  23731. toJSON() {
  23732. const data = super.toJSON();
  23733. data.v0 = this.v0.toArray();
  23734. data.v1 = this.v1.toArray();
  23735. data.v2 = this.v2.toArray();
  23736. data.v3 = this.v3.toArray();
  23737. return data;
  23738. }
  23739. fromJSON( json ) {
  23740. super.fromJSON( json );
  23741. this.v0.fromArray( json.v0 );
  23742. this.v1.fromArray( json.v1 );
  23743. this.v2.fromArray( json.v2 );
  23744. this.v3.fromArray( json.v3 );
  23745. return this;
  23746. }
  23747. }
  23748. /**
  23749. * A curve representing a 3D Cubic Bezier curve.
  23750. *
  23751. * @augments Curve
  23752. */
  23753. class CubicBezierCurve3 extends Curve {
  23754. /**
  23755. * Constructs a new Cubic Bezier curve.
  23756. *
  23757. * @param {Vector3} [v0] - The start point.
  23758. * @param {Vector3} [v1] - The first control point.
  23759. * @param {Vector3} [v2] - The second control point.
  23760. * @param {Vector3} [v3] - The end point.
  23761. */
  23762. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23763. super();
  23764. /**
  23765. * This flag can be used for type testing.
  23766. *
  23767. * @type {boolean}
  23768. * @readonly
  23769. * @default true
  23770. */
  23771. this.isCubicBezierCurve3 = true;
  23772. this.type = 'CubicBezierCurve3';
  23773. /**
  23774. * The start point.
  23775. *
  23776. * @type {Vector3}
  23777. */
  23778. this.v0 = v0;
  23779. /**
  23780. * The first control point.
  23781. *
  23782. * @type {Vector3}
  23783. */
  23784. this.v1 = v1;
  23785. /**
  23786. * The second control point.
  23787. *
  23788. * @type {Vector3}
  23789. */
  23790. this.v2 = v2;
  23791. /**
  23792. * The end point.
  23793. *
  23794. * @type {Vector3}
  23795. */
  23796. this.v3 = v3;
  23797. }
  23798. /**
  23799. * Returns a point on the curve.
  23800. *
  23801. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23802. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23803. * @return {Vector3} The position on the curve.
  23804. */
  23805. getPoint( t, optionalTarget = new Vector3() ) {
  23806. const point = optionalTarget;
  23807. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23808. point.set(
  23809. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23810. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23811. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23812. );
  23813. return point;
  23814. }
  23815. copy( source ) {
  23816. super.copy( source );
  23817. this.v0.copy( source.v0 );
  23818. this.v1.copy( source.v1 );
  23819. this.v2.copy( source.v2 );
  23820. this.v3.copy( source.v3 );
  23821. return this;
  23822. }
  23823. toJSON() {
  23824. const data = super.toJSON();
  23825. data.v0 = this.v0.toArray();
  23826. data.v1 = this.v1.toArray();
  23827. data.v2 = this.v2.toArray();
  23828. data.v3 = this.v3.toArray();
  23829. return data;
  23830. }
  23831. fromJSON( json ) {
  23832. super.fromJSON( json );
  23833. this.v0.fromArray( json.v0 );
  23834. this.v1.fromArray( json.v1 );
  23835. this.v2.fromArray( json.v2 );
  23836. this.v3.fromArray( json.v3 );
  23837. return this;
  23838. }
  23839. }
  23840. /**
  23841. * A curve representing a 2D line segment.
  23842. *
  23843. * @augments Curve
  23844. */
  23845. class LineCurve extends Curve {
  23846. /**
  23847. * Constructs a new line curve.
  23848. *
  23849. * @param {Vector2} [v1] - The start point.
  23850. * @param {Vector2} [v2] - The end point.
  23851. */
  23852. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  23853. super();
  23854. /**
  23855. * This flag can be used for type testing.
  23856. *
  23857. * @type {boolean}
  23858. * @readonly
  23859. * @default true
  23860. */
  23861. this.isLineCurve = true;
  23862. this.type = 'LineCurve';
  23863. /**
  23864. * The start point.
  23865. *
  23866. * @type {Vector2}
  23867. */
  23868. this.v1 = v1;
  23869. /**
  23870. * The end point.
  23871. *
  23872. * @type {Vector2}
  23873. */
  23874. this.v2 = v2;
  23875. }
  23876. /**
  23877. * Returns a point on the line.
  23878. *
  23879. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23880. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23881. * @return {Vector2} The position on the line.
  23882. */
  23883. getPoint( t, optionalTarget = new Vector2() ) {
  23884. const point = optionalTarget;
  23885. if ( t === 1 ) {
  23886. point.copy( this.v2 );
  23887. } else {
  23888. point.copy( this.v2 ).sub( this.v1 );
  23889. point.multiplyScalar( t ).add( this.v1 );
  23890. }
  23891. return point;
  23892. }
  23893. // Line curve is linear, so we can overwrite default getPointAt
  23894. getPointAt( u, optionalTarget ) {
  23895. return this.getPoint( u, optionalTarget );
  23896. }
  23897. getTangent( t, optionalTarget = new Vector2() ) {
  23898. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23899. }
  23900. getTangentAt( u, optionalTarget ) {
  23901. return this.getTangent( u, optionalTarget );
  23902. }
  23903. copy( source ) {
  23904. super.copy( source );
  23905. this.v1.copy( source.v1 );
  23906. this.v2.copy( source.v2 );
  23907. return this;
  23908. }
  23909. toJSON() {
  23910. const data = super.toJSON();
  23911. data.v1 = this.v1.toArray();
  23912. data.v2 = this.v2.toArray();
  23913. return data;
  23914. }
  23915. fromJSON( json ) {
  23916. super.fromJSON( json );
  23917. this.v1.fromArray( json.v1 );
  23918. this.v2.fromArray( json.v2 );
  23919. return this;
  23920. }
  23921. }
  23922. /**
  23923. * A curve representing a 3D line segment.
  23924. *
  23925. * @augments Curve
  23926. */
  23927. class LineCurve3 extends Curve {
  23928. /**
  23929. * Constructs a new line curve.
  23930. *
  23931. * @param {Vector3} [v1] - The start point.
  23932. * @param {Vector3} [v2] - The end point.
  23933. */
  23934. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  23935. super();
  23936. /**
  23937. * This flag can be used for type testing.
  23938. *
  23939. * @type {boolean}
  23940. * @readonly
  23941. * @default true
  23942. */
  23943. this.isLineCurve3 = true;
  23944. this.type = 'LineCurve3';
  23945. /**
  23946. * The start point.
  23947. *
  23948. * @type {Vector3}
  23949. */
  23950. this.v1 = v1;
  23951. /**
  23952. * The end point.
  23953. *
  23954. * @type {Vector2}
  23955. */
  23956. this.v2 = v2;
  23957. }
  23958. /**
  23959. * Returns a point on the line.
  23960. *
  23961. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  23962. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23963. * @return {Vector3} The position on the line.
  23964. */
  23965. getPoint( t, optionalTarget = new Vector3() ) {
  23966. const point = optionalTarget;
  23967. if ( t === 1 ) {
  23968. point.copy( this.v2 );
  23969. } else {
  23970. point.copy( this.v2 ).sub( this.v1 );
  23971. point.multiplyScalar( t ).add( this.v1 );
  23972. }
  23973. return point;
  23974. }
  23975. // Line curve is linear, so we can overwrite default getPointAt
  23976. getPointAt( u, optionalTarget ) {
  23977. return this.getPoint( u, optionalTarget );
  23978. }
  23979. getTangent( t, optionalTarget = new Vector3() ) {
  23980. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  23981. }
  23982. getTangentAt( u, optionalTarget ) {
  23983. return this.getTangent( u, optionalTarget );
  23984. }
  23985. copy( source ) {
  23986. super.copy( source );
  23987. this.v1.copy( source.v1 );
  23988. this.v2.copy( source.v2 );
  23989. return this;
  23990. }
  23991. toJSON() {
  23992. const data = super.toJSON();
  23993. data.v1 = this.v1.toArray();
  23994. data.v2 = this.v2.toArray();
  23995. return data;
  23996. }
  23997. fromJSON( json ) {
  23998. super.fromJSON( json );
  23999. this.v1.fromArray( json.v1 );
  24000. this.v2.fromArray( json.v2 );
  24001. return this;
  24002. }
  24003. }
  24004. /**
  24005. * A curve representing a 2D Quadratic Bezier curve.
  24006. *
  24007. * ```js
  24008. * const curve = new THREE.QuadraticBezierCurve(
  24009. * new THREE.Vector2( - 10, 0 ),
  24010. * new THREE.Vector2( 20, 15 ),
  24011. * new THREE.Vector2( 10, 0 )
  24012. * )
  24013. *
  24014. * const points = curve.getPoints( 50 );
  24015. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24016. *
  24017. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24018. *
  24019. * // Create the final object to add to the scene
  24020. * const curveObject = new THREE.Line( geometry, material );
  24021. * ```
  24022. *
  24023. * @augments Curve
  24024. */
  24025. class QuadraticBezierCurve extends Curve {
  24026. /**
  24027. * Constructs a new Quadratic Bezier curve.
  24028. *
  24029. * @param {Vector2} [v0] - The start point.
  24030. * @param {Vector2} [v1] - The control point.
  24031. * @param {Vector2} [v2] - The end point.
  24032. */
  24033. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24034. super();
  24035. /**
  24036. * This flag can be used for type testing.
  24037. *
  24038. * @type {boolean}
  24039. * @readonly
  24040. * @default true
  24041. */
  24042. this.isQuadraticBezierCurve = true;
  24043. this.type = 'QuadraticBezierCurve';
  24044. /**
  24045. * The start point.
  24046. *
  24047. * @type {Vector2}
  24048. */
  24049. this.v0 = v0;
  24050. /**
  24051. * The control point.
  24052. *
  24053. * @type {Vector2}
  24054. */
  24055. this.v1 = v1;
  24056. /**
  24057. * The end point.
  24058. *
  24059. * @type {Vector2}
  24060. */
  24061. this.v2 = v2;
  24062. }
  24063. /**
  24064. * Returns a point on the curve.
  24065. *
  24066. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24067. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24068. * @return {Vector2} The position on the curve.
  24069. */
  24070. getPoint( t, optionalTarget = new Vector2() ) {
  24071. const point = optionalTarget;
  24072. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24073. point.set(
  24074. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24075. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24076. );
  24077. return point;
  24078. }
  24079. copy( source ) {
  24080. super.copy( source );
  24081. this.v0.copy( source.v0 );
  24082. this.v1.copy( source.v1 );
  24083. this.v2.copy( source.v2 );
  24084. return this;
  24085. }
  24086. toJSON() {
  24087. const data = super.toJSON();
  24088. data.v0 = this.v0.toArray();
  24089. data.v1 = this.v1.toArray();
  24090. data.v2 = this.v2.toArray();
  24091. return data;
  24092. }
  24093. fromJSON( json ) {
  24094. super.fromJSON( json );
  24095. this.v0.fromArray( json.v0 );
  24096. this.v1.fromArray( json.v1 );
  24097. this.v2.fromArray( json.v2 );
  24098. return this;
  24099. }
  24100. }
  24101. /**
  24102. * A curve representing a 3D Quadratic Bezier curve.
  24103. *
  24104. * @augments Curve
  24105. */
  24106. class QuadraticBezierCurve3 extends Curve {
  24107. /**
  24108. * Constructs a new Quadratic Bezier curve.
  24109. *
  24110. * @param {Vector3} [v0] - The start point.
  24111. * @param {Vector3} [v1] - The control point.
  24112. * @param {Vector3} [v2] - The end point.
  24113. */
  24114. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24115. super();
  24116. /**
  24117. * This flag can be used for type testing.
  24118. *
  24119. * @type {boolean}
  24120. * @readonly
  24121. * @default true
  24122. */
  24123. this.isQuadraticBezierCurve3 = true;
  24124. this.type = 'QuadraticBezierCurve3';
  24125. /**
  24126. * The start point.
  24127. *
  24128. * @type {Vector3}
  24129. */
  24130. this.v0 = v0;
  24131. /**
  24132. * The control point.
  24133. *
  24134. * @type {Vector3}
  24135. */
  24136. this.v1 = v1;
  24137. /**
  24138. * The end point.
  24139. *
  24140. * @type {Vector3}
  24141. */
  24142. this.v2 = v2;
  24143. }
  24144. /**
  24145. * Returns a point on the curve.
  24146. *
  24147. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24148. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24149. * @return {Vector3} The position on the curve.
  24150. */
  24151. getPoint( t, optionalTarget = new Vector3() ) {
  24152. const point = optionalTarget;
  24153. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24154. point.set(
  24155. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24156. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24157. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24158. );
  24159. return point;
  24160. }
  24161. copy( source ) {
  24162. super.copy( source );
  24163. this.v0.copy( source.v0 );
  24164. this.v1.copy( source.v1 );
  24165. this.v2.copy( source.v2 );
  24166. return this;
  24167. }
  24168. toJSON() {
  24169. const data = super.toJSON();
  24170. data.v0 = this.v0.toArray();
  24171. data.v1 = this.v1.toArray();
  24172. data.v2 = this.v2.toArray();
  24173. return data;
  24174. }
  24175. fromJSON( json ) {
  24176. super.fromJSON( json );
  24177. this.v0.fromArray( json.v0 );
  24178. this.v1.fromArray( json.v1 );
  24179. this.v2.fromArray( json.v2 );
  24180. return this;
  24181. }
  24182. }
  24183. /**
  24184. * A curve representing a 2D spline curve.
  24185. *
  24186. * ```js
  24187. * // Create a sine-like wave
  24188. * const curve = new THREE.SplineCurve( [
  24189. * new THREE.Vector2( -10, 0 ),
  24190. * new THREE.Vector2( -5, 5 ),
  24191. * new THREE.Vector2( 0, 0 ),
  24192. * new THREE.Vector2( 5, -5 ),
  24193. * new THREE.Vector2( 10, 0 )
  24194. * ] );
  24195. *
  24196. * const points = curve.getPoints( 50 );
  24197. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24198. *
  24199. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24200. *
  24201. * // Create the final object to add to the scene
  24202. * const splineObject = new THREE.Line( geometry, material );
  24203. * ```
  24204. *
  24205. * @augments Curve
  24206. */
  24207. class SplineCurve extends Curve {
  24208. /**
  24209. * Constructs a new 2D spline curve.
  24210. *
  24211. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24212. */
  24213. constructor( points = [] ) {
  24214. super();
  24215. /**
  24216. * This flag can be used for type testing.
  24217. *
  24218. * @type {boolean}
  24219. * @readonly
  24220. * @default true
  24221. */
  24222. this.isSplineCurve = true;
  24223. this.type = 'SplineCurve';
  24224. /**
  24225. * An array of 2D points defining the curve.
  24226. *
  24227. * @type {Array<Vector2>}
  24228. */
  24229. this.points = points;
  24230. }
  24231. /**
  24232. * Returns a point on the curve.
  24233. *
  24234. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24235. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24236. * @return {Vector2} The position on the curve.
  24237. */
  24238. getPoint( t, optionalTarget = new Vector2() ) {
  24239. const point = optionalTarget;
  24240. const points = this.points;
  24241. const p = ( points.length - 1 ) * t;
  24242. const intPoint = Math.floor( p );
  24243. const weight = p - intPoint;
  24244. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24245. const p1 = points[ intPoint ];
  24246. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24247. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24248. point.set(
  24249. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24250. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24251. );
  24252. return point;
  24253. }
  24254. copy( source ) {
  24255. super.copy( source );
  24256. this.points = [];
  24257. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24258. const point = source.points[ i ];
  24259. this.points.push( point.clone() );
  24260. }
  24261. return this;
  24262. }
  24263. toJSON() {
  24264. const data = super.toJSON();
  24265. data.points = [];
  24266. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24267. const point = this.points[ i ];
  24268. data.points.push( point.toArray() );
  24269. }
  24270. return data;
  24271. }
  24272. fromJSON( json ) {
  24273. super.fromJSON( json );
  24274. this.points = [];
  24275. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24276. const point = json.points[ i ];
  24277. this.points.push( new Vector2().fromArray( point ) );
  24278. }
  24279. return this;
  24280. }
  24281. }
  24282. var Curves = /*#__PURE__*/Object.freeze({
  24283. __proto__: null,
  24284. ArcCurve: ArcCurve,
  24285. CatmullRomCurve3: CatmullRomCurve3,
  24286. CubicBezierCurve: CubicBezierCurve,
  24287. CubicBezierCurve3: CubicBezierCurve3,
  24288. EllipseCurve: EllipseCurve,
  24289. LineCurve: LineCurve,
  24290. LineCurve3: LineCurve3,
  24291. QuadraticBezierCurve: QuadraticBezierCurve,
  24292. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24293. SplineCurve: SplineCurve
  24294. });
  24295. /**
  24296. * A base class extending {@link Curve}. `CurvePath` is simply an
  24297. * array of connected curves, but retains the API of a curve.
  24298. *
  24299. * @augments Curve
  24300. */
  24301. class CurvePath extends Curve {
  24302. /**
  24303. * Constructs a new curve path.
  24304. */
  24305. constructor() {
  24306. super();
  24307. this.type = 'CurvePath';
  24308. /**
  24309. * An array of curves defining the
  24310. * path.
  24311. *
  24312. * @type {Array<Curve>}
  24313. */
  24314. this.curves = [];
  24315. /**
  24316. * Whether the path should automatically be closed
  24317. * by a line curve.
  24318. *
  24319. * @type {boolean}
  24320. * @default false
  24321. */
  24322. this.autoClose = false;
  24323. }
  24324. /**
  24325. * Adds a curve to this curve path.
  24326. *
  24327. * @param {Curve} curve - The curve to add.
  24328. */
  24329. add( curve ) {
  24330. this.curves.push( curve );
  24331. }
  24332. /**
  24333. * Adds a line curve to close the path.
  24334. *
  24335. * @return {CurvePath} A reference to this curve path.
  24336. */
  24337. closePath() {
  24338. // Add a line curve if start and end of lines are not connected
  24339. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24340. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24341. if ( ! startPoint.equals( endPoint ) ) {
  24342. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24343. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24344. }
  24345. return this;
  24346. }
  24347. /**
  24348. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24349. * for the given interpolation factor.
  24350. *
  24351. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24352. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24353. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24354. */
  24355. getPoint( t, optionalTarget ) {
  24356. // To get accurate point with reference to
  24357. // entire path distance at time t,
  24358. // following has to be done:
  24359. // 1. Length of each sub path have to be known
  24360. // 2. Locate and identify type of curve
  24361. // 3. Get t for the curve
  24362. // 4. Return curve.getPointAt(t')
  24363. const d = t * this.getLength();
  24364. const curveLengths = this.getCurveLengths();
  24365. let i = 0;
  24366. // To think about boundaries points.
  24367. while ( i < curveLengths.length ) {
  24368. if ( curveLengths[ i ] >= d ) {
  24369. const diff = curveLengths[ i ] - d;
  24370. const curve = this.curves[ i ];
  24371. const segmentLength = curve.getLength();
  24372. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24373. return curve.getPointAt( u, optionalTarget );
  24374. }
  24375. i ++;
  24376. }
  24377. return null;
  24378. // loop where sum != 0, sum > d , sum+1 <d
  24379. }
  24380. getLength() {
  24381. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24382. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24383. // getPoint() depends on getLength
  24384. const lens = this.getCurveLengths();
  24385. return lens[ lens.length - 1 ];
  24386. }
  24387. updateArcLengths() {
  24388. // cacheLengths must be recalculated.
  24389. this.needsUpdate = true;
  24390. this.cacheLengths = null;
  24391. this.getCurveLengths();
  24392. }
  24393. /**
  24394. * Returns list of cumulative curve lengths of the defined curves.
  24395. *
  24396. * @return {Array<number>} The curve lengths.
  24397. */
  24398. getCurveLengths() {
  24399. // Compute lengths and cache them
  24400. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24401. // We use cache values if curves and cache array are same length
  24402. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24403. return this.cacheLengths;
  24404. }
  24405. // Get length of sub-curve
  24406. // Push sums into cached array
  24407. const lengths = [];
  24408. let sums = 0;
  24409. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24410. sums += this.curves[ i ].getLength();
  24411. lengths.push( sums );
  24412. }
  24413. this.cacheLengths = lengths;
  24414. return lengths;
  24415. }
  24416. getSpacedPoints( divisions = 40 ) {
  24417. const points = [];
  24418. for ( let i = 0; i <= divisions; i ++ ) {
  24419. points.push( this.getPoint( i / divisions ) );
  24420. }
  24421. if ( this.autoClose ) {
  24422. points.push( points[ 0 ] );
  24423. }
  24424. return points;
  24425. }
  24426. getPoints( divisions = 12 ) {
  24427. const points = [];
  24428. let last;
  24429. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24430. const curve = curves[ i ];
  24431. const resolution = curve.isEllipseCurve ? divisions * 2
  24432. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24433. : curve.isSplineCurve ? divisions * curve.points.length
  24434. : divisions;
  24435. const pts = curve.getPoints( resolution );
  24436. for ( let j = 0; j < pts.length; j ++ ) {
  24437. const point = pts[ j ];
  24438. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24439. points.push( point );
  24440. last = point;
  24441. }
  24442. }
  24443. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24444. points.push( points[ 0 ] );
  24445. }
  24446. return points;
  24447. }
  24448. copy( source ) {
  24449. super.copy( source );
  24450. this.curves = [];
  24451. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24452. const curve = source.curves[ i ];
  24453. this.curves.push( curve.clone() );
  24454. }
  24455. this.autoClose = source.autoClose;
  24456. return this;
  24457. }
  24458. toJSON() {
  24459. const data = super.toJSON();
  24460. data.autoClose = this.autoClose;
  24461. data.curves = [];
  24462. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24463. const curve = this.curves[ i ];
  24464. data.curves.push( curve.toJSON() );
  24465. }
  24466. return data;
  24467. }
  24468. fromJSON( json ) {
  24469. super.fromJSON( json );
  24470. this.autoClose = json.autoClose;
  24471. this.curves = [];
  24472. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24473. const curve = json.curves[ i ];
  24474. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24475. }
  24476. return this;
  24477. }
  24478. }
  24479. /**
  24480. * A 2D path representation. The class provides methods for creating paths
  24481. * and contours of 2D shapes similar to the 2D Canvas API.
  24482. *
  24483. * ```js
  24484. * const path = new THREE.Path();
  24485. *
  24486. * path.lineTo( 0, 0.8 );
  24487. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24488. * path.lineTo( 1, 1 );
  24489. *
  24490. * const points = path.getPoints();
  24491. *
  24492. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24493. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24494. *
  24495. * const line = new THREE.Line( geometry, material );
  24496. * scene.add( line );
  24497. * ```
  24498. *
  24499. * @augments CurvePath
  24500. */
  24501. class Path extends CurvePath {
  24502. /**
  24503. * Constructs a new path.
  24504. *
  24505. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24506. */
  24507. constructor( points ) {
  24508. super();
  24509. this.type = 'Path';
  24510. /**
  24511. * The current offset of the path. Any new curve added will start here.
  24512. *
  24513. * @type {Vector2}
  24514. */
  24515. this.currentPoint = new Vector2();
  24516. if ( points ) {
  24517. this.setFromPoints( points );
  24518. }
  24519. }
  24520. /**
  24521. * Creates a path from the given list of points. The points are added
  24522. * to the path as instances of {@link LineCurve}.
  24523. *
  24524. * @param {Array<Vector2>} points - An array of 2D points.
  24525. * @return {Path} A reference to this path.
  24526. */
  24527. setFromPoints( points ) {
  24528. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24529. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24530. this.lineTo( points[ i ].x, points[ i ].y );
  24531. }
  24532. return this;
  24533. }
  24534. /**
  24535. * Moves {@link Path#currentPoint} to the given point.
  24536. *
  24537. * @param {number} x - The x coordinate.
  24538. * @param {number} y - The y coordinate.
  24539. * @return {Path} A reference to this path.
  24540. */
  24541. moveTo( x, y ) {
  24542. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24543. return this;
  24544. }
  24545. /**
  24546. * Adds an instance of {@link LineCurve} to the path by connecting
  24547. * the current point with the given one.
  24548. *
  24549. * @param {number} x - The x coordinate of the end point.
  24550. * @param {number} y - The y coordinate of the end point.
  24551. * @return {Path} A reference to this path.
  24552. */
  24553. lineTo( x, y ) {
  24554. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24555. this.curves.push( curve );
  24556. this.currentPoint.set( x, y );
  24557. return this;
  24558. }
  24559. /**
  24560. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24561. * the current point with the given one.
  24562. *
  24563. * @param {number} aCPx - The x coordinate of the control point.
  24564. * @param {number} aCPy - The y coordinate of the control point.
  24565. * @param {number} aX - The x coordinate of the end point.
  24566. * @param {number} aY - The y coordinate of the end point.
  24567. * @return {Path} A reference to this path.
  24568. */
  24569. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24570. const curve = new QuadraticBezierCurve(
  24571. this.currentPoint.clone(),
  24572. new Vector2( aCPx, aCPy ),
  24573. new Vector2( aX, aY )
  24574. );
  24575. this.curves.push( curve );
  24576. this.currentPoint.set( aX, aY );
  24577. return this;
  24578. }
  24579. /**
  24580. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24581. * the current point with the given one.
  24582. *
  24583. * @param {number} aCP1x - The x coordinate of the first control point.
  24584. * @param {number} aCP1y - The y coordinate of the first control point.
  24585. * @param {number} aCP2x - The x coordinate of the second control point.
  24586. * @param {number} aCP2y - The y coordinate of the second control point.
  24587. * @param {number} aX - The x coordinate of the end point.
  24588. * @param {number} aY - The y coordinate of the end point.
  24589. * @return {Path} A reference to this path.
  24590. */
  24591. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24592. const curve = new CubicBezierCurve(
  24593. this.currentPoint.clone(),
  24594. new Vector2( aCP1x, aCP1y ),
  24595. new Vector2( aCP2x, aCP2y ),
  24596. new Vector2( aX, aY )
  24597. );
  24598. this.curves.push( curve );
  24599. this.currentPoint.set( aX, aY );
  24600. return this;
  24601. }
  24602. /**
  24603. * Adds an instance of {@link SplineCurve} to the path by connecting
  24604. * the current point with the given list of points.
  24605. *
  24606. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24607. * @return {Path} A reference to this path.
  24608. */
  24609. splineThru( pts ) {
  24610. const npts = [ this.currentPoint.clone() ].concat( pts );
  24611. const curve = new SplineCurve( npts );
  24612. this.curves.push( curve );
  24613. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24614. return this;
  24615. }
  24616. /**
  24617. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24618. * to the current point.
  24619. *
  24620. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24621. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24622. * @param {number} [aRadius=1] - The radius of the arc.
  24623. * @param {number} [aStartAngle=0] - The start angle in radians.
  24624. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24625. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24626. * @return {Path} A reference to this path.
  24627. */
  24628. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24629. const x0 = this.currentPoint.x;
  24630. const y0 = this.currentPoint.y;
  24631. this.absarc( aX + x0, aY + y0, aRadius,
  24632. aStartAngle, aEndAngle, aClockwise );
  24633. return this;
  24634. }
  24635. /**
  24636. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24637. *
  24638. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24639. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24640. * @param {number} [aRadius=1] - The radius of the arc.
  24641. * @param {number} [aStartAngle=0] - The start angle in radians.
  24642. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24643. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24644. * @return {Path} A reference to this path.
  24645. */
  24646. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24647. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24648. return this;
  24649. }
  24650. /**
  24651. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24652. * to the current point
  24653. *
  24654. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24655. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24656. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24657. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24658. * @param {number} [aStartAngle=0] - The start angle in radians.
  24659. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24660. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24661. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24662. * @return {Path} A reference to this path.
  24663. */
  24664. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24665. const x0 = this.currentPoint.x;
  24666. const y0 = this.currentPoint.y;
  24667. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24668. return this;
  24669. }
  24670. /**
  24671. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24672. *
  24673. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24674. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24675. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24676. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24677. * @param {number} [aStartAngle=0] - The start angle in radians.
  24678. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24679. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24680. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24681. * @return {Path} A reference to this path.
  24682. */
  24683. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24684. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24685. if ( this.curves.length > 0 ) {
  24686. // if a previous curve is present, attempt to join
  24687. const firstPoint = curve.getPoint( 0 );
  24688. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24689. this.lineTo( firstPoint.x, firstPoint.y );
  24690. }
  24691. }
  24692. this.curves.push( curve );
  24693. const lastPoint = curve.getPoint( 1 );
  24694. this.currentPoint.copy( lastPoint );
  24695. return this;
  24696. }
  24697. copy( source ) {
  24698. super.copy( source );
  24699. this.currentPoint.copy( source.currentPoint );
  24700. return this;
  24701. }
  24702. toJSON() {
  24703. const data = super.toJSON();
  24704. data.currentPoint = this.currentPoint.toArray();
  24705. return data;
  24706. }
  24707. fromJSON( json ) {
  24708. super.fromJSON( json );
  24709. this.currentPoint.fromArray( json.currentPoint );
  24710. return this;
  24711. }
  24712. }
  24713. /**
  24714. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24715. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24716. * points, or to get triangulated faces.
  24717. *
  24718. * ```js
  24719. * const heartShape = new THREE.Shape();
  24720. *
  24721. * heartShape.moveTo( 25, 25 );
  24722. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24723. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24724. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24725. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24726. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24727. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24728. *
  24729. * const extrudeSettings = {
  24730. * depth: 8,
  24731. * bevelEnabled: true,
  24732. * bevelSegments: 2,
  24733. * steps: 2,
  24734. * bevelSize: 1,
  24735. * bevelThickness: 1
  24736. * };
  24737. *
  24738. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24739. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24740. * ```
  24741. *
  24742. * @augments Path
  24743. */
  24744. class Shape extends Path {
  24745. /**
  24746. * Constructs a new shape.
  24747. *
  24748. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24749. */
  24750. constructor( points ) {
  24751. super( points );
  24752. /**
  24753. * The UUID of the shape.
  24754. *
  24755. * @type {string}
  24756. * @readonly
  24757. */
  24758. this.uuid = generateUUID();
  24759. this.type = 'Shape';
  24760. /**
  24761. * Defines the holes in the shape. Hole definitions must use the
  24762. * opposite winding order (CW/CCW) than the outer shape.
  24763. *
  24764. * @type {Array<Path>}
  24765. * @readonly
  24766. */
  24767. this.holes = [];
  24768. }
  24769. /**
  24770. * Returns an array representing each contour of the holes
  24771. * as a list of 2D points.
  24772. *
  24773. * @param {number} divisions - The fineness of the result.
  24774. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24775. */
  24776. getPointsHoles( divisions ) {
  24777. const holesPts = [];
  24778. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24779. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24780. }
  24781. return holesPts;
  24782. }
  24783. // get points of shape and holes (keypoints based on segments parameter)
  24784. /**
  24785. * Returns an object that holds contour data for the shape and its holes as
  24786. * arrays of 2D points.
  24787. *
  24788. * @param {number} divisions - The fineness of the result.
  24789. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  24790. */
  24791. extractPoints( divisions ) {
  24792. return {
  24793. shape: this.getPoints( divisions ),
  24794. holes: this.getPointsHoles( divisions )
  24795. };
  24796. }
  24797. copy( source ) {
  24798. super.copy( source );
  24799. this.holes = [];
  24800. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24801. const hole = source.holes[ i ];
  24802. this.holes.push( hole.clone() );
  24803. }
  24804. return this;
  24805. }
  24806. toJSON() {
  24807. const data = super.toJSON();
  24808. data.uuid = this.uuid;
  24809. data.holes = [];
  24810. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24811. const hole = this.holes[ i ];
  24812. data.holes.push( hole.toJSON() );
  24813. }
  24814. return data;
  24815. }
  24816. fromJSON( json ) {
  24817. super.fromJSON( json );
  24818. this.uuid = json.uuid;
  24819. this.holes = [];
  24820. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24821. const hole = json.holes[ i ];
  24822. this.holes.push( new Path().fromJSON( hole ) );
  24823. }
  24824. return this;
  24825. }
  24826. }
  24827. /* eslint-disable */
  24828. // copy of mapbox/earcut version 3.0.2
  24829. // https://github.com/mapbox/earcut/tree/v3.0.2
  24830. function earcut(data, holeIndices, dim = 2) {
  24831. const hasHoles = holeIndices && holeIndices.length;
  24832. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24833. let outerNode = linkedList(data, 0, outerLen, dim, true);
  24834. const triangles = [];
  24835. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  24836. let minX, minY, invSize;
  24837. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  24838. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  24839. if (data.length > 80 * dim) {
  24840. minX = data[0];
  24841. minY = data[1];
  24842. let maxX = minX;
  24843. let maxY = minY;
  24844. for (let i = dim; i < outerLen; i += dim) {
  24845. const x = data[i];
  24846. const y = data[i + 1];
  24847. if (x < minX) minX = x;
  24848. if (y < minY) minY = y;
  24849. if (x > maxX) maxX = x;
  24850. if (y > maxY) maxY = y;
  24851. }
  24852. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  24853. invSize = Math.max(maxX - minX, maxY - minY);
  24854. invSize = invSize !== 0 ? 32767 / invSize : 0;
  24855. }
  24856. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  24857. return triangles;
  24858. }
  24859. // create a circular doubly linked list from polygon points in the specified winding order
  24860. function linkedList(data, start, end, dim, clockwise) {
  24861. let last;
  24862. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  24863. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24864. } else {
  24865. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  24866. }
  24867. if (last && equals(last, last.next)) {
  24868. removeNode(last);
  24869. last = last.next;
  24870. }
  24871. return last;
  24872. }
  24873. // eliminate colinear or duplicate points
  24874. function filterPoints(start, end) {
  24875. if (!start) return start;
  24876. if (!end) end = start;
  24877. let p = start,
  24878. again;
  24879. do {
  24880. again = false;
  24881. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  24882. removeNode(p);
  24883. p = end = p.prev;
  24884. if (p === p.next) break;
  24885. again = true;
  24886. } else {
  24887. p = p.next;
  24888. }
  24889. } while (again || p !== end);
  24890. return end;
  24891. }
  24892. // main ear slicing loop which triangulates a polygon (given as a linked list)
  24893. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  24894. if (!ear) return;
  24895. // interlink polygon nodes in z-order
  24896. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  24897. let stop = ear;
  24898. // iterate through ears, slicing them one by one
  24899. while (ear.prev !== ear.next) {
  24900. const prev = ear.prev;
  24901. const next = ear.next;
  24902. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  24903. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  24904. removeNode(ear);
  24905. // skipping the next vertex leads to less sliver triangles
  24906. ear = next.next;
  24907. stop = next.next;
  24908. continue;
  24909. }
  24910. ear = next;
  24911. // if we looped through the whole remaining polygon and can't find any more ears
  24912. if (ear === stop) {
  24913. // try filtering points and slicing again
  24914. if (!pass) {
  24915. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  24916. // if this didn't work, try curing all small self-intersections locally
  24917. } else if (pass === 1) {
  24918. ear = cureLocalIntersections(filterPoints(ear), triangles);
  24919. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  24920. // as a last resort, try splitting the remaining polygon into two
  24921. } else if (pass === 2) {
  24922. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  24923. }
  24924. break;
  24925. }
  24926. }
  24927. }
  24928. // check whether a polygon node forms a valid ear with adjacent nodes
  24929. function isEar(ear) {
  24930. const a = ear.prev,
  24931. b = ear,
  24932. c = ear.next;
  24933. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24934. // now make sure we don't have other points inside the potential ear
  24935. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24936. // triangle bbox
  24937. const x0 = Math.min(ax, bx, cx),
  24938. y0 = Math.min(ay, by, cy),
  24939. x1 = Math.max(ax, bx, cx),
  24940. y1 = Math.max(ay, by, cy);
  24941. let p = c.next;
  24942. while (p !== a) {
  24943. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  24944. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  24945. area(p.prev, p, p.next) >= 0) return false;
  24946. p = p.next;
  24947. }
  24948. return true;
  24949. }
  24950. function isEarHashed(ear, minX, minY, invSize) {
  24951. const a = ear.prev,
  24952. b = ear,
  24953. c = ear.next;
  24954. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  24955. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  24956. // triangle bbox
  24957. const x0 = Math.min(ax, bx, cx),
  24958. y0 = Math.min(ay, by, cy),
  24959. x1 = Math.max(ax, bx, cx),
  24960. y1 = Math.max(ay, by, cy);
  24961. // z-order range for the current triangle bbox;
  24962. const minZ = zOrder(x0, y0, minX, minY, invSize),
  24963. maxZ = zOrder(x1, y1, minX, minY, invSize);
  24964. let p = ear.prevZ,
  24965. n = ear.nextZ;
  24966. // look for points inside the triangle in both directions
  24967. while (p && p.z >= minZ && n && n.z <= maxZ) {
  24968. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24969. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24970. p = p.prevZ;
  24971. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24972. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24973. n = n.nextZ;
  24974. }
  24975. // look for remaining points in decreasing z-order
  24976. while (p && p.z >= minZ) {
  24977. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  24978. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  24979. p = p.prevZ;
  24980. }
  24981. // look for remaining points in increasing z-order
  24982. while (n && n.z <= maxZ) {
  24983. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  24984. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  24985. n = n.nextZ;
  24986. }
  24987. return true;
  24988. }
  24989. // go through all polygon nodes and cure small local self-intersections
  24990. function cureLocalIntersections(start, triangles) {
  24991. let p = start;
  24992. do {
  24993. const a = p.prev,
  24994. b = p.next.next;
  24995. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  24996. triangles.push(a.i, p.i, b.i);
  24997. // remove two nodes involved
  24998. removeNode(p);
  24999. removeNode(p.next);
  25000. p = start = b;
  25001. }
  25002. p = p.next;
  25003. } while (p !== start);
  25004. return filterPoints(p);
  25005. }
  25006. // try splitting polygon into two and triangulate them independently
  25007. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25008. // look for a valid diagonal that divides the polygon into two
  25009. let a = start;
  25010. do {
  25011. let b = a.next.next;
  25012. while (b !== a.prev) {
  25013. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25014. // split the polygon in two by the diagonal
  25015. let c = splitPolygon(a, b);
  25016. // filter colinear points around the cuts
  25017. a = filterPoints(a, a.next);
  25018. c = filterPoints(c, c.next);
  25019. // run earcut on each half
  25020. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25021. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25022. return;
  25023. }
  25024. b = b.next;
  25025. }
  25026. a = a.next;
  25027. } while (a !== start);
  25028. }
  25029. // link every hole into the outer loop, producing a single-ring polygon without holes
  25030. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25031. const queue = [];
  25032. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25033. const start = holeIndices[i] * dim;
  25034. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25035. const list = linkedList(data, start, end, dim, false);
  25036. if (list === list.next) list.steiner = true;
  25037. queue.push(getLeftmost(list));
  25038. }
  25039. queue.sort(compareXYSlope);
  25040. // process holes from left to right
  25041. for (let i = 0; i < queue.length; i++) {
  25042. outerNode = eliminateHole(queue[i], outerNode);
  25043. }
  25044. return outerNode;
  25045. }
  25046. function compareXYSlope(a, b) {
  25047. let result = a.x - b.x;
  25048. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25049. // the bridge to the outer shell is always the point that they meet at.
  25050. if (result === 0) {
  25051. result = a.y - b.y;
  25052. if (result === 0) {
  25053. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25054. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25055. result = aSlope - bSlope;
  25056. }
  25057. }
  25058. return result;
  25059. }
  25060. // find a bridge between vertices that connects hole with an outer ring and link it
  25061. function eliminateHole(hole, outerNode) {
  25062. const bridge = findHoleBridge(hole, outerNode);
  25063. if (!bridge) {
  25064. return outerNode;
  25065. }
  25066. const bridgeReverse = splitPolygon(bridge, hole);
  25067. // filter collinear points around the cuts
  25068. filterPoints(bridgeReverse, bridgeReverse.next);
  25069. return filterPoints(bridge, bridge.next);
  25070. }
  25071. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25072. function findHoleBridge(hole, outerNode) {
  25073. let p = outerNode;
  25074. const hx = hole.x;
  25075. const hy = hole.y;
  25076. let qx = -Infinity;
  25077. let m;
  25078. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25079. // segment's endpoint with lesser x will be potential connection point
  25080. // unless they intersect at a vertex, then choose the vertex
  25081. if (equals(hole, p)) return p;
  25082. do {
  25083. if (equals(hole, p.next)) return p.next;
  25084. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25085. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25086. if (x <= hx && x > qx) {
  25087. qx = x;
  25088. m = p.x < p.next.x ? p : p.next;
  25089. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25090. }
  25091. }
  25092. p = p.next;
  25093. } while (p !== outerNode);
  25094. if (!m) return null;
  25095. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25096. // if there are no points found, we have a valid connection;
  25097. // otherwise choose the point of the minimum angle with the ray as connection point
  25098. const stop = m;
  25099. const mx = m.x;
  25100. const my = m.y;
  25101. let tanMin = Infinity;
  25102. p = m;
  25103. do {
  25104. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25105. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25106. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25107. if (locallyInside(p, hole) &&
  25108. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25109. m = p;
  25110. tanMin = tan;
  25111. }
  25112. }
  25113. p = p.next;
  25114. } while (p !== stop);
  25115. return m;
  25116. }
  25117. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25118. function sectorContainsSector(m, p) {
  25119. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25120. }
  25121. // interlink polygon nodes in z-order
  25122. function indexCurve(start, minX, minY, invSize) {
  25123. let p = start;
  25124. do {
  25125. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25126. p.prevZ = p.prev;
  25127. p.nextZ = p.next;
  25128. p = p.next;
  25129. } while (p !== start);
  25130. p.prevZ.nextZ = null;
  25131. p.prevZ = null;
  25132. sortLinked(p);
  25133. }
  25134. // Simon Tatham's linked list merge sort algorithm
  25135. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25136. function sortLinked(list) {
  25137. let numMerges;
  25138. let inSize = 1;
  25139. do {
  25140. let p = list;
  25141. let e;
  25142. list = null;
  25143. let tail = null;
  25144. numMerges = 0;
  25145. while (p) {
  25146. numMerges++;
  25147. let q = p;
  25148. let pSize = 0;
  25149. for (let i = 0; i < inSize; i++) {
  25150. pSize++;
  25151. q = q.nextZ;
  25152. if (!q) break;
  25153. }
  25154. let qSize = inSize;
  25155. while (pSize > 0 || (qSize > 0 && q)) {
  25156. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25157. e = p;
  25158. p = p.nextZ;
  25159. pSize--;
  25160. } else {
  25161. e = q;
  25162. q = q.nextZ;
  25163. qSize--;
  25164. }
  25165. if (tail) tail.nextZ = e;
  25166. else list = e;
  25167. e.prevZ = tail;
  25168. tail = e;
  25169. }
  25170. p = q;
  25171. }
  25172. tail.nextZ = null;
  25173. inSize *= 2;
  25174. } while (numMerges > 1);
  25175. return list;
  25176. }
  25177. // z-order of a point given coords and inverse of the longer side of data bbox
  25178. function zOrder(x, y, minX, minY, invSize) {
  25179. // coords are transformed into non-negative 15-bit integer range
  25180. x = (x - minX) * invSize | 0;
  25181. y = (y - minY) * invSize | 0;
  25182. x = (x | (x << 8)) & 0x00FF00FF;
  25183. x = (x | (x << 4)) & 0x0F0F0F0F;
  25184. x = (x | (x << 2)) & 0x33333333;
  25185. x = (x | (x << 1)) & 0x55555555;
  25186. y = (y | (y << 8)) & 0x00FF00FF;
  25187. y = (y | (y << 4)) & 0x0F0F0F0F;
  25188. y = (y | (y << 2)) & 0x33333333;
  25189. y = (y | (y << 1)) & 0x55555555;
  25190. return x | (y << 1);
  25191. }
  25192. // find the leftmost node of a polygon ring
  25193. function getLeftmost(start) {
  25194. let p = start,
  25195. leftmost = start;
  25196. do {
  25197. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25198. p = p.next;
  25199. } while (p !== start);
  25200. return leftmost;
  25201. }
  25202. // check if a point lies within a convex triangle
  25203. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25204. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25205. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25206. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25207. }
  25208. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25209. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25210. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25211. }
  25212. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25213. function isValidDiagonal(a, b) {
  25214. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25215. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25216. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25217. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25218. }
  25219. // signed area of a triangle
  25220. function area(p, q, r) {
  25221. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25222. }
  25223. // check if two points are equal
  25224. function equals(p1, p2) {
  25225. return p1.x === p2.x && p1.y === p2.y;
  25226. }
  25227. // check if two segments intersect
  25228. function intersects(p1, q1, p2, q2) {
  25229. const o1 = sign(area(p1, q1, p2));
  25230. const o2 = sign(area(p1, q1, q2));
  25231. const o3 = sign(area(p2, q2, p1));
  25232. const o4 = sign(area(p2, q2, q1));
  25233. if (o1 !== o2 && o3 !== o4) return true; // general case
  25234. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25235. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25236. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25237. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25238. return false;
  25239. }
  25240. // for collinear points p, q, r, check if point q lies on segment pr
  25241. function onSegment(p, q, r) {
  25242. 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);
  25243. }
  25244. function sign(num) {
  25245. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25246. }
  25247. // check if a polygon diagonal intersects any polygon segments
  25248. function intersectsPolygon(a, b) {
  25249. let p = a;
  25250. do {
  25251. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25252. intersects(p, p.next, a, b)) return true;
  25253. p = p.next;
  25254. } while (p !== a);
  25255. return false;
  25256. }
  25257. // check if a polygon diagonal is locally inside the polygon
  25258. function locallyInside(a, b) {
  25259. return area(a.prev, a, a.next) < 0 ?
  25260. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25261. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25262. }
  25263. // check if the middle point of a polygon diagonal is inside the polygon
  25264. function middleInside(a, b) {
  25265. let p = a;
  25266. let inside = false;
  25267. const px = (a.x + b.x) / 2;
  25268. const py = (a.y + b.y) / 2;
  25269. do {
  25270. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25271. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25272. inside = !inside;
  25273. p = p.next;
  25274. } while (p !== a);
  25275. return inside;
  25276. }
  25277. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25278. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25279. function splitPolygon(a, b) {
  25280. const a2 = createNode(a.i, a.x, a.y),
  25281. b2 = createNode(b.i, b.x, b.y),
  25282. an = a.next,
  25283. bp = b.prev;
  25284. a.next = b;
  25285. b.prev = a;
  25286. a2.next = an;
  25287. an.prev = a2;
  25288. b2.next = a2;
  25289. a2.prev = b2;
  25290. bp.next = b2;
  25291. b2.prev = bp;
  25292. return b2;
  25293. }
  25294. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25295. function insertNode(i, x, y, last) {
  25296. const p = createNode(i, x, y);
  25297. if (!last) {
  25298. p.prev = p;
  25299. p.next = p;
  25300. } else {
  25301. p.next = last.next;
  25302. p.prev = last;
  25303. last.next.prev = p;
  25304. last.next = p;
  25305. }
  25306. return p;
  25307. }
  25308. function removeNode(p) {
  25309. p.next.prev = p.prev;
  25310. p.prev.next = p.next;
  25311. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25312. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25313. }
  25314. function createNode(i, x, y) {
  25315. return {
  25316. i, // vertex index in coordinates array
  25317. x, y, // vertex coordinates
  25318. prev: null, // previous and next vertex nodes in a polygon ring
  25319. next: null,
  25320. z: 0, // z-order curve value
  25321. prevZ: null, // previous and next nodes in z-order
  25322. nextZ: null,
  25323. steiner: false // indicates whether this is a steiner point
  25324. };
  25325. }
  25326. function signedArea(data, start, end, dim) {
  25327. let sum = 0;
  25328. for (let i = start, j = end - dim; i < end; i += dim) {
  25329. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25330. j = i;
  25331. }
  25332. return sum;
  25333. }
  25334. /**
  25335. * An implementation of the earcut polygon triangulation algorithm.
  25336. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25337. *
  25338. * @see https://github.com/mapbox/earcut
  25339. */
  25340. class Earcut {
  25341. /**
  25342. * Triangulates the given shape definition by returning an array of triangles.
  25343. *
  25344. * @param {Array<number>} data - An array with 2D points.
  25345. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25346. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25347. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25348. * representing vertex indices.
  25349. */
  25350. static triangulate( data, holeIndices, dim = 2 ) {
  25351. return earcut( data, holeIndices, dim );
  25352. }
  25353. }
  25354. /**
  25355. * A class containing utility functions for shapes.
  25356. *
  25357. * @hideconstructor
  25358. */
  25359. class ShapeUtils {
  25360. /**
  25361. * Calculate area of a ( 2D ) contour polygon.
  25362. *
  25363. * @param {Array<Vector2>} contour - An array of 2D points.
  25364. * @return {number} The area.
  25365. */
  25366. static area( contour ) {
  25367. const n = contour.length;
  25368. let a = 0.0;
  25369. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25370. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25371. }
  25372. return a * 0.5;
  25373. }
  25374. /**
  25375. * Returns `true` if the given contour uses a clockwise winding order.
  25376. *
  25377. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25378. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25379. */
  25380. static isClockWise( pts ) {
  25381. return ShapeUtils.area( pts ) < 0;
  25382. }
  25383. /**
  25384. * Triangulates the given shape definition.
  25385. *
  25386. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25387. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25388. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25389. */
  25390. static triangulateShape( contour, holes ) {
  25391. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25392. const holeIndices = []; // array of hole indices
  25393. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25394. removeDupEndPts( contour );
  25395. addContour( vertices, contour );
  25396. //
  25397. let holeIndex = contour.length;
  25398. holes.forEach( removeDupEndPts );
  25399. for ( let i = 0; i < holes.length; i ++ ) {
  25400. holeIndices.push( holeIndex );
  25401. holeIndex += holes[ i ].length;
  25402. addContour( vertices, holes[ i ] );
  25403. }
  25404. //
  25405. const triangles = Earcut.triangulate( vertices, holeIndices );
  25406. //
  25407. for ( let i = 0; i < triangles.length; i += 3 ) {
  25408. faces.push( triangles.slice( i, i + 3 ) );
  25409. }
  25410. return faces;
  25411. }
  25412. }
  25413. function removeDupEndPts( points ) {
  25414. const l = points.length;
  25415. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25416. points.pop();
  25417. }
  25418. }
  25419. function addContour( vertices, contour ) {
  25420. for ( let i = 0; i < contour.length; i ++ ) {
  25421. vertices.push( contour[ i ].x );
  25422. vertices.push( contour[ i ].y );
  25423. }
  25424. }
  25425. /**
  25426. * Creates extruded geometry from a path shape.
  25427. *
  25428. * ```js
  25429. * const length = 12, width = 8;
  25430. *
  25431. * const shape = new THREE.Shape();
  25432. * shape.moveTo( 0,0 );
  25433. * shape.lineTo( 0, width );
  25434. * shape.lineTo( length, width );
  25435. * shape.lineTo( length, 0 );
  25436. * shape.lineTo( 0, 0 );
  25437. *
  25438. * const geometry = new THREE.ExtrudeGeometry( shape );
  25439. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25440. * const mesh = new THREE.Mesh( geometry, material ) ;
  25441. * scene.add( mesh );
  25442. * ```
  25443. *
  25444. * @augments BufferGeometry
  25445. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25446. */
  25447. class ExtrudeGeometry extends BufferGeometry {
  25448. /**
  25449. * Constructs a new extrude geometry.
  25450. *
  25451. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25452. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25453. */
  25454. 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 = {} ) {
  25455. super();
  25456. this.type = 'ExtrudeGeometry';
  25457. /**
  25458. * Holds the constructor parameters that have been
  25459. * used to generate the geometry. Any modification
  25460. * after instantiation does not change the geometry.
  25461. *
  25462. * @type {Object}
  25463. */
  25464. this.parameters = {
  25465. shapes: shapes,
  25466. options: options
  25467. };
  25468. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25469. const scope = this;
  25470. const verticesArray = [];
  25471. const uvArray = [];
  25472. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25473. const shape = shapes[ i ];
  25474. addShape( shape );
  25475. }
  25476. // build geometry
  25477. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25478. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25479. this.computeVertexNormals();
  25480. // functions
  25481. function addShape( shape ) {
  25482. const placeholder = [];
  25483. // options
  25484. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25485. const steps = options.steps !== undefined ? options.steps : 1;
  25486. const depth = options.depth !== undefined ? options.depth : 1;
  25487. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25488. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25489. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25490. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25491. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25492. const extrudePath = options.extrudePath;
  25493. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25494. //
  25495. let extrudePts, extrudeByPath = false;
  25496. let splineTube, binormal, normal, position2;
  25497. if ( extrudePath ) {
  25498. extrudePts = extrudePath.getSpacedPoints( steps );
  25499. extrudeByPath = true;
  25500. bevelEnabled = false; // bevels not supported for path extrusion
  25501. // SETUP TNB variables
  25502. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25503. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25504. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25505. binormal = new Vector3();
  25506. normal = new Vector3();
  25507. position2 = new Vector3();
  25508. }
  25509. // Safeguards if bevels are not enabled
  25510. if ( ! bevelEnabled ) {
  25511. bevelSegments = 0;
  25512. bevelThickness = 0;
  25513. bevelSize = 0;
  25514. bevelOffset = 0;
  25515. }
  25516. // Variables initialization
  25517. const shapePoints = shape.extractPoints( curveSegments );
  25518. let vertices = shapePoints.shape;
  25519. const holes = shapePoints.holes;
  25520. const reverse = ! ShapeUtils.isClockWise( vertices );
  25521. if ( reverse ) {
  25522. vertices = vertices.reverse();
  25523. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25524. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25525. const ahole = holes[ h ];
  25526. if ( ShapeUtils.isClockWise( ahole ) ) {
  25527. holes[ h ] = ahole.reverse();
  25528. }
  25529. }
  25530. }
  25531. /**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.
  25532. * @param {Array<Vector2>} points
  25533. */
  25534. function mergeOverlappingPoints( points ) {
  25535. const THRESHOLD = 1e-10;
  25536. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25537. let prevPos = points[ 0 ];
  25538. for ( let i = 1; i <= points.length; i ++ ) {
  25539. const currentIndex = i % points.length;
  25540. const currentPos = points[ currentIndex ];
  25541. const dx = currentPos.x - prevPos.x;
  25542. const dy = currentPos.y - prevPos.y;
  25543. const distSq = dx * dx + dy * dy;
  25544. const scalingFactorSqrt = Math.max(
  25545. Math.abs( currentPos.x ),
  25546. Math.abs( currentPos.y ),
  25547. Math.abs( prevPos.x ),
  25548. Math.abs( prevPos.y )
  25549. );
  25550. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25551. if ( distSq <= thresholdSqScaled ) {
  25552. points.splice( currentIndex, 1 );
  25553. i --;
  25554. continue;
  25555. }
  25556. prevPos = currentPos;
  25557. }
  25558. }
  25559. mergeOverlappingPoints( vertices );
  25560. holes.forEach( mergeOverlappingPoints );
  25561. const numHoles = holes.length;
  25562. /* Vertices */
  25563. const contour = vertices; // vertices has all points but contour has only points of circumference
  25564. for ( let h = 0; h < numHoles; h ++ ) {
  25565. const ahole = holes[ h ];
  25566. vertices = vertices.concat( ahole );
  25567. }
  25568. function scalePt2( pt, vec, size ) {
  25569. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25570. return pt.clone().addScaledVector( vec, size );
  25571. }
  25572. const vlen = vertices.length;
  25573. // Find directions for point movement
  25574. function getBevelVec( inPt, inPrev, inNext ) {
  25575. // computes for inPt the corresponding point inPt' on a new contour
  25576. // shifted by 1 unit (length of normalized vector) to the left
  25577. // if we walk along contour clockwise, this new contour is outside the old one
  25578. //
  25579. // inPt' is the intersection of the two lines parallel to the two
  25580. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25581. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25582. // good reading for geometry algorithms (here: line-line intersection)
  25583. // http://geomalgorithms.com/a05-_intersect-1.html
  25584. const v_prev_x = inPt.x - inPrev.x,
  25585. v_prev_y = inPt.y - inPrev.y;
  25586. const v_next_x = inNext.x - inPt.x,
  25587. v_next_y = inNext.y - inPt.y;
  25588. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25589. // check for collinear edges
  25590. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25591. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25592. // not collinear
  25593. // length of vectors for normalizing
  25594. const v_prev_len = Math.sqrt( v_prev_lensq );
  25595. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25596. // shift adjacent points by unit vectors to the left
  25597. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25598. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25599. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25600. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25601. // scaling factor for v_prev to intersection point
  25602. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25603. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25604. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25605. // vector from inPt to intersection point
  25606. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25607. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25608. // Don't normalize!, otherwise sharp corners become ugly
  25609. // but prevent crazy spikes
  25610. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25611. if ( v_trans_lensq <= 2 ) {
  25612. return new Vector2( v_trans_x, v_trans_y );
  25613. } else {
  25614. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25615. }
  25616. } else {
  25617. // handle special case of collinear edges
  25618. let direction_eq = false; // assumes: opposite
  25619. if ( v_prev_x > Number.EPSILON ) {
  25620. if ( v_next_x > Number.EPSILON ) {
  25621. direction_eq = true;
  25622. }
  25623. } else {
  25624. if ( v_prev_x < - Number.EPSILON ) {
  25625. if ( v_next_x < - Number.EPSILON ) {
  25626. direction_eq = true;
  25627. }
  25628. } else {
  25629. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25630. direction_eq = true;
  25631. }
  25632. }
  25633. }
  25634. if ( direction_eq ) {
  25635. // log("Warning: lines are a straight sequence");
  25636. v_trans_x = - v_prev_y;
  25637. v_trans_y = v_prev_x;
  25638. shrink_by = Math.sqrt( v_prev_lensq );
  25639. } else {
  25640. // log("Warning: lines are a straight spike");
  25641. v_trans_x = v_prev_x;
  25642. v_trans_y = v_prev_y;
  25643. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25644. }
  25645. }
  25646. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25647. }
  25648. const contourMovements = [];
  25649. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25650. if ( j === il ) j = 0;
  25651. if ( k === il ) k = 0;
  25652. // (j)---(i)---(k)
  25653. // log('i,j,k', i, j , k)
  25654. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25655. }
  25656. const holesMovements = [];
  25657. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25658. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25659. const ahole = holes[ h ];
  25660. oneHoleMovements = [];
  25661. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25662. if ( j === il ) j = 0;
  25663. if ( k === il ) k = 0;
  25664. // (j)---(i)---(k)
  25665. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25666. }
  25667. holesMovements.push( oneHoleMovements );
  25668. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25669. }
  25670. let faces;
  25671. if ( bevelSegments === 0 ) {
  25672. faces = ShapeUtils.triangulateShape( contour, holes );
  25673. } else {
  25674. const contractedContourVertices = [];
  25675. const expandedHoleVertices = [];
  25676. // Loop bevelSegments, 1 for the front, 1 for the back
  25677. for ( let b = 0; b < bevelSegments; b ++ ) {
  25678. //for ( b = bevelSegments; b > 0; b -- ) {
  25679. const t = b / bevelSegments;
  25680. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25681. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25682. // contract shape
  25683. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25684. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25685. v( vert.x, vert.y, - z );
  25686. if ( t === 0 ) contractedContourVertices.push( vert );
  25687. }
  25688. // expand holes
  25689. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25690. const ahole = holes[ h ];
  25691. oneHoleMovements = holesMovements[ h ];
  25692. const oneHoleVertices = [];
  25693. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25694. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25695. v( vert.x, vert.y, - z );
  25696. if ( t === 0 ) oneHoleVertices.push( vert );
  25697. }
  25698. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25699. }
  25700. }
  25701. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25702. }
  25703. const flen = faces.length;
  25704. const bs = bevelSize + bevelOffset;
  25705. // Back facing vertices
  25706. for ( let i = 0; i < vlen; i ++ ) {
  25707. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25708. if ( ! extrudeByPath ) {
  25709. v( vert.x, vert.y, 0 );
  25710. } else {
  25711. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25712. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25713. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25714. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25715. v( position2.x, position2.y, position2.z );
  25716. }
  25717. }
  25718. // Add stepped vertices...
  25719. // Including front facing vertices
  25720. for ( let s = 1; s <= steps; s ++ ) {
  25721. for ( let i = 0; i < vlen; i ++ ) {
  25722. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25723. if ( ! extrudeByPath ) {
  25724. v( vert.x, vert.y, depth / steps * s );
  25725. } else {
  25726. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25727. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25728. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25729. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25730. v( position2.x, position2.y, position2.z );
  25731. }
  25732. }
  25733. }
  25734. // Add bevel segments planes
  25735. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25736. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25737. const t = b / bevelSegments;
  25738. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25739. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25740. // contract shape
  25741. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25742. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25743. v( vert.x, vert.y, depth + z );
  25744. }
  25745. // expand holes
  25746. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25747. const ahole = holes[ h ];
  25748. oneHoleMovements = holesMovements[ h ];
  25749. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25750. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25751. if ( ! extrudeByPath ) {
  25752. v( vert.x, vert.y, depth + z );
  25753. } else {
  25754. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25755. }
  25756. }
  25757. }
  25758. }
  25759. /* Faces */
  25760. // Top and bottom faces
  25761. buildLidFaces();
  25762. // Sides faces
  25763. buildSideFaces();
  25764. ///// Internal functions
  25765. function buildLidFaces() {
  25766. const start = verticesArray.length / 3;
  25767. if ( bevelEnabled ) {
  25768. let layer = 0; // steps + 1
  25769. let offset = vlen * layer;
  25770. // Bottom faces
  25771. for ( let i = 0; i < flen; i ++ ) {
  25772. const face = faces[ i ];
  25773. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25774. }
  25775. layer = steps + bevelSegments * 2;
  25776. offset = vlen * layer;
  25777. // Top faces
  25778. for ( let i = 0; i < flen; i ++ ) {
  25779. const face = faces[ i ];
  25780. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25781. }
  25782. } else {
  25783. // Bottom faces
  25784. for ( let i = 0; i < flen; i ++ ) {
  25785. const face = faces[ i ];
  25786. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  25787. }
  25788. // Top faces
  25789. for ( let i = 0; i < flen; i ++ ) {
  25790. const face = faces[ i ];
  25791. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  25792. }
  25793. }
  25794. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  25795. }
  25796. // Create faces for the z-sides of the shape
  25797. function buildSideFaces() {
  25798. const start = verticesArray.length / 3;
  25799. let layeroffset = 0;
  25800. sidewalls( contour, layeroffset );
  25801. layeroffset += contour.length;
  25802. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25803. const ahole = holes[ h ];
  25804. sidewalls( ahole, layeroffset );
  25805. //, true
  25806. layeroffset += ahole.length;
  25807. }
  25808. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  25809. }
  25810. function sidewalls( contour, layeroffset ) {
  25811. let i = contour.length;
  25812. while ( -- i >= 0 ) {
  25813. const j = i;
  25814. let k = i - 1;
  25815. if ( k < 0 ) k = contour.length - 1;
  25816. //log('b', i,j, i-1, k,vertices.length);
  25817. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  25818. const slen1 = vlen * s;
  25819. const slen2 = vlen * ( s + 1 );
  25820. const a = layeroffset + j + slen1,
  25821. b = layeroffset + k + slen1,
  25822. c = layeroffset + k + slen2,
  25823. d = layeroffset + j + slen2;
  25824. f4( a, b, c, d );
  25825. }
  25826. }
  25827. }
  25828. function v( x, y, z ) {
  25829. placeholder.push( x );
  25830. placeholder.push( y );
  25831. placeholder.push( z );
  25832. }
  25833. function f3( a, b, c ) {
  25834. addVertex( a );
  25835. addVertex( b );
  25836. addVertex( c );
  25837. const nextIndex = verticesArray.length / 3;
  25838. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25839. addUV( uvs[ 0 ] );
  25840. addUV( uvs[ 1 ] );
  25841. addUV( uvs[ 2 ] );
  25842. }
  25843. function f4( a, b, c, d ) {
  25844. addVertex( a );
  25845. addVertex( b );
  25846. addVertex( d );
  25847. addVertex( b );
  25848. addVertex( c );
  25849. addVertex( d );
  25850. const nextIndex = verticesArray.length / 3;
  25851. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  25852. addUV( uvs[ 0 ] );
  25853. addUV( uvs[ 1 ] );
  25854. addUV( uvs[ 3 ] );
  25855. addUV( uvs[ 1 ] );
  25856. addUV( uvs[ 2 ] );
  25857. addUV( uvs[ 3 ] );
  25858. }
  25859. function addVertex( index ) {
  25860. verticesArray.push( placeholder[ index * 3 + 0 ] );
  25861. verticesArray.push( placeholder[ index * 3 + 1 ] );
  25862. verticesArray.push( placeholder[ index * 3 + 2 ] );
  25863. }
  25864. function addUV( vector2 ) {
  25865. uvArray.push( vector2.x );
  25866. uvArray.push( vector2.y );
  25867. }
  25868. }
  25869. }
  25870. copy( source ) {
  25871. super.copy( source );
  25872. this.parameters = Object.assign( {}, source.parameters );
  25873. return this;
  25874. }
  25875. toJSON() {
  25876. const data = super.toJSON();
  25877. const shapes = this.parameters.shapes;
  25878. const options = this.parameters.options;
  25879. return toJSON$1( shapes, options, data );
  25880. }
  25881. /**
  25882. * Factory method for creating an instance of this class from the given
  25883. * JSON object.
  25884. *
  25885. * @param {Object} data - A JSON object representing the serialized geometry.
  25886. * @param {Array<Shape>} shapes - An array of shapes.
  25887. * @return {ExtrudeGeometry} A new instance.
  25888. */
  25889. static fromJSON( data, shapes ) {
  25890. const geometryShapes = [];
  25891. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25892. const shape = shapes[ data.shapes[ j ] ];
  25893. geometryShapes.push( shape );
  25894. }
  25895. const extrudePath = data.options.extrudePath;
  25896. if ( extrudePath !== undefined ) {
  25897. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25898. }
  25899. return new ExtrudeGeometry( geometryShapes, data.options );
  25900. }
  25901. }
  25902. const WorldUVGenerator = {
  25903. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  25904. const a_x = vertices[ indexA * 3 ];
  25905. const a_y = vertices[ indexA * 3 + 1 ];
  25906. const b_x = vertices[ indexB * 3 ];
  25907. const b_y = vertices[ indexB * 3 + 1 ];
  25908. const c_x = vertices[ indexC * 3 ];
  25909. const c_y = vertices[ indexC * 3 + 1 ];
  25910. return [
  25911. new Vector2( a_x, a_y ),
  25912. new Vector2( b_x, b_y ),
  25913. new Vector2( c_x, c_y )
  25914. ];
  25915. },
  25916. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  25917. const a_x = vertices[ indexA * 3 ];
  25918. const a_y = vertices[ indexA * 3 + 1 ];
  25919. const a_z = vertices[ indexA * 3 + 2 ];
  25920. const b_x = vertices[ indexB * 3 ];
  25921. const b_y = vertices[ indexB * 3 + 1 ];
  25922. const b_z = vertices[ indexB * 3 + 2 ];
  25923. const c_x = vertices[ indexC * 3 ];
  25924. const c_y = vertices[ indexC * 3 + 1 ];
  25925. const c_z = vertices[ indexC * 3 + 2 ];
  25926. const d_x = vertices[ indexD * 3 ];
  25927. const d_y = vertices[ indexD * 3 + 1 ];
  25928. const d_z = vertices[ indexD * 3 + 2 ];
  25929. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  25930. return [
  25931. new Vector2( a_x, 1 - a_z ),
  25932. new Vector2( b_x, 1 - b_z ),
  25933. new Vector2( c_x, 1 - c_z ),
  25934. new Vector2( d_x, 1 - d_z )
  25935. ];
  25936. } else {
  25937. return [
  25938. new Vector2( a_y, 1 - a_z ),
  25939. new Vector2( b_y, 1 - b_z ),
  25940. new Vector2( c_y, 1 - c_z ),
  25941. new Vector2( d_y, 1 - d_z )
  25942. ];
  25943. }
  25944. }
  25945. };
  25946. function toJSON$1( shapes, options, data ) {
  25947. data.shapes = [];
  25948. if ( Array.isArray( shapes ) ) {
  25949. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25950. const shape = shapes[ i ];
  25951. data.shapes.push( shape.uuid );
  25952. }
  25953. } else {
  25954. data.shapes.push( shapes.uuid );
  25955. }
  25956. data.options = Object.assign( {}, options );
  25957. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  25958. return data;
  25959. }
  25960. /**
  25961. * A geometry class for representing an icosahedron.
  25962. *
  25963. * ```js
  25964. * const geometry = new THREE.IcosahedronGeometry();
  25965. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  25966. * const icosahedron = new THREE.Mesh( geometry, material );
  25967. * scene.add( icosahedron );
  25968. * ```
  25969. *
  25970. * @augments PolyhedronGeometry
  25971. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  25972. */
  25973. class IcosahedronGeometry extends PolyhedronGeometry {
  25974. /**
  25975. * Constructs a new icosahedron geometry.
  25976. *
  25977. * @param {number} [radius=1] - Radius of the icosahedron.
  25978. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  25979. */
  25980. constructor( radius = 1, detail = 0 ) {
  25981. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  25982. const vertices = [
  25983. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  25984. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  25985. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  25986. ];
  25987. const indices = [
  25988. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  25989. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  25990. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  25991. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  25992. ];
  25993. super( vertices, indices, radius, detail );
  25994. this.type = 'IcosahedronGeometry';
  25995. /**
  25996. * Holds the constructor parameters that have been
  25997. * used to generate the geometry. Any modification
  25998. * after instantiation does not change the geometry.
  25999. *
  26000. * @type {Object}
  26001. */
  26002. this.parameters = {
  26003. radius: radius,
  26004. detail: detail
  26005. };
  26006. }
  26007. /**
  26008. * Factory method for creating an instance of this class from the given
  26009. * JSON object.
  26010. *
  26011. * @param {Object} data - A JSON object representing the serialized geometry.
  26012. * @return {IcosahedronGeometry} A new instance.
  26013. */
  26014. static fromJSON( data ) {
  26015. return new IcosahedronGeometry( data.radius, data.detail );
  26016. }
  26017. }
  26018. /**
  26019. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26020. *
  26021. * ```js
  26022. * const points = [];
  26023. * for ( let i = 0; i < 10; i ++ ) {
  26024. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26025. * }
  26026. * const geometry = new THREE.LatheGeometry( points );
  26027. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26028. * const lathe = new THREE.Mesh( geometry, material );
  26029. * scene.add( lathe );
  26030. * ```
  26031. *
  26032. * @augments BufferGeometry
  26033. * @demo scenes/geometry-browser.html#LatheGeometry
  26034. */
  26035. class LatheGeometry extends BufferGeometry {
  26036. /**
  26037. * Constructs a new lathe geometry.
  26038. *
  26039. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26040. * must be greater than zero.
  26041. * @param {number} [segments=12] - The number of circumference segments to generate.
  26042. * @param {number} [phiStart=0] - The starting angle in radians.
  26043. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26044. * closed lathe, less than 2PI is a portion.
  26045. */
  26046. 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 ) {
  26047. super();
  26048. this.type = 'LatheGeometry';
  26049. /**
  26050. * Holds the constructor parameters that have been
  26051. * used to generate the geometry. Any modification
  26052. * after instantiation does not change the geometry.
  26053. *
  26054. * @type {Object}
  26055. */
  26056. this.parameters = {
  26057. points: points,
  26058. segments: segments,
  26059. phiStart: phiStart,
  26060. phiLength: phiLength
  26061. };
  26062. segments = Math.floor( segments );
  26063. // clamp phiLength so it's in range of [ 0, 2PI ]
  26064. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26065. // buffers
  26066. const indices = [];
  26067. const vertices = [];
  26068. const uvs = [];
  26069. const initNormals = [];
  26070. const normals = [];
  26071. // helper variables
  26072. const inverseSegments = 1.0 / segments;
  26073. const vertex = new Vector3();
  26074. const uv = new Vector2();
  26075. const normal = new Vector3();
  26076. const curNormal = new Vector3();
  26077. const prevNormal = new Vector3();
  26078. let dx = 0;
  26079. let dy = 0;
  26080. // pre-compute normals for initial "meridian"
  26081. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26082. switch ( j ) {
  26083. case 0: // special handling for 1st vertex on path
  26084. dx = points[ j + 1 ].x - points[ j ].x;
  26085. dy = points[ j + 1 ].y - points[ j ].y;
  26086. normal.x = dy * 1.0;
  26087. normal.y = - dx;
  26088. normal.z = dy * 0.0;
  26089. prevNormal.copy( normal );
  26090. normal.normalize();
  26091. initNormals.push( normal.x, normal.y, normal.z );
  26092. break;
  26093. case ( points.length - 1 ): // special handling for last Vertex on path
  26094. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26095. break;
  26096. default: // default handling for all vertices in between
  26097. dx = points[ j + 1 ].x - points[ j ].x;
  26098. dy = points[ j + 1 ].y - points[ j ].y;
  26099. normal.x = dy * 1.0;
  26100. normal.y = - dx;
  26101. normal.z = dy * 0.0;
  26102. curNormal.copy( normal );
  26103. normal.x += prevNormal.x;
  26104. normal.y += prevNormal.y;
  26105. normal.z += prevNormal.z;
  26106. normal.normalize();
  26107. initNormals.push( normal.x, normal.y, normal.z );
  26108. prevNormal.copy( curNormal );
  26109. }
  26110. }
  26111. // generate vertices, uvs and normals
  26112. for ( let i = 0; i <= segments; i ++ ) {
  26113. const phi = phiStart + i * inverseSegments * phiLength;
  26114. const sin = Math.sin( phi );
  26115. const cos = Math.cos( phi );
  26116. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26117. // vertex
  26118. vertex.x = points[ j ].x * sin;
  26119. vertex.y = points[ j ].y;
  26120. vertex.z = points[ j ].x * cos;
  26121. vertices.push( vertex.x, vertex.y, vertex.z );
  26122. // uv
  26123. uv.x = i / segments;
  26124. uv.y = j / ( points.length - 1 );
  26125. uvs.push( uv.x, uv.y );
  26126. // normal
  26127. const x = initNormals[ 3 * j + 0 ] * sin;
  26128. const y = initNormals[ 3 * j + 1 ];
  26129. const z = initNormals[ 3 * j + 0 ] * cos;
  26130. normals.push( x, y, z );
  26131. }
  26132. }
  26133. // indices
  26134. for ( let i = 0; i < segments; i ++ ) {
  26135. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26136. const base = j + i * points.length;
  26137. const a = base;
  26138. const b = base + points.length;
  26139. const c = base + points.length + 1;
  26140. const d = base + 1;
  26141. // faces
  26142. indices.push( a, b, d );
  26143. indices.push( c, d, b );
  26144. }
  26145. }
  26146. // build geometry
  26147. this.setIndex( indices );
  26148. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26149. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26150. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26151. }
  26152. copy( source ) {
  26153. super.copy( source );
  26154. this.parameters = Object.assign( {}, source.parameters );
  26155. return this;
  26156. }
  26157. /**
  26158. * Factory method for creating an instance of this class from the given
  26159. * JSON object.
  26160. *
  26161. * @param {Object} data - A JSON object representing the serialized geometry.
  26162. * @return {LatheGeometry} A new instance.
  26163. */
  26164. static fromJSON( data ) {
  26165. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26166. }
  26167. }
  26168. /**
  26169. * A geometry class for representing an octahedron.
  26170. *
  26171. * ```js
  26172. * const geometry = new THREE.OctahedronGeometry();
  26173. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26174. * const octahedron = new THREE.Mesh( geometry, material );
  26175. * scene.add( octahedron );
  26176. * ```
  26177. *
  26178. * @augments PolyhedronGeometry
  26179. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26180. */
  26181. class OctahedronGeometry extends PolyhedronGeometry {
  26182. /**
  26183. * Constructs a new octahedron geometry.
  26184. *
  26185. * @param {number} [radius=1] - Radius of the octahedron.
  26186. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26187. */
  26188. constructor( radius = 1, detail = 0 ) {
  26189. const vertices = [
  26190. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26191. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26192. ];
  26193. const indices = [
  26194. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26195. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26196. 1, 3, 4, 1, 4, 2
  26197. ];
  26198. super( vertices, indices, radius, detail );
  26199. this.type = 'OctahedronGeometry';
  26200. /**
  26201. * Holds the constructor parameters that have been
  26202. * used to generate the geometry. Any modification
  26203. * after instantiation does not change the geometry.
  26204. *
  26205. * @type {Object}
  26206. */
  26207. this.parameters = {
  26208. radius: radius,
  26209. detail: detail
  26210. };
  26211. }
  26212. /**
  26213. * Factory method for creating an instance of this class from the given
  26214. * JSON object.
  26215. *
  26216. * @param {Object} data - A JSON object representing the serialized geometry.
  26217. * @return {OctahedronGeometry} A new instance.
  26218. */
  26219. static fromJSON( data ) {
  26220. return new OctahedronGeometry( data.radius, data.detail );
  26221. }
  26222. }
  26223. /**
  26224. * A geometry class for representing a plane.
  26225. *
  26226. * ```js
  26227. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26228. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26229. * const plane = new THREE.Mesh( geometry, material );
  26230. * scene.add( plane );
  26231. * ```
  26232. *
  26233. * @augments BufferGeometry
  26234. * @demo scenes/geometry-browser.html#PlaneGeometry
  26235. */
  26236. class PlaneGeometry extends BufferGeometry {
  26237. /**
  26238. * Constructs a new plane geometry.
  26239. *
  26240. * @param {number} [width=1] - The width along the X axis.
  26241. * @param {number} [height=1] - The height along the Y axis
  26242. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26243. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26244. */
  26245. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26246. super();
  26247. this.type = 'PlaneGeometry';
  26248. /**
  26249. * Holds the constructor parameters that have been
  26250. * used to generate the geometry. Any modification
  26251. * after instantiation does not change the geometry.
  26252. *
  26253. * @type {Object}
  26254. */
  26255. this.parameters = {
  26256. width: width,
  26257. height: height,
  26258. widthSegments: widthSegments,
  26259. heightSegments: heightSegments
  26260. };
  26261. const width_half = width / 2;
  26262. const height_half = height / 2;
  26263. const gridX = Math.floor( widthSegments );
  26264. const gridY = Math.floor( heightSegments );
  26265. const gridX1 = gridX + 1;
  26266. const gridY1 = gridY + 1;
  26267. const segment_width = width / gridX;
  26268. const segment_height = height / gridY;
  26269. //
  26270. const indices = [];
  26271. const vertices = [];
  26272. const normals = [];
  26273. const uvs = [];
  26274. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26275. const y = iy * segment_height - height_half;
  26276. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26277. const x = ix * segment_width - width_half;
  26278. vertices.push( x, - y, 0 );
  26279. normals.push( 0, 0, 1 );
  26280. uvs.push( ix / gridX );
  26281. uvs.push( 1 - ( iy / gridY ) );
  26282. }
  26283. }
  26284. for ( let iy = 0; iy < gridY; iy ++ ) {
  26285. for ( let ix = 0; ix < gridX; ix ++ ) {
  26286. const a = ix + gridX1 * iy;
  26287. const b = ix + gridX1 * ( iy + 1 );
  26288. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26289. const d = ( ix + 1 ) + gridX1 * iy;
  26290. indices.push( a, b, d );
  26291. indices.push( b, c, d );
  26292. }
  26293. }
  26294. this.setIndex( indices );
  26295. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26296. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26297. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26298. }
  26299. copy( source ) {
  26300. super.copy( source );
  26301. this.parameters = Object.assign( {}, source.parameters );
  26302. return this;
  26303. }
  26304. /**
  26305. * Factory method for creating an instance of this class from the given
  26306. * JSON object.
  26307. *
  26308. * @param {Object} data - A JSON object representing the serialized geometry.
  26309. * @return {PlaneGeometry} A new instance.
  26310. */
  26311. static fromJSON( data ) {
  26312. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26313. }
  26314. }
  26315. /**
  26316. * A class for generating a two-dimensional ring geometry.
  26317. *
  26318. * ```js
  26319. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26320. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26321. * const mesh = new THREE.Mesh( geometry, material );
  26322. * scene.add( mesh );
  26323. * ```
  26324. *
  26325. * @augments BufferGeometry
  26326. * @demo scenes/geometry-browser.html#RingGeometry
  26327. */
  26328. class RingGeometry extends BufferGeometry {
  26329. /**
  26330. * Constructs a new ring geometry.
  26331. *
  26332. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26333. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26334. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26335. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26336. * @param {number} [thetaStart=0] - Starting angle in radians.
  26337. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26338. */
  26339. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26340. super();
  26341. this.type = 'RingGeometry';
  26342. /**
  26343. * Holds the constructor parameters that have been
  26344. * used to generate the geometry. Any modification
  26345. * after instantiation does not change the geometry.
  26346. *
  26347. * @type {Object}
  26348. */
  26349. this.parameters = {
  26350. innerRadius: innerRadius,
  26351. outerRadius: outerRadius,
  26352. thetaSegments: thetaSegments,
  26353. phiSegments: phiSegments,
  26354. thetaStart: thetaStart,
  26355. thetaLength: thetaLength
  26356. };
  26357. thetaSegments = Math.max( 3, thetaSegments );
  26358. phiSegments = Math.max( 1, phiSegments );
  26359. // buffers
  26360. const indices = [];
  26361. const vertices = [];
  26362. const normals = [];
  26363. const uvs = [];
  26364. // some helper variables
  26365. let radius = innerRadius;
  26366. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26367. const vertex = new Vector3();
  26368. const uv = new Vector2();
  26369. // generate vertices, normals and uvs
  26370. for ( let j = 0; j <= phiSegments; j ++ ) {
  26371. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26372. // values are generate from the inside of the ring to the outside
  26373. const segment = thetaStart + i / thetaSegments * thetaLength;
  26374. // vertex
  26375. vertex.x = radius * Math.cos( segment );
  26376. vertex.y = radius * Math.sin( segment );
  26377. vertices.push( vertex.x, vertex.y, vertex.z );
  26378. // normal
  26379. normals.push( 0, 0, 1 );
  26380. // uv
  26381. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26382. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26383. uvs.push( uv.x, uv.y );
  26384. }
  26385. // increase the radius for next row of vertices
  26386. radius += radiusStep;
  26387. }
  26388. // indices
  26389. for ( let j = 0; j < phiSegments; j ++ ) {
  26390. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26391. for ( let i = 0; i < thetaSegments; i ++ ) {
  26392. const segment = i + thetaSegmentLevel;
  26393. const a = segment;
  26394. const b = segment + thetaSegments + 1;
  26395. const c = segment + thetaSegments + 2;
  26396. const d = segment + 1;
  26397. // faces
  26398. indices.push( a, b, d );
  26399. indices.push( b, c, d );
  26400. }
  26401. }
  26402. // build geometry
  26403. this.setIndex( indices );
  26404. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26405. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26406. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26407. }
  26408. copy( source ) {
  26409. super.copy( source );
  26410. this.parameters = Object.assign( {}, source.parameters );
  26411. return this;
  26412. }
  26413. /**
  26414. * Factory method for creating an instance of this class from the given
  26415. * JSON object.
  26416. *
  26417. * @param {Object} data - A JSON object representing the serialized geometry.
  26418. * @return {RingGeometry} A new instance.
  26419. */
  26420. static fromJSON( data ) {
  26421. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26422. }
  26423. }
  26424. /**
  26425. * Creates an one-sided polygonal geometry from one or more path shapes.
  26426. *
  26427. * ```js
  26428. * const arcShape = new THREE.Shape()
  26429. * .moveTo( 5, 1 )
  26430. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26431. *
  26432. * const geometry = new THREE.ShapeGeometry( arcShape );
  26433. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26434. * const mesh = new THREE.Mesh( geometry, material ) ;
  26435. * scene.add( mesh );
  26436. * ```
  26437. *
  26438. * @augments BufferGeometry
  26439. * @demo scenes/geometry-browser.html#ShapeGeometry
  26440. */
  26441. class ShapeGeometry extends BufferGeometry {
  26442. /**
  26443. * Constructs a new shape geometry.
  26444. *
  26445. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26446. * @param {number} [curveSegments=12] - Number of segments per shape.
  26447. */
  26448. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26449. super();
  26450. this.type = 'ShapeGeometry';
  26451. /**
  26452. * Holds the constructor parameters that have been
  26453. * used to generate the geometry. Any modification
  26454. * after instantiation does not change the geometry.
  26455. *
  26456. * @type {Object}
  26457. */
  26458. this.parameters = {
  26459. shapes: shapes,
  26460. curveSegments: curveSegments
  26461. };
  26462. // buffers
  26463. const indices = [];
  26464. const vertices = [];
  26465. const normals = [];
  26466. const uvs = [];
  26467. // helper variables
  26468. let groupStart = 0;
  26469. let groupCount = 0;
  26470. // allow single and array values for "shapes" parameter
  26471. if ( Array.isArray( shapes ) === false ) {
  26472. addShape( shapes );
  26473. } else {
  26474. for ( let i = 0; i < shapes.length; i ++ ) {
  26475. addShape( shapes[ i ] );
  26476. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26477. groupStart += groupCount;
  26478. groupCount = 0;
  26479. }
  26480. }
  26481. // build geometry
  26482. this.setIndex( indices );
  26483. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26484. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26485. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26486. // helper functions
  26487. function addShape( shape ) {
  26488. const indexOffset = vertices.length / 3;
  26489. const points = shape.extractPoints( curveSegments );
  26490. let shapeVertices = points.shape;
  26491. const shapeHoles = points.holes;
  26492. // check direction of vertices
  26493. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26494. shapeVertices = shapeVertices.reverse();
  26495. }
  26496. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26497. const shapeHole = shapeHoles[ i ];
  26498. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26499. shapeHoles[ i ] = shapeHole.reverse();
  26500. }
  26501. }
  26502. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26503. // join vertices of inner and outer paths to a single array
  26504. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26505. const shapeHole = shapeHoles[ i ];
  26506. shapeVertices = shapeVertices.concat( shapeHole );
  26507. }
  26508. // vertices, normals, uvs
  26509. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26510. const vertex = shapeVertices[ i ];
  26511. vertices.push( vertex.x, vertex.y, 0 );
  26512. normals.push( 0, 0, 1 );
  26513. uvs.push( vertex.x, vertex.y ); // world uvs
  26514. }
  26515. // indices
  26516. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26517. const face = faces[ i ];
  26518. const a = face[ 0 ] + indexOffset;
  26519. const b = face[ 1 ] + indexOffset;
  26520. const c = face[ 2 ] + indexOffset;
  26521. indices.push( a, b, c );
  26522. groupCount += 3;
  26523. }
  26524. }
  26525. }
  26526. copy( source ) {
  26527. super.copy( source );
  26528. this.parameters = Object.assign( {}, source.parameters );
  26529. return this;
  26530. }
  26531. toJSON() {
  26532. const data = super.toJSON();
  26533. const shapes = this.parameters.shapes;
  26534. return toJSON( shapes, data );
  26535. }
  26536. /**
  26537. * Factory method for creating an instance of this class from the given
  26538. * JSON object.
  26539. *
  26540. * @param {Object} data - A JSON object representing the serialized geometry.
  26541. * @param {Array<Shape>} shapes - An array of shapes.
  26542. * @return {ShapeGeometry} A new instance.
  26543. */
  26544. static fromJSON( data, shapes ) {
  26545. const geometryShapes = [];
  26546. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26547. const shape = shapes[ data.shapes[ j ] ];
  26548. geometryShapes.push( shape );
  26549. }
  26550. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26551. }
  26552. }
  26553. function toJSON( shapes, data ) {
  26554. data.shapes = [];
  26555. if ( Array.isArray( shapes ) ) {
  26556. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26557. const shape = shapes[ i ];
  26558. data.shapes.push( shape.uuid );
  26559. }
  26560. } else {
  26561. data.shapes.push( shapes.uuid );
  26562. }
  26563. return data;
  26564. }
  26565. /**
  26566. * A class for generating a sphere geometry.
  26567. *
  26568. * ```js
  26569. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26570. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26571. * const sphere = new THREE.Mesh( geometry, material );
  26572. * scene.add( sphere );
  26573. * ```
  26574. *
  26575. * @augments BufferGeometry
  26576. * @demo scenes/geometry-browser.html#SphereGeometry
  26577. */
  26578. class SphereGeometry extends BufferGeometry {
  26579. /**
  26580. * Constructs a new sphere geometry.
  26581. *
  26582. * @param {number} [radius=1] - The sphere radius.
  26583. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26584. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26585. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26586. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26587. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26588. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26589. */
  26590. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26591. super();
  26592. this.type = 'SphereGeometry';
  26593. /**
  26594. * Holds the constructor parameters that have been
  26595. * used to generate the geometry. Any modification
  26596. * after instantiation does not change the geometry.
  26597. *
  26598. * @type {Object}
  26599. */
  26600. this.parameters = {
  26601. radius: radius,
  26602. widthSegments: widthSegments,
  26603. heightSegments: heightSegments,
  26604. phiStart: phiStart,
  26605. phiLength: phiLength,
  26606. thetaStart: thetaStart,
  26607. thetaLength: thetaLength
  26608. };
  26609. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26610. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26611. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26612. let index = 0;
  26613. const grid = [];
  26614. const vertex = new Vector3();
  26615. const normal = new Vector3();
  26616. // buffers
  26617. const indices = [];
  26618. const vertices = [];
  26619. const normals = [];
  26620. const uvs = [];
  26621. // generate vertices, normals and uvs
  26622. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26623. const verticesRow = [];
  26624. const v = iy / heightSegments;
  26625. const theta = thetaStart + v * thetaLength;
  26626. const y = radius * Math.cos( theta );
  26627. const ringRadius = Math.sqrt( radius * radius - y * y );
  26628. // special case for the poles
  26629. let uOffset = 0;
  26630. if ( iy === 0 && thetaStart === 0 ) {
  26631. uOffset = 0.5 / widthSegments;
  26632. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26633. uOffset = -0.5 / widthSegments;
  26634. }
  26635. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26636. const u = ix / widthSegments;
  26637. const phi = phiStart + u * phiLength;
  26638. // vertex
  26639. vertex.x = - ringRadius * Math.cos( phi );
  26640. vertex.y = y;
  26641. vertex.z = ringRadius * Math.sin( phi );
  26642. vertices.push( vertex.x, vertex.y, vertex.z );
  26643. // normal
  26644. normal.copy( vertex ).normalize();
  26645. normals.push( normal.x, normal.y, normal.z );
  26646. // uv
  26647. uvs.push( u + uOffset, 1 - v );
  26648. verticesRow.push( index ++ );
  26649. }
  26650. grid.push( verticesRow );
  26651. }
  26652. // indices
  26653. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26654. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26655. const a = grid[ iy ][ ix + 1 ];
  26656. const b = grid[ iy ][ ix ];
  26657. const c = grid[ iy + 1 ][ ix ];
  26658. const d = grid[ iy + 1 ][ ix + 1 ];
  26659. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26660. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26661. }
  26662. }
  26663. // build geometry
  26664. this.setIndex( indices );
  26665. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26666. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26667. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26668. }
  26669. copy( source ) {
  26670. super.copy( source );
  26671. this.parameters = Object.assign( {}, source.parameters );
  26672. return this;
  26673. }
  26674. /**
  26675. * Factory method for creating an instance of this class from the given
  26676. * JSON object.
  26677. *
  26678. * @param {Object} data - A JSON object representing the serialized geometry.
  26679. * @return {SphereGeometry} A new instance.
  26680. */
  26681. static fromJSON( data ) {
  26682. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26683. }
  26684. }
  26685. /**
  26686. * A geometry class for representing an tetrahedron.
  26687. *
  26688. * ```js
  26689. * const geometry = new THREE.TetrahedronGeometry();
  26690. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26691. * const tetrahedron = new THREE.Mesh( geometry, material );
  26692. * scene.add( tetrahedron );
  26693. * ```
  26694. *
  26695. * @augments PolyhedronGeometry
  26696. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  26697. */
  26698. class TetrahedronGeometry extends PolyhedronGeometry {
  26699. /**
  26700. * Constructs a new tetrahedron geometry.
  26701. *
  26702. * @param {number} [radius=1] - Radius of the tetrahedron.
  26703. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26704. */
  26705. constructor( radius = 1, detail = 0 ) {
  26706. const vertices = [
  26707. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26708. ];
  26709. const indices = [
  26710. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26711. ];
  26712. super( vertices, indices, radius, detail );
  26713. this.type = 'TetrahedronGeometry';
  26714. /**
  26715. * Holds the constructor parameters that have been
  26716. * used to generate the geometry. Any modification
  26717. * after instantiation does not change the geometry.
  26718. *
  26719. * @type {Object}
  26720. */
  26721. this.parameters = {
  26722. radius: radius,
  26723. detail: detail
  26724. };
  26725. }
  26726. /**
  26727. * Factory method for creating an instance of this class from the given
  26728. * JSON object.
  26729. *
  26730. * @param {Object} data - A JSON object representing the serialized geometry.
  26731. * @return {TetrahedronGeometry} A new instance.
  26732. */
  26733. static fromJSON( data ) {
  26734. return new TetrahedronGeometry( data.radius, data.detail );
  26735. }
  26736. }
  26737. /**
  26738. * A geometry class for representing an torus.
  26739. *
  26740. * ```js
  26741. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26742. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26743. * const torus = new THREE.Mesh( geometry, material );
  26744. * scene.add( torus );
  26745. * ```
  26746. *
  26747. * @augments BufferGeometry
  26748. * @demo scenes/geometry-browser.html#TorusGeometry
  26749. */
  26750. class TorusGeometry extends BufferGeometry {
  26751. /**
  26752. * Constructs a new torus geometry.
  26753. *
  26754. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26755. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26756. * @param {number} [radialSegments=12] - The number of radial segments.
  26757. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26758. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26759. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  26760. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  26761. */
  26762. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26763. super();
  26764. this.type = 'TorusGeometry';
  26765. /**
  26766. * Holds the constructor parameters that have been
  26767. * used to generate the geometry. Any modification
  26768. * after instantiation does not change the geometry.
  26769. *
  26770. * @type {Object}
  26771. */
  26772. this.parameters = {
  26773. radius: radius,
  26774. tube: tube,
  26775. radialSegments: radialSegments,
  26776. tubularSegments: tubularSegments,
  26777. arc: arc,
  26778. thetaStart: thetaStart,
  26779. thetaLength: thetaLength,
  26780. };
  26781. radialSegments = Math.floor( radialSegments );
  26782. tubularSegments = Math.floor( tubularSegments );
  26783. // buffers
  26784. const indices = [];
  26785. const vertices = [];
  26786. const normals = [];
  26787. const uvs = [];
  26788. // helper variables
  26789. const center = new Vector3();
  26790. const vertex = new Vector3();
  26791. const normal = new Vector3();
  26792. // generate vertices, normals and uvs
  26793. for ( let j = 0; j <= radialSegments; j ++ ) {
  26794. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  26795. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26796. const u = i / tubularSegments * arc;
  26797. // vertex
  26798. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26799. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26800. vertex.z = tube * Math.sin( v );
  26801. vertices.push( vertex.x, vertex.y, vertex.z );
  26802. // normal
  26803. center.x = radius * Math.cos( u );
  26804. center.y = radius * Math.sin( u );
  26805. normal.subVectors( vertex, center ).normalize();
  26806. normals.push( normal.x, normal.y, normal.z );
  26807. // uv
  26808. uvs.push( i / tubularSegments );
  26809. uvs.push( j / radialSegments );
  26810. }
  26811. }
  26812. // generate indices
  26813. for ( let j = 1; j <= radialSegments; j ++ ) {
  26814. for ( let i = 1; i <= tubularSegments; i ++ ) {
  26815. // indices
  26816. const a = ( tubularSegments + 1 ) * j + i - 1;
  26817. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  26818. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  26819. const d = ( tubularSegments + 1 ) * j + i;
  26820. // faces
  26821. indices.push( a, b, d );
  26822. indices.push( b, c, d );
  26823. }
  26824. }
  26825. // build geometry
  26826. this.setIndex( indices );
  26827. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26828. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26829. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26830. }
  26831. copy( source ) {
  26832. super.copy( source );
  26833. this.parameters = Object.assign( {}, source.parameters );
  26834. return this;
  26835. }
  26836. /**
  26837. * Factory method for creating an instance of this class from the given
  26838. * JSON object.
  26839. *
  26840. * @param {Object} data - A JSON object representing the serialized geometry.
  26841. * @return {TorusGeometry} A new instance.
  26842. */
  26843. static fromJSON( data ) {
  26844. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  26845. }
  26846. }
  26847. /**
  26848. * Creates a torus knot, the particular shape of which is defined by a pair
  26849. * of coprime integers, p and q. If p and q are not coprime, the result will
  26850. * be a torus link.
  26851. *
  26852. * ```js
  26853. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  26854. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26855. * const torusKnot = new THREE.Mesh( geometry, material );
  26856. * scene.add( torusKnot );
  26857. * ```
  26858. *
  26859. * @augments BufferGeometry
  26860. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  26861. */
  26862. class TorusKnotGeometry extends BufferGeometry {
  26863. /**
  26864. * Constructs a new torus knot geometry.
  26865. *
  26866. * @param {number} [radius=1] - Radius of the torus knot.
  26867. * @param {number} [tube=0.4] - Radius of the tube.
  26868. * @param {number} [tubularSegments=64] - The number of tubular segments.
  26869. * @param {number} [radialSegments=8] - The number of radial segments.
  26870. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  26871. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  26872. */
  26873. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  26874. super();
  26875. this.type = 'TorusKnotGeometry';
  26876. /**
  26877. * Holds the constructor parameters that have been
  26878. * used to generate the geometry. Any modification
  26879. * after instantiation does not change the geometry.
  26880. *
  26881. * @type {Object}
  26882. */
  26883. this.parameters = {
  26884. radius: radius,
  26885. tube: tube,
  26886. tubularSegments: tubularSegments,
  26887. radialSegments: radialSegments,
  26888. p: p,
  26889. q: q
  26890. };
  26891. tubularSegments = Math.floor( tubularSegments );
  26892. radialSegments = Math.floor( radialSegments );
  26893. // buffers
  26894. const indices = [];
  26895. const vertices = [];
  26896. const normals = [];
  26897. const uvs = [];
  26898. // helper variables
  26899. const vertex = new Vector3();
  26900. const normal = new Vector3();
  26901. const P1 = new Vector3();
  26902. const P2 = new Vector3();
  26903. const B = new Vector3();
  26904. const T = new Vector3();
  26905. const N = new Vector3();
  26906. // generate vertices, normals and uvs
  26907. for ( let i = 0; i <= tubularSegments; ++ i ) {
  26908. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  26909. const u = i / tubularSegments * p * Math.PI * 2;
  26910. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  26911. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  26912. calculatePositionOnCurve( u, p, q, radius, P1 );
  26913. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  26914. // calculate orthonormal basis
  26915. T.subVectors( P2, P1 );
  26916. N.addVectors( P2, P1 );
  26917. B.crossVectors( T, N );
  26918. N.crossVectors( B, T );
  26919. // normalize B, N. T can be ignored, we don't use it
  26920. B.normalize();
  26921. N.normalize();
  26922. for ( let j = 0; j <= radialSegments; ++ j ) {
  26923. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  26924. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  26925. const v = j / radialSegments * Math.PI * 2;
  26926. const cx = - tube * Math.cos( v );
  26927. const cy = tube * Math.sin( v );
  26928. // now calculate the final vertex position.
  26929. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  26930. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  26931. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  26932. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  26933. vertices.push( vertex.x, vertex.y, vertex.z );
  26934. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  26935. normal.subVectors( vertex, P1 ).normalize();
  26936. normals.push( normal.x, normal.y, normal.z );
  26937. // uv
  26938. uvs.push( i / tubularSegments );
  26939. uvs.push( j / radialSegments );
  26940. }
  26941. }
  26942. // generate indices
  26943. for ( let j = 1; j <= tubularSegments; j ++ ) {
  26944. for ( let i = 1; i <= radialSegments; i ++ ) {
  26945. // indices
  26946. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  26947. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  26948. const c = ( radialSegments + 1 ) * j + i;
  26949. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  26950. // faces
  26951. indices.push( a, b, d );
  26952. indices.push( b, c, d );
  26953. }
  26954. }
  26955. // build geometry
  26956. this.setIndex( indices );
  26957. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26958. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26959. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26960. // this function calculates the current position on the torus curve
  26961. function calculatePositionOnCurve( u, p, q, radius, position ) {
  26962. const cu = Math.cos( u );
  26963. const su = Math.sin( u );
  26964. const quOverP = q / p * u;
  26965. const cs = Math.cos( quOverP );
  26966. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  26967. position.y = radius * ( 2 + cs ) * su * 0.5;
  26968. position.z = radius * Math.sin( quOverP ) * 0.5;
  26969. }
  26970. }
  26971. copy( source ) {
  26972. super.copy( source );
  26973. this.parameters = Object.assign( {}, source.parameters );
  26974. return this;
  26975. }
  26976. /**
  26977. * Factory method for creating an instance of this class from the given
  26978. * JSON object.
  26979. *
  26980. * @param {Object} data - A JSON object representing the serialized geometry.
  26981. * @return {TorusKnotGeometry} A new instance.
  26982. */
  26983. static fromJSON( data ) {
  26984. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  26985. }
  26986. }
  26987. /**
  26988. * Creates a tube that extrudes along a 3D curve.
  26989. *
  26990. * ```js
  26991. * class CustomSinCurve extends THREE.Curve {
  26992. *
  26993. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  26994. *
  26995. * const tx = t * 3 - 1.5;
  26996. * const ty = Math.sin( 2 * Math.PI * t );
  26997. * const tz = 0;
  26998. *
  26999. * return optionalTarget.set( tx, ty, tz );
  27000. * }
  27001. *
  27002. * }
  27003. *
  27004. * const path = new CustomSinCurve( 10 );
  27005. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27006. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27007. * const mesh = new THREE.Mesh( geometry, material );
  27008. * scene.add( mesh );
  27009. * ```
  27010. *
  27011. * @augments BufferGeometry
  27012. * @demo scenes/geometry-browser.html#TubeGeometry
  27013. */
  27014. class TubeGeometry extends BufferGeometry {
  27015. /**
  27016. * Constructs a new tube geometry.
  27017. *
  27018. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27019. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27020. * @param {number} [radius=1] -The radius of the tube.
  27021. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27022. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27023. */
  27024. 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 ) {
  27025. super();
  27026. this.type = 'TubeGeometry';
  27027. /**
  27028. * Holds the constructor parameters that have been
  27029. * used to generate the geometry. Any modification
  27030. * after instantiation does not change the geometry.
  27031. *
  27032. * @type {Object}
  27033. */
  27034. this.parameters = {
  27035. path: path,
  27036. tubularSegments: tubularSegments,
  27037. radius: radius,
  27038. radialSegments: radialSegments,
  27039. closed: closed
  27040. };
  27041. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27042. // expose internals
  27043. this.tangents = frames.tangents;
  27044. this.normals = frames.normals;
  27045. this.binormals = frames.binormals;
  27046. // helper variables
  27047. const vertex = new Vector3();
  27048. const normal = new Vector3();
  27049. const uv = new Vector2();
  27050. let P = new Vector3();
  27051. // buffer
  27052. const vertices = [];
  27053. const normals = [];
  27054. const uvs = [];
  27055. const indices = [];
  27056. // create buffer data
  27057. generateBufferData();
  27058. // build geometry
  27059. this.setIndex( indices );
  27060. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27061. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27062. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27063. // functions
  27064. function generateBufferData() {
  27065. for ( let i = 0; i < tubularSegments; i ++ ) {
  27066. generateSegment( i );
  27067. }
  27068. // if the geometry is not closed, generate the last row of vertices and normals
  27069. // at the regular position on the given path
  27070. //
  27071. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27072. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27073. // uvs are generated in a separate function.
  27074. // this makes it easy compute correct values for closed geometries
  27075. generateUVs();
  27076. // finally create faces
  27077. generateIndices();
  27078. }
  27079. function generateSegment( i ) {
  27080. // we use getPointAt to sample evenly distributed points from the given path
  27081. P = path.getPointAt( i / tubularSegments, P );
  27082. // retrieve corresponding normal and binormal
  27083. const N = frames.normals[ i ];
  27084. const B = frames.binormals[ i ];
  27085. // generate normals and vertices for the current segment
  27086. for ( let j = 0; j <= radialSegments; j ++ ) {
  27087. const v = j / radialSegments * Math.PI * 2;
  27088. const sin = Math.sin( v );
  27089. const cos = - Math.cos( v );
  27090. // normal
  27091. normal.x = ( cos * N.x + sin * B.x );
  27092. normal.y = ( cos * N.y + sin * B.y );
  27093. normal.z = ( cos * N.z + sin * B.z );
  27094. normal.normalize();
  27095. normals.push( normal.x, normal.y, normal.z );
  27096. // vertex
  27097. vertex.x = P.x + radius * normal.x;
  27098. vertex.y = P.y + radius * normal.y;
  27099. vertex.z = P.z + radius * normal.z;
  27100. vertices.push( vertex.x, vertex.y, vertex.z );
  27101. }
  27102. }
  27103. function generateIndices() {
  27104. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27105. for ( let i = 1; i <= radialSegments; i ++ ) {
  27106. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27107. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27108. const c = ( radialSegments + 1 ) * j + i;
  27109. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27110. // faces
  27111. indices.push( a, b, d );
  27112. indices.push( b, c, d );
  27113. }
  27114. }
  27115. }
  27116. function generateUVs() {
  27117. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27118. for ( let j = 0; j <= radialSegments; j ++ ) {
  27119. uv.x = i / tubularSegments;
  27120. uv.y = j / radialSegments;
  27121. uvs.push( uv.x, uv.y );
  27122. }
  27123. }
  27124. }
  27125. }
  27126. copy( source ) {
  27127. super.copy( source );
  27128. this.parameters = Object.assign( {}, source.parameters );
  27129. return this;
  27130. }
  27131. toJSON() {
  27132. const data = super.toJSON();
  27133. data.path = this.parameters.path.toJSON();
  27134. return data;
  27135. }
  27136. /**
  27137. * Factory method for creating an instance of this class from the given
  27138. * JSON object.
  27139. *
  27140. * @param {Object} data - A JSON object representing the serialized geometry.
  27141. * @return {TubeGeometry} A new instance.
  27142. */
  27143. static fromJSON( data ) {
  27144. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27145. // User defined curves or instances of CurvePath will not be deserialized.
  27146. return new TubeGeometry(
  27147. new Curves[ data.path.type ]().fromJSON( data.path ),
  27148. data.tubularSegments,
  27149. data.radius,
  27150. data.radialSegments,
  27151. data.closed
  27152. );
  27153. }
  27154. }
  27155. /**
  27156. * Can be used as a helper object to visualize a geometry as a wireframe.
  27157. *
  27158. * ```js
  27159. * const geometry = new THREE.SphereGeometry();
  27160. *
  27161. * const wireframe = new THREE.WireframeGeometry( geometry );
  27162. *
  27163. * const line = new THREE.LineSegments( wireframe );
  27164. * line.material.depthWrite = false;
  27165. * line.material.opacity = 0.25;
  27166. * line.material.transparent = true;
  27167. *
  27168. * scene.add( line );
  27169. * ```
  27170. *
  27171. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27172. *
  27173. * @augments BufferGeometry
  27174. */
  27175. class WireframeGeometry extends BufferGeometry {
  27176. /**
  27177. * Constructs a new wireframe geometry.
  27178. *
  27179. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27180. */
  27181. constructor( geometry = null ) {
  27182. super();
  27183. this.type = 'WireframeGeometry';
  27184. /**
  27185. * Holds the constructor parameters that have been
  27186. * used to generate the geometry. Any modification
  27187. * after instantiation does not change the geometry.
  27188. *
  27189. * @type {Object}
  27190. */
  27191. this.parameters = {
  27192. geometry: geometry
  27193. };
  27194. if ( geometry !== null ) {
  27195. // buffer
  27196. const vertices = [];
  27197. const edges = new Set();
  27198. // helper variables
  27199. const start = new Vector3();
  27200. const end = new Vector3();
  27201. if ( geometry.index !== null ) {
  27202. // indexed BufferGeometry
  27203. const position = geometry.attributes.position;
  27204. const indices = geometry.index;
  27205. let groups = geometry.groups;
  27206. if ( groups.length === 0 ) {
  27207. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27208. }
  27209. // create a data structure that contains all edges without duplicates
  27210. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27211. const group = groups[ o ];
  27212. const groupStart = group.start;
  27213. const groupCount = group.count;
  27214. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27215. for ( let j = 0; j < 3; j ++ ) {
  27216. const index1 = indices.getX( i + j );
  27217. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27218. start.fromBufferAttribute( position, index1 );
  27219. end.fromBufferAttribute( position, index2 );
  27220. if ( isUniqueEdge( start, end, edges ) === true ) {
  27221. vertices.push( start.x, start.y, start.z );
  27222. vertices.push( end.x, end.y, end.z );
  27223. }
  27224. }
  27225. }
  27226. }
  27227. } else {
  27228. // non-indexed BufferGeometry
  27229. const position = geometry.attributes.position;
  27230. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27231. for ( let j = 0; j < 3; j ++ ) {
  27232. // three edges per triangle, an edge is represented as (index1, index2)
  27233. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27234. const index1 = 3 * i + j;
  27235. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27236. start.fromBufferAttribute( position, index1 );
  27237. end.fromBufferAttribute( position, index2 );
  27238. if ( isUniqueEdge( start, end, edges ) === true ) {
  27239. vertices.push( start.x, start.y, start.z );
  27240. vertices.push( end.x, end.y, end.z );
  27241. }
  27242. }
  27243. }
  27244. }
  27245. // build geometry
  27246. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27247. }
  27248. }
  27249. copy( source ) {
  27250. super.copy( source );
  27251. this.parameters = Object.assign( {}, source.parameters );
  27252. return this;
  27253. }
  27254. }
  27255. function isUniqueEdge( start, end, edges ) {
  27256. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27257. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27258. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27259. return false;
  27260. } else {
  27261. edges.add( hash1 );
  27262. edges.add( hash2 );
  27263. return true;
  27264. }
  27265. }
  27266. var Geometries = /*#__PURE__*/Object.freeze({
  27267. __proto__: null,
  27268. BoxGeometry: BoxGeometry,
  27269. CapsuleGeometry: CapsuleGeometry,
  27270. CircleGeometry: CircleGeometry,
  27271. ConeGeometry: ConeGeometry,
  27272. CylinderGeometry: CylinderGeometry,
  27273. DodecahedronGeometry: DodecahedronGeometry,
  27274. EdgesGeometry: EdgesGeometry,
  27275. ExtrudeGeometry: ExtrudeGeometry,
  27276. IcosahedronGeometry: IcosahedronGeometry,
  27277. LatheGeometry: LatheGeometry,
  27278. OctahedronGeometry: OctahedronGeometry,
  27279. PlaneGeometry: PlaneGeometry,
  27280. PolyhedronGeometry: PolyhedronGeometry,
  27281. RingGeometry: RingGeometry,
  27282. ShapeGeometry: ShapeGeometry,
  27283. SphereGeometry: SphereGeometry,
  27284. TetrahedronGeometry: TetrahedronGeometry,
  27285. TorusGeometry: TorusGeometry,
  27286. TorusKnotGeometry: TorusKnotGeometry,
  27287. TubeGeometry: TubeGeometry,
  27288. WireframeGeometry: WireframeGeometry
  27289. });
  27290. /**
  27291. * This material can receive shadows, but otherwise is completely transparent.
  27292. *
  27293. * ```js
  27294. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27295. * geometry.rotateX( - Math.PI / 2 );
  27296. *
  27297. * const material = new THREE.ShadowMaterial();
  27298. * material.opacity = 0.2;
  27299. *
  27300. * const plane = new THREE.Mesh( geometry, material );
  27301. * plane.position.y = -200;
  27302. * plane.receiveShadow = true;
  27303. * scene.add( plane );
  27304. * ```
  27305. *
  27306. * @augments Material
  27307. */
  27308. class ShadowMaterial extends Material {
  27309. /**
  27310. * Constructs a new shadow material.
  27311. *
  27312. * @param {Object} [parameters] - An object with one or more properties
  27313. * defining the material's appearance. Any property of the material
  27314. * (including any property from inherited materials) can be passed
  27315. * in here. Color values can be passed any type of value accepted
  27316. * by {@link Color#set}.
  27317. */
  27318. constructor( parameters ) {
  27319. super();
  27320. /**
  27321. * This flag can be used for type testing.
  27322. *
  27323. * @type {boolean}
  27324. * @readonly
  27325. * @default true
  27326. */
  27327. this.isShadowMaterial = true;
  27328. this.type = 'ShadowMaterial';
  27329. /**
  27330. * Color of the material.
  27331. *
  27332. * @type {Color}
  27333. * @default (0,0,0)
  27334. */
  27335. this.color = new Color( 0x000000 );
  27336. /**
  27337. * Overwritten since shadow materials are transparent
  27338. * by default.
  27339. *
  27340. * @type {boolean}
  27341. * @default true
  27342. */
  27343. this.transparent = true;
  27344. /**
  27345. * Whether the material is affected by fog or not.
  27346. *
  27347. * @type {boolean}
  27348. * @default true
  27349. */
  27350. this.fog = true;
  27351. this.setValues( parameters );
  27352. }
  27353. copy( source ) {
  27354. super.copy( source );
  27355. this.color.copy( source.color );
  27356. this.fog = source.fog;
  27357. return this;
  27358. }
  27359. }
  27360. /**
  27361. * Provides utility functions for managing uniforms.
  27362. *
  27363. * @module UniformsUtils
  27364. */
  27365. /**
  27366. * Clones the given uniform definitions by performing a deep-copy. That means
  27367. * if the value of a uniform refers to an object like a Vector3 or Texture,
  27368. * the cloned uniform will refer to a new object reference.
  27369. *
  27370. * @param {Object} src - An object representing uniform definitions.
  27371. * @return {Object} The cloned uniforms.
  27372. */
  27373. function cloneUniforms( src ) {
  27374. const dst = {};
  27375. for ( const u in src ) {
  27376. dst[ u ] = {};
  27377. for ( const p in src[ u ] ) {
  27378. const property = src[ u ][ p ];
  27379. if ( isThreeObject( property ) ) {
  27380. if ( property.isRenderTargetTexture ) {
  27381. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  27382. dst[ u ][ p ] = null;
  27383. } else {
  27384. dst[ u ][ p ] = property.clone();
  27385. }
  27386. } else if ( Array.isArray( property ) ) {
  27387. if ( isThreeObject( property[ 0 ] ) ) {
  27388. const clonedProperty = [];
  27389. for ( let i = 0, l = property.length; i < l; i ++ ) {
  27390. clonedProperty[ i ] = property[ i ].clone();
  27391. }
  27392. dst[ u ][ p ] = clonedProperty;
  27393. } else {
  27394. dst[ u ][ p ] = property.slice();
  27395. }
  27396. } else {
  27397. dst[ u ][ p ] = property;
  27398. }
  27399. }
  27400. }
  27401. return dst;
  27402. }
  27403. /**
  27404. * Merges the given uniform definitions into a single object. Since the
  27405. * method internally uses cloneUniforms(), it performs a deep-copy when
  27406. * producing the merged uniform definitions.
  27407. *
  27408. * @param {Array} uniforms - An array of objects containing uniform definitions.
  27409. * @return {Object} The merged uniforms.
  27410. */
  27411. function mergeUniforms( uniforms ) {
  27412. const merged = {};
  27413. for ( let u = 0; u < uniforms.length; u ++ ) {
  27414. const tmp = cloneUniforms( uniforms[ u ] );
  27415. for ( const p in tmp ) {
  27416. merged[ p ] = tmp[ p ];
  27417. }
  27418. }
  27419. return merged;
  27420. }
  27421. function isThreeObject( property ) {
  27422. return ( property && ( property.isColor ||
  27423. property.isMatrix3 || property.isMatrix4 ||
  27424. property.isVector2 || property.isVector3 || property.isVector4 ||
  27425. property.isTexture || property.isQuaternion ) );
  27426. }
  27427. function cloneUniformsGroups( src ) {
  27428. const dst = [];
  27429. for ( let u = 0; u < src.length; u ++ ) {
  27430. dst.push( src[ u ].clone() );
  27431. }
  27432. return dst;
  27433. }
  27434. function getUnlitUniformColorSpace( renderer ) {
  27435. const currentRenderTarget = renderer.getRenderTarget();
  27436. if ( currentRenderTarget === null ) {
  27437. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  27438. return renderer.outputColorSpace;
  27439. }
  27440. // https://github.com/mrdoob/three.js/issues/27868
  27441. if ( currentRenderTarget.isXRRenderTarget === true ) {
  27442. return currentRenderTarget.texture.colorSpace;
  27443. }
  27444. return ColorManagement.workingColorSpace;
  27445. }
  27446. // Legacy
  27447. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  27448. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  27449. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  27450. /**
  27451. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  27452. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  27453. * effect not included with any of the built-in materials.
  27454. *
  27455. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  27456. *
  27457. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  27458. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  27459. * you don't want that, use {@link RawShaderMaterial} instead.
  27460. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  27461. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  27462. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  27463. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  27464. * - The loop variable has to be *i*.
  27465. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  27466. * value of *i* for the given iteration and can be used in preprocessor
  27467. * statements.
  27468. *
  27469. * ```js
  27470. * const material = new THREE.ShaderMaterial( {
  27471. * uniforms: {
  27472. * time: { value: 1.0 },
  27473. * resolution: { value: new THREE.Vector2() }
  27474. * },
  27475. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  27476. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  27477. * } );
  27478. * ```
  27479. *
  27480. * @augments Material
  27481. */
  27482. class ShaderMaterial extends Material {
  27483. /**
  27484. * Constructs a new shader material.
  27485. *
  27486. * @param {Object} [parameters] - An object with one or more properties
  27487. * defining the material's appearance. Any property of the material
  27488. * (including any property from inherited materials) can be passed
  27489. * in here. Color values can be passed any type of value accepted
  27490. * by {@link Color#set}.
  27491. */
  27492. constructor( parameters ) {
  27493. super();
  27494. /**
  27495. * This flag can be used for type testing.
  27496. *
  27497. * @type {boolean}
  27498. * @readonly
  27499. * @default true
  27500. */
  27501. this.isShaderMaterial = true;
  27502. this.type = 'ShaderMaterial';
  27503. /**
  27504. * Defines custom constants using `#define` directives within the GLSL code
  27505. * for both the vertex shader and the fragment shader; each key/value pair
  27506. * yields another directive.
  27507. * ```js
  27508. * defines: {
  27509. * FOO: 15,
  27510. * BAR: true
  27511. * }
  27512. * ```
  27513. * Yields the lines:
  27514. * ```
  27515. * #define FOO 15
  27516. * #define BAR true
  27517. * ```
  27518. *
  27519. * @type {Object}
  27520. */
  27521. this.defines = {};
  27522. /**
  27523. * An object of the form:
  27524. * ```js
  27525. * {
  27526. * "uniform1": { value: 1.0 },
  27527. * "uniform2": { value: 2 }
  27528. * }
  27529. * ```
  27530. * specifying the uniforms to be passed to the shader code; keys are uniform
  27531. * names, values are definitions of the form
  27532. * ```
  27533. * {
  27534. * value: 1.0
  27535. * }
  27536. * ```
  27537. * where `value` is the value of the uniform. Names must match the name of
  27538. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  27539. * on every frame, so updating the value of the uniform will immediately
  27540. * update the value available to the GLSL code.
  27541. *
  27542. * @type {Object}
  27543. */
  27544. this.uniforms = {};
  27545. /**
  27546. * An array holding uniforms groups for configuring UBOs.
  27547. *
  27548. * @type {Array<UniformsGroup>}
  27549. */
  27550. this.uniformsGroups = [];
  27551. /**
  27552. * Vertex shader GLSL code. This is the actual code for the shader.
  27553. *
  27554. * @type {string}
  27555. */
  27556. this.vertexShader = default_vertex;
  27557. /**
  27558. * Fragment shader GLSL code. This is the actual code for the shader.
  27559. *
  27560. * @type {string}
  27561. */
  27562. this.fragmentShader = default_fragment;
  27563. /**
  27564. * Controls line thickness or lines.
  27565. *
  27566. * WebGL and WebGPU ignore this setting and always render line primitives with a
  27567. * width of one pixel.
  27568. *
  27569. * @type {number}
  27570. * @default 1
  27571. */
  27572. this.linewidth = 1;
  27573. /**
  27574. * Renders the geometry as a wireframe.
  27575. *
  27576. * @type {boolean}
  27577. * @default false
  27578. */
  27579. this.wireframe = false;
  27580. /**
  27581. * Controls the thickness of the wireframe.
  27582. *
  27583. * WebGL and WebGPU ignore this property and always render
  27584. * 1 pixel wide lines.
  27585. *
  27586. * @type {number}
  27587. * @default 1
  27588. */
  27589. this.wireframeLinewidth = 1;
  27590. /**
  27591. * Defines whether the material color is affected by global fog settings; `true`
  27592. * to pass fog uniforms to the shader.
  27593. *
  27594. * Setting this property to `true` requires the definition of fog uniforms. It is
  27595. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  27596. * with predefined fog uniforms.
  27597. *
  27598. * ```js
  27599. * const material = new ShaderMaterial( {
  27600. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  27601. * vertexShader: vertexShader,
  27602. * fragmentShader: fragmentShader,
  27603. * fog: true
  27604. * } );
  27605. * ```
  27606. *
  27607. * @type {boolean}
  27608. * @default false
  27609. */
  27610. this.fog = false;
  27611. /**
  27612. * Defines whether this material uses lighting; `true` to pass uniform data
  27613. * related to lighting to this shader.
  27614. *
  27615. * @type {boolean}
  27616. * @default false
  27617. */
  27618. this.lights = false;
  27619. /**
  27620. * Defines whether this material supports clipping; `true` to let the renderer
  27621. * pass the clippingPlanes uniform.
  27622. *
  27623. * @type {boolean}
  27624. * @default false
  27625. */
  27626. this.clipping = false;
  27627. /**
  27628. * Overwritten and set to `true` by default.
  27629. *
  27630. * @type {boolean}
  27631. * @default true
  27632. */
  27633. this.forceSinglePass = true;
  27634. /**
  27635. * This object allows to enable certain WebGL 2 extensions.
  27636. *
  27637. * - clipCullDistance: set to `true` to use vertex shader clipping
  27638. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  27639. *
  27640. * @type {{clipCullDistance:false,multiDraw:false}}
  27641. */
  27642. this.extensions = {
  27643. clipCullDistance: false, // set to use vertex shader clipping
  27644. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  27645. };
  27646. /**
  27647. * When the rendered geometry doesn't include these attributes but the
  27648. * material does, these default values will be passed to the shaders. This
  27649. * avoids errors when buffer data is missing.
  27650. *
  27651. * - color: [ 1, 1, 1 ]
  27652. * - uv: [ 0, 0 ]
  27653. * - uv1: [ 0, 0 ]
  27654. *
  27655. * @type {Object}
  27656. */
  27657. this.defaultAttributeValues = {
  27658. 'color': [ 1, 1, 1 ],
  27659. 'uv': [ 0, 0 ],
  27660. 'uv1': [ 0, 0 ]
  27661. };
  27662. /**
  27663. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  27664. * to bind a generic vertex index to an attribute variable.
  27665. *
  27666. * @type {string|undefined}
  27667. * @default undefined
  27668. */
  27669. this.index0AttributeName = undefined;
  27670. /**
  27671. * Can be used to force a uniform update while changing uniforms in
  27672. * {@link Object3D#onBeforeRender}.
  27673. *
  27674. * @type {boolean}
  27675. * @default false
  27676. */
  27677. this.uniformsNeedUpdate = false;
  27678. /**
  27679. * Defines the GLSL version of custom shader code.
  27680. *
  27681. * @type {?(GLSL1|GLSL3)}
  27682. * @default null
  27683. */
  27684. this.glslVersion = null;
  27685. if ( parameters !== undefined ) {
  27686. this.setValues( parameters );
  27687. }
  27688. }
  27689. copy( source ) {
  27690. super.copy( source );
  27691. this.fragmentShader = source.fragmentShader;
  27692. this.vertexShader = source.vertexShader;
  27693. this.uniforms = cloneUniforms( source.uniforms );
  27694. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  27695. this.defines = Object.assign( {}, source.defines );
  27696. this.wireframe = source.wireframe;
  27697. this.wireframeLinewidth = source.wireframeLinewidth;
  27698. this.fog = source.fog;
  27699. this.lights = source.lights;
  27700. this.clipping = source.clipping;
  27701. this.extensions = Object.assign( {}, source.extensions );
  27702. this.glslVersion = source.glslVersion;
  27703. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  27704. this.index0AttributeName = source.index0AttributeName;
  27705. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  27706. return this;
  27707. }
  27708. toJSON( meta ) {
  27709. const data = super.toJSON( meta );
  27710. data.glslVersion = this.glslVersion;
  27711. data.uniforms = {};
  27712. for ( const name in this.uniforms ) {
  27713. const uniform = this.uniforms[ name ];
  27714. const value = uniform.value;
  27715. if ( value && value.isTexture ) {
  27716. data.uniforms[ name ] = {
  27717. type: 't',
  27718. value: value.toJSON( meta ).uuid
  27719. };
  27720. } else if ( value && value.isColor ) {
  27721. data.uniforms[ name ] = {
  27722. type: 'c',
  27723. value: value.getHex()
  27724. };
  27725. } else if ( value && value.isVector2 ) {
  27726. data.uniforms[ name ] = {
  27727. type: 'v2',
  27728. value: value.toArray()
  27729. };
  27730. } else if ( value && value.isVector3 ) {
  27731. data.uniforms[ name ] = {
  27732. type: 'v3',
  27733. value: value.toArray()
  27734. };
  27735. } else if ( value && value.isVector4 ) {
  27736. data.uniforms[ name ] = {
  27737. type: 'v4',
  27738. value: value.toArray()
  27739. };
  27740. } else if ( value && value.isMatrix3 ) {
  27741. data.uniforms[ name ] = {
  27742. type: 'm3',
  27743. value: value.toArray()
  27744. };
  27745. } else if ( value && value.isMatrix4 ) {
  27746. data.uniforms[ name ] = {
  27747. type: 'm4',
  27748. value: value.toArray()
  27749. };
  27750. } else {
  27751. data.uniforms[ name ] = {
  27752. value: value
  27753. };
  27754. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  27755. }
  27756. }
  27757. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  27758. data.vertexShader = this.vertexShader;
  27759. data.fragmentShader = this.fragmentShader;
  27760. data.lights = this.lights;
  27761. data.clipping = this.clipping;
  27762. const extensions = {};
  27763. for ( const key in this.extensions ) {
  27764. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  27765. }
  27766. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  27767. return data;
  27768. }
  27769. /**
  27770. * Deserializes the material from the given JSON.
  27771. *
  27772. * @param {Object} json - The JSON holding the serialized material.
  27773. * @param {Object<string,Texture>} textures - A dictionary holding textures referenced by the material.
  27774. * @return {ShaderMaterial} A reference to this material.
  27775. */
  27776. fromJSON( json, textures ) {
  27777. super.fromJSON( json, textures );
  27778. if ( json.uniforms !== undefined ) {
  27779. for ( const name in json.uniforms ) {
  27780. const uniform = json.uniforms[ name ];
  27781. this.uniforms[ name ] = {};
  27782. switch ( uniform.type ) {
  27783. case 't':
  27784. this.uniforms[ name ].value = textures[ uniform.value ] || null;
  27785. break;
  27786. case 'c':
  27787. this.uniforms[ name ].value = new Color().setHex( uniform.value );
  27788. break;
  27789. case 'v2':
  27790. this.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27791. break;
  27792. case 'v3':
  27793. this.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27794. break;
  27795. case 'v4':
  27796. this.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27797. break;
  27798. case 'm3':
  27799. this.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27800. break;
  27801. case 'm4':
  27802. this.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27803. break;
  27804. default:
  27805. this.uniforms[ name ].value = uniform.value;
  27806. }
  27807. }
  27808. }
  27809. if ( json.defines !== undefined ) this.defines = json.defines;
  27810. if ( json.vertexShader !== undefined ) this.vertexShader = json.vertexShader;
  27811. if ( json.fragmentShader !== undefined ) this.fragmentShader = json.fragmentShader;
  27812. if ( json.glslVersion !== undefined ) this.glslVersion = json.glslVersion;
  27813. if ( json.extensions !== undefined ) {
  27814. for ( const key in json.extensions ) {
  27815. this.extensions[ key ] = json.extensions[ key ];
  27816. }
  27817. }
  27818. if ( json.lights !== undefined ) this.lights = json.lights;
  27819. if ( json.clipping !== undefined ) this.clipping = json.clipping;
  27820. return this;
  27821. }
  27822. }
  27823. /**
  27824. * This class works just like {@link ShaderMaterial}, except that definitions
  27825. * of built-in uniforms and attributes are not automatically prepended to the
  27826. * GLSL shader code.
  27827. *
  27828. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27829. *
  27830. * @augments ShaderMaterial
  27831. */
  27832. class RawShaderMaterial extends ShaderMaterial {
  27833. /**
  27834. * Constructs a new raw shader material.
  27835. *
  27836. * @param {Object} [parameters] - An object with one or more properties
  27837. * defining the material's appearance. Any property of the material
  27838. * (including any property from inherited materials) can be passed
  27839. * in here. Color values can be passed any type of value accepted
  27840. * by {@link Color#set}.
  27841. */
  27842. constructor( parameters ) {
  27843. super( parameters );
  27844. /**
  27845. * This flag can be used for type testing.
  27846. *
  27847. * @type {boolean}
  27848. * @readonly
  27849. * @default true
  27850. */
  27851. this.isRawShaderMaterial = true;
  27852. this.type = 'RawShaderMaterial';
  27853. }
  27854. }
  27855. /**
  27856. * A standard physically based material, using Metallic-Roughness workflow.
  27857. *
  27858. * Physically based rendering (PBR) has recently become the standard in many
  27859. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27860. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27861. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27862. *
  27863. * This approach differs from older approaches in that instead of using
  27864. * approximations for the way in which light interacts with a surface, a
  27865. * physically correct model is used. The idea is that, instead of tweaking
  27866. * materials to look good under specific lighting, a material can be created
  27867. * that will react 'correctly' under all lighting scenarios.
  27868. *
  27869. * In practice this gives a more accurate and realistic looking result than
  27870. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27871. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27872. * shading.
  27873. *
  27874. * Note that for best results you should always specify an environment map when using this material.
  27875. *
  27876. * For a non-technical introduction to the concept of PBR and how to set up a
  27877. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27878. *
  27879. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27880. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27881. *
  27882. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27883. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27884. * (pdf), by Brent Burley.
  27885. *
  27886. * @augments Material
  27887. * @demo scenes/material-browser.html#MeshStandardMaterial
  27888. */
  27889. class MeshStandardMaterial extends Material {
  27890. /**
  27891. * Constructs a new mesh standard material.
  27892. *
  27893. * @param {Object} [parameters] - An object with one or more properties
  27894. * defining the material's appearance. Any property of the material
  27895. * (including any property from inherited materials) can be passed
  27896. * in here. Color values can be passed any type of value accepted
  27897. * by {@link Color#set}.
  27898. */
  27899. constructor( parameters ) {
  27900. super();
  27901. /**
  27902. * This flag can be used for type testing.
  27903. *
  27904. * @type {boolean}
  27905. * @readonly
  27906. * @default true
  27907. */
  27908. this.isMeshStandardMaterial = true;
  27909. this.type = 'MeshStandardMaterial';
  27910. this.defines = { 'STANDARD': '' };
  27911. /**
  27912. * Color of the material.
  27913. *
  27914. * @type {Color}
  27915. * @default (1,1,1)
  27916. */
  27917. this.color = new Color( 0xffffff ); // diffuse
  27918. /**
  27919. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27920. * means fully diffuse. If `roughnessMap` is also provided,
  27921. * both values are multiplied.
  27922. *
  27923. * @type {number}
  27924. * @default 1
  27925. */
  27926. this.roughness = 1.0;
  27927. /**
  27928. * How much the material is like a metal. Non-metallic materials such as wood
  27929. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27930. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27931. * If `metalnessMap` is also provided, both values are multiplied.
  27932. *
  27933. * @type {number}
  27934. * @default 0
  27935. */
  27936. this.metalness = 0.0;
  27937. /**
  27938. * The color map. May optionally include an alpha channel, typically combined
  27939. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27940. * color is modulated by the diffuse `color`.
  27941. *
  27942. * `map` represents color data, and the texture must be assigned a
  27943. * {@link Texture#colorSpace}. Most `map` textures set
  27944. * `texture.colorSpace = SRGBColorSpace`.
  27945. *
  27946. * @type {?Texture}
  27947. * @default null
  27948. */
  27949. this.map = null;
  27950. /**
  27951. * The light map. Requires a second set of UVs.
  27952. *
  27953. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  27954. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  27955. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  27956. * such as `.exr` or `.hdr`.
  27957. *
  27958. * @type {?Texture}
  27959. * @default null
  27960. */
  27961. this.lightMap = null;
  27962. /**
  27963. * Intensity of the baked light.
  27964. *
  27965. * @type {number}
  27966. * @default 1
  27967. */
  27968. this.lightMapIntensity = 1.0;
  27969. /**
  27970. * The red channel of this texture is used as the ambient occlusion map.
  27971. * Requires a second set of UVs.
  27972. *
  27973. * `aoMap` represents non-color data. Any texture assigned must have
  27974. * `texture.colorSpace = NoColorSpace` (default).
  27975. *
  27976. * @type {?Texture}
  27977. * @default null
  27978. */
  27979. this.aoMap = null;
  27980. /**
  27981. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27982. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27983. * red channel is also `1`, ambient light is fully occluded on a surface.
  27984. *
  27985. * @type {number}
  27986. * @default 1
  27987. */
  27988. this.aoMapIntensity = 1.0;
  27989. /**
  27990. * Emissive (light) color of the material, essentially a solid color
  27991. * unaffected by other lighting.
  27992. *
  27993. * @type {Color}
  27994. * @default (0,0,0)
  27995. */
  27996. this.emissive = new Color( 0x000000 );
  27997. /**
  27998. * Intensity of the emissive light. Modulates the emissive color.
  27999. *
  28000. * @type {number}
  28001. * @default 1
  28002. */
  28003. this.emissiveIntensity = 1.0;
  28004. /**
  28005. * Set emissive (glow) map. The emissive map color is modulated by the
  28006. * emissive color and the emissive intensity. If you have an emissive map,
  28007. * be sure to set the emissive color to something other than black.
  28008. *
  28009. * `emissiveMap` represents color data, and the texture must be assigned a
  28010. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  28011. * `texture.colorSpace = SRGBColorSpace`.
  28012. *
  28013. * @type {?Texture}
  28014. * @default null
  28015. */
  28016. this.emissiveMap = null;
  28017. /**
  28018. * The texture to create a bump map. The black and white values map to the
  28019. * perceived depth in relation to the lights. Bump doesn't actually affect
  28020. * the geometry of the object, only the lighting. If a normal map is defined
  28021. * this will be ignored.
  28022. *
  28023. * `bumpMap` represents non-color data. Any texture assigned must have
  28024. * `texture.colorSpace = NoColorSpace` (default).
  28025. *
  28026. * @type {?Texture}
  28027. * @default null
  28028. */
  28029. this.bumpMap = null;
  28030. /**
  28031. * How much the bump map affects the material. Typical range is `[0,1]`.
  28032. *
  28033. * @type {number}
  28034. * @default 1
  28035. */
  28036. this.bumpScale = 1;
  28037. /**
  28038. * The texture to create a normal map. The RGB values affect the surface
  28039. * normal for each pixel fragment and change the way the color is lit. Normal
  28040. * maps do not change the actual shape of the surface, only the lighting. In
  28041. * case the material has a normal map authored using the left handed
  28042. * convention, the `y` component of `normalScale` should be negated to compensate
  28043. * for the different handedness.
  28044. *
  28045. * `normalMap` represents non-color data. Any texture assigned must have
  28046. * `texture.colorSpace = NoColorSpace` (default).
  28047. *
  28048. * @type {?Texture}
  28049. * @default null
  28050. */
  28051. this.normalMap = null;
  28052. /**
  28053. * The type of normal map.
  28054. *
  28055. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28056. * @default TangentSpaceNormalMap
  28057. */
  28058. this.normalMapType = TangentSpaceNormalMap;
  28059. /**
  28060. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28061. *
  28062. * @type {Vector2}
  28063. * @default (1,1)
  28064. */
  28065. this.normalScale = new Vector2( 1, 1 );
  28066. /**
  28067. * The displacement map affects the position of the mesh's vertices. Unlike
  28068. * other maps which only affect the light and shade of the material the
  28069. * displaced vertices can cast shadows, block other objects, and otherwise
  28070. * act as real geometry. The displacement texture is an image where the value
  28071. * of each pixel (white being the highest) is mapped against, and
  28072. * repositions, the vertices of the mesh. For best results, pair a
  28073. * displacement map with a matching normal map, since the renderer can
  28074. * not recompute surface normals from the displaced vertices.
  28075. *
  28076. * `displacementMap` represents non-color data. Any texture assigned must have
  28077. * `texture.colorSpace = NoColorSpace` (default).
  28078. *
  28079. * @type {?Texture}
  28080. * @default null
  28081. */
  28082. this.displacementMap = null;
  28083. /**
  28084. * How much the displacement map affects the mesh (where black is no
  28085. * displacement, and white is maximum displacement). Without a displacement
  28086. * map set, this value is not applied.
  28087. *
  28088. * @type {number}
  28089. * @default 0
  28090. */
  28091. this.displacementScale = 1;
  28092. /**
  28093. * The offset of the displacement map's values on the mesh's vertices.
  28094. * The bias is added to the scaled sample of the displacement map.
  28095. * Without a displacement map set, this value is not applied.
  28096. *
  28097. * @type {number}
  28098. * @default 0
  28099. */
  28100. this.displacementBias = 0;
  28101. /**
  28102. * The green channel of this texture is used to alter the roughness of the
  28103. * material.
  28104. *
  28105. * `roughnessMap` represents non-color data. Any texture assigned must have
  28106. * `texture.colorSpace = NoColorSpace` (default).
  28107. *
  28108. * @type {?Texture}
  28109. * @default null
  28110. */
  28111. this.roughnessMap = null;
  28112. /**
  28113. * The blue channel of this texture is used to alter the metalness of the
  28114. * material.
  28115. *
  28116. * `metalnessMap` represents non-color data. Any texture assigned must have
  28117. * `texture.colorSpace = NoColorSpace` (default).
  28118. *
  28119. * @type {?Texture}
  28120. * @default null
  28121. */
  28122. this.metalnessMap = null;
  28123. /**
  28124. * The alpha map is a grayscale texture that controls the opacity across the
  28125. * surface (black: fully transparent; white: fully opaque).
  28126. *
  28127. * Only the color of the texture is used, ignoring the alpha channel if one
  28128. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28129. * when sampling this texture due to the extra bit of precision provided for
  28130. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28131. * luminance/alpha textures will also still work as expected.
  28132. *
  28133. * `alphaMap` represents non-color data. Any texture assigned must have
  28134. * `texture.colorSpace = NoColorSpace` (default).
  28135. *
  28136. * @type {?Texture}
  28137. * @default null
  28138. */
  28139. this.alphaMap = null;
  28140. /**
  28141. * The environment map. To ensure a physically correct rendering, environment maps
  28142. * are internally pre-processed with {@link PMREMGenerator}.
  28143. *
  28144. * `envMap` represents luminance data, and the texture must be assigned
  28145. * a {@link Texture#colorSpace}. Most `envMap` textures set
  28146. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28147. * such as `.exr` or `.hdr`.
  28148. *
  28149. * @type {?Texture}
  28150. * @default null
  28151. */
  28152. this.envMap = null;
  28153. /**
  28154. * The rotation of the environment map in radians.
  28155. *
  28156. * @type {Euler}
  28157. * @default (0,0,0)
  28158. */
  28159. this.envMapRotation = new Euler();
  28160. /**
  28161. * Scales the effect of the environment map by multiplying its color.
  28162. *
  28163. * @type {number}
  28164. * @default 1
  28165. */
  28166. this.envMapIntensity = 1.0;
  28167. /**
  28168. * Renders the geometry as a wireframe.
  28169. *
  28170. * @type {boolean}
  28171. * @default false
  28172. */
  28173. this.wireframe = false;
  28174. /**
  28175. * Controls the thickness of the wireframe.
  28176. *
  28177. * Can only be used with {@link SVGRenderer}.
  28178. *
  28179. * @type {number}
  28180. * @default 1
  28181. */
  28182. this.wireframeLinewidth = 1;
  28183. /**
  28184. * Defines appearance of wireframe ends.
  28185. *
  28186. * Can only be used with {@link SVGRenderer}.
  28187. *
  28188. * @type {('round'|'bevel'|'miter')}
  28189. * @default 'round'
  28190. */
  28191. this.wireframeLinecap = 'round';
  28192. /**
  28193. * Defines appearance of wireframe joints.
  28194. *
  28195. * Can only be used with {@link SVGRenderer}.
  28196. *
  28197. * @type {('round'|'bevel'|'miter')}
  28198. * @default 'round'
  28199. */
  28200. this.wireframeLinejoin = 'round';
  28201. /**
  28202. * Whether the material is rendered with flat shading or not.
  28203. *
  28204. * @type {boolean}
  28205. * @default false
  28206. */
  28207. this.flatShading = false;
  28208. /**
  28209. * Whether the material is affected by fog or not.
  28210. *
  28211. * @type {boolean}
  28212. * @default true
  28213. */
  28214. this.fog = true;
  28215. this.setValues( parameters );
  28216. }
  28217. copy( source ) {
  28218. super.copy( source );
  28219. this.defines = { 'STANDARD': '' };
  28220. this.color.copy( source.color );
  28221. this.roughness = source.roughness;
  28222. this.metalness = source.metalness;
  28223. this.map = source.map;
  28224. this.lightMap = source.lightMap;
  28225. this.lightMapIntensity = source.lightMapIntensity;
  28226. this.aoMap = source.aoMap;
  28227. this.aoMapIntensity = source.aoMapIntensity;
  28228. this.emissive.copy( source.emissive );
  28229. this.emissiveMap = source.emissiveMap;
  28230. this.emissiveIntensity = source.emissiveIntensity;
  28231. this.bumpMap = source.bumpMap;
  28232. this.bumpScale = source.bumpScale;
  28233. this.normalMap = source.normalMap;
  28234. this.normalMapType = source.normalMapType;
  28235. this.normalScale.copy( source.normalScale );
  28236. this.displacementMap = source.displacementMap;
  28237. this.displacementScale = source.displacementScale;
  28238. this.displacementBias = source.displacementBias;
  28239. this.roughnessMap = source.roughnessMap;
  28240. this.metalnessMap = source.metalnessMap;
  28241. this.alphaMap = source.alphaMap;
  28242. this.envMap = source.envMap;
  28243. this.envMapRotation.copy( source.envMapRotation );
  28244. this.envMapIntensity = source.envMapIntensity;
  28245. this.wireframe = source.wireframe;
  28246. this.wireframeLinewidth = source.wireframeLinewidth;
  28247. this.wireframeLinecap = source.wireframeLinecap;
  28248. this.wireframeLinejoin = source.wireframeLinejoin;
  28249. this.flatShading = source.flatShading;
  28250. this.fog = source.fog;
  28251. return this;
  28252. }
  28253. }
  28254. /**
  28255. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28256. * physically-based rendering properties:
  28257. *
  28258. * - Anisotropy: Ability to represent the anisotropic property of materials
  28259. * as observable with brushed metals.
  28260. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28261. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28262. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28263. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28264. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28265. * wings of many insects.
  28266. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28267. * transparent materials are less reflective. Physically-based transmission provides a more
  28268. * realistic option for thin, transparent surfaces like glass.
  28269. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28270. * - Sheen: Can be used for representing cloth and fabric materials.
  28271. *
  28272. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28273. * higher performance cost, per pixel, than other three.js materials. Most
  28274. * effects are disabled by default, and add cost as they are enabled. For
  28275. * best results, always specify an environment map when using this material.
  28276. *
  28277. * @augments MeshStandardMaterial
  28278. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28279. */
  28280. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28281. /**
  28282. * Constructs a new mesh physical material.
  28283. *
  28284. * @param {Object} [parameters] - An object with one or more properties
  28285. * defining the material's appearance. Any property of the material
  28286. * (including any property from inherited materials) can be passed
  28287. * in here. Color values can be passed any type of value accepted
  28288. * by {@link Color#set}.
  28289. */
  28290. constructor( parameters ) {
  28291. super();
  28292. /**
  28293. * This flag can be used for type testing.
  28294. *
  28295. * @type {boolean}
  28296. * @readonly
  28297. * @default true
  28298. */
  28299. this.isMeshPhysicalMaterial = true;
  28300. this.defines = {
  28301. 'STANDARD': '',
  28302. 'PHYSICAL': ''
  28303. };
  28304. this.type = 'MeshPhysicalMaterial';
  28305. /**
  28306. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28307. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28308. * property provides additional rotation to the vectors in the texture.
  28309. *
  28310. * @type {number}
  28311. * @default 1
  28312. */
  28313. this.anisotropyRotation = 0;
  28314. /**
  28315. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28316. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28317. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28318. *
  28319. * `anisotropyMap` represents non-color data. Any texture assigned must have
  28320. * `texture.colorSpace = NoColorSpace` (default).
  28321. *
  28322. * @type {?Texture}
  28323. * @default null
  28324. */
  28325. this.anisotropyMap = null;
  28326. /**
  28327. * The red channel of this texture is multiplied against `clearcoat`,
  28328. * for per-pixel control over a coating's intensity.
  28329. *
  28330. * `clearcoatMap` represents non-color data. Any texture assigned must have
  28331. * `texture.colorSpace = NoColorSpace` (default).
  28332. *
  28333. * @type {?Texture}
  28334. * @default null
  28335. */
  28336. this.clearcoatMap = null;
  28337. /**
  28338. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28339. *
  28340. * @type {number}
  28341. * @default 0
  28342. */
  28343. this.clearcoatRoughness = 0.0;
  28344. /**
  28345. * The green channel of this texture is multiplied against
  28346. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28347. *
  28348. * `clearcoatRoughnessMap` represents non-color data. Any texture assigned must have
  28349. * `texture.colorSpace = NoColorSpace` (default).
  28350. *
  28351. * @type {?Texture}
  28352. * @default null
  28353. */
  28354. this.clearcoatRoughnessMap = null;
  28355. /**
  28356. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28357. * `(0,0)` to `(1,1)`.
  28358. *
  28359. * @type {Vector2}
  28360. * @default (1,1)
  28361. */
  28362. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28363. /**
  28364. * Can be used to enable independent normals for the clear coat layer.
  28365. *
  28366. * `clearcoatNormalMap` represents non-color data. Any texture assigned must have
  28367. * `texture.colorSpace = NoColorSpace` (default).
  28368. *
  28369. * @type {?Texture}
  28370. * @default null
  28371. */
  28372. this.clearcoatNormalMap = null;
  28373. /**
  28374. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28375. *
  28376. * @type {number}
  28377. * @default 1.5
  28378. */
  28379. this.ior = 1.5;
  28380. /**
  28381. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28382. * corresponds to an index-of-refraction of `1.5`.
  28383. *
  28384. * This models the reflectivity of non-metallic materials. It has no effect
  28385. * when `metalness` is `1.0`
  28386. *
  28387. * @name MeshPhysicalMaterial#reflectivity
  28388. * @type {number}
  28389. * @default 0.5
  28390. */
  28391. Object.defineProperty( this, 'reflectivity', {
  28392. get: function () {
  28393. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28394. },
  28395. set: function ( reflectivity ) {
  28396. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28397. }
  28398. } );
  28399. /**
  28400. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28401. * control over iridescence.
  28402. *
  28403. * `iridescenceMap` represents non-color data. Any texture assigned must have
  28404. * `texture.colorSpace = NoColorSpace` (default).
  28405. *
  28406. * @type {?Texture}
  28407. * @default null
  28408. */
  28409. this.iridescenceMap = null;
  28410. /**
  28411. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28412. * Between `1.0` to `2.333`.
  28413. *
  28414. * @type {number}
  28415. * @default 1.3
  28416. */
  28417. this.iridescenceIOR = 1.3;
  28418. /**
  28419. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28420. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28421. *
  28422. * @type {Array<number,number>}
  28423. * @default [100,400]
  28424. */
  28425. this.iridescenceThicknessRange = [ 100, 400 ];
  28426. /**
  28427. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28428. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28429. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28430. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28431. * - Values in-between will linearly interpolate between the elements of the array.
  28432. *
  28433. * `iridescenceThicknessMap` represents non-color data. Any texture assigned must have
  28434. * `texture.colorSpace = NoColorSpace` (default).
  28435. *
  28436. * @type {?Texture}
  28437. * @default null
  28438. */
  28439. this.iridescenceThicknessMap = null;
  28440. /**
  28441. * The sheen tint.
  28442. *
  28443. * @type {Color}
  28444. * @default (0,0,0)
  28445. */
  28446. this.sheenColor = new Color( 0x000000 );
  28447. /**
  28448. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28449. * over sheen tint.
  28450. *
  28451. * `sheenColorMap` represents color data, and the texture must be assigned a
  28452. * {@link Texture#colorSpace}. Most `sheenColorMap` textures set
  28453. * `texture.colorSpace = SRGBColorSpace`.
  28454. *
  28455. * @type {?Texture}
  28456. * @default null
  28457. */
  28458. this.sheenColorMap = null;
  28459. /**
  28460. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28461. *
  28462. * @type {number}
  28463. * @default 1
  28464. */
  28465. this.sheenRoughness = 1.0;
  28466. /**
  28467. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28468. * over sheen roughness.
  28469. *
  28470. * `sheenRoughnessMap` represents non-color data. Any texture assigned must have
  28471. * `texture.colorSpace = NoColorSpace` (default).
  28472. *
  28473. * @type {?Texture}
  28474. * @default null
  28475. */
  28476. this.sheenRoughnessMap = null;
  28477. /**
  28478. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28479. * optical transparency.
  28480. *
  28481. * `transmissionMap` represents non-color data. Any texture assigned must have
  28482. * `texture.colorSpace = NoColorSpace` (default).
  28483. *
  28484. * @type {?Texture}
  28485. * @default null
  28486. */
  28487. this.transmissionMap = null;
  28488. /**
  28489. * The thickness of the volume beneath the surface. The value is given in the
  28490. * coordinate space of the mesh. If the value is `0` the material is
  28491. * thin-walled. Otherwise the material is a volume boundary.
  28492. *
  28493. * @type {number}
  28494. * @default 0
  28495. */
  28496. this.thickness = 0;
  28497. /**
  28498. * A texture that defines the thickness, stored in the green channel. This will
  28499. * be multiplied by `thickness`.
  28500. *
  28501. * `thicknessMap` represents non-color data. Any texture assigned must have
  28502. * `texture.colorSpace = NoColorSpace` (default).
  28503. *
  28504. * @type {?Texture}
  28505. * @default null
  28506. */
  28507. this.thicknessMap = null;
  28508. /**
  28509. * Density of the medium given as the average distance that light travels in
  28510. * the medium before interacting with a particle. The value is given in world
  28511. * space units, and must be greater than zero.
  28512. *
  28513. * @type {number}
  28514. * @default Infinity
  28515. */
  28516. this.attenuationDistance = Infinity;
  28517. /**
  28518. * The color that white light turns into due to absorption when reaching the
  28519. * attenuation distance.
  28520. *
  28521. * @type {Color}
  28522. * @default (1,1,1)
  28523. */
  28524. this.attenuationColor = new Color( 1, 1, 1 );
  28525. /**
  28526. * A float that scales the amount of specular reflection for non-metals only.
  28527. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28528. *
  28529. * @type {number}
  28530. * @default 1
  28531. */
  28532. this.specularIntensity = 1.0;
  28533. /**
  28534. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28535. * for per-pixel control over specular intensity.
  28536. *
  28537. * `specularIntensityMap` represents non-color data. Any texture assigned must have
  28538. * `texture.colorSpace = NoColorSpace` (default).
  28539. *
  28540. * @type {?Texture}
  28541. * @default null
  28542. */
  28543. this.specularIntensityMap = null;
  28544. /**
  28545. * Tints the specular reflection at normal incidence for non-metals only.
  28546. *
  28547. * @type {Color}
  28548. * @default (1,1,1)
  28549. */
  28550. this.specularColor = new Color( 1, 1, 1 );
  28551. /**
  28552. * The RGB channels of this texture are multiplied against `specularColor`,
  28553. * for per-pixel control over specular color.
  28554. *
  28555. * `specularColorMap` represents color data, and the texture must be assigned a
  28556. * {@link Texture#colorSpace}. Most `specularColorMap` textures set
  28557. * `texture.colorSpace = SRGBColorSpace`.
  28558. *
  28559. * @type {?Texture}
  28560. * @default null
  28561. */
  28562. this.specularColorMap = null;
  28563. this._anisotropy = 0;
  28564. this._clearcoat = 0;
  28565. this._dispersion = 0;
  28566. this._iridescence = 0;
  28567. this._sheen = 0.0;
  28568. this._transmission = 0;
  28569. this.setValues( parameters );
  28570. }
  28571. /**
  28572. * The anisotropy strength, from `0.0` to `1.0`.
  28573. *
  28574. * @type {number}
  28575. * @default 0
  28576. */
  28577. get anisotropy() {
  28578. return this._anisotropy;
  28579. }
  28580. set anisotropy( value ) {
  28581. if ( this._anisotropy > 0 !== value > 0 ) {
  28582. this.version ++;
  28583. }
  28584. this._anisotropy = value;
  28585. }
  28586. /**
  28587. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28588. * clear coat related properties to enable multilayer materials that have a
  28589. * thin translucent layer over the base layer.
  28590. *
  28591. * @type {number}
  28592. * @default 0
  28593. */
  28594. get clearcoat() {
  28595. return this._clearcoat;
  28596. }
  28597. set clearcoat( value ) {
  28598. if ( this._clearcoat > 0 !== value > 0 ) {
  28599. this.version ++;
  28600. }
  28601. this._clearcoat = value;
  28602. }
  28603. /**
  28604. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28605. * the surface and the viewer, from `0.0` to `1.0`.
  28606. *
  28607. * @type {number}
  28608. * @default 0
  28609. */
  28610. get iridescence() {
  28611. return this._iridescence;
  28612. }
  28613. set iridescence( value ) {
  28614. if ( this._iridescence > 0 !== value > 0 ) {
  28615. this.version ++;
  28616. }
  28617. this._iridescence = value;
  28618. }
  28619. /**
  28620. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28621. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28622. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28623. *
  28624. * @type {number}
  28625. * @default 0
  28626. */
  28627. get dispersion() {
  28628. return this._dispersion;
  28629. }
  28630. set dispersion( value ) {
  28631. if ( this._dispersion > 0 !== value > 0 ) {
  28632. this.version ++;
  28633. }
  28634. this._dispersion = value;
  28635. }
  28636. /**
  28637. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28638. *
  28639. * @type {number}
  28640. * @default 0
  28641. */
  28642. get sheen() {
  28643. return this._sheen;
  28644. }
  28645. set sheen( value ) {
  28646. if ( this._sheen > 0 !== value > 0 ) {
  28647. this.version ++;
  28648. }
  28649. this._sheen = value;
  28650. }
  28651. /**
  28652. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28653. *
  28654. * Thin, transparent or semitransparent, plastic or glass materials remain
  28655. * largely reflective even if they are fully transmissive. The transmission
  28656. * property can be used to model these materials.
  28657. *
  28658. * When transmission is non-zero, `opacity` should be set to `1`.
  28659. *
  28660. * @type {number}
  28661. * @default 0
  28662. */
  28663. get transmission() {
  28664. return this._transmission;
  28665. }
  28666. set transmission( value ) {
  28667. if ( this._transmission > 0 !== value > 0 ) {
  28668. this.version ++;
  28669. }
  28670. this._transmission = value;
  28671. }
  28672. copy( source ) {
  28673. super.copy( source );
  28674. this.defines = {
  28675. 'STANDARD': '',
  28676. 'PHYSICAL': ''
  28677. };
  28678. this.anisotropy = source.anisotropy;
  28679. this.anisotropyRotation = source.anisotropyRotation;
  28680. this.anisotropyMap = source.anisotropyMap;
  28681. this.clearcoat = source.clearcoat;
  28682. this.clearcoatMap = source.clearcoatMap;
  28683. this.clearcoatRoughness = source.clearcoatRoughness;
  28684. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28685. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28686. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28687. this.dispersion = source.dispersion;
  28688. this.ior = source.ior;
  28689. this.iridescence = source.iridescence;
  28690. this.iridescenceMap = source.iridescenceMap;
  28691. this.iridescenceIOR = source.iridescenceIOR;
  28692. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28693. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28694. this.sheen = source.sheen;
  28695. this.sheenColor.copy( source.sheenColor );
  28696. this.sheenColorMap = source.sheenColorMap;
  28697. this.sheenRoughness = source.sheenRoughness;
  28698. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28699. this.transmission = source.transmission;
  28700. this.transmissionMap = source.transmissionMap;
  28701. this.thickness = source.thickness;
  28702. this.thicknessMap = source.thicknessMap;
  28703. this.attenuationDistance = source.attenuationDistance;
  28704. this.attenuationColor.copy( source.attenuationColor );
  28705. this.specularIntensity = source.specularIntensity;
  28706. this.specularIntensityMap = source.specularIntensityMap;
  28707. this.specularColor.copy( source.specularColor );
  28708. this.specularColorMap = source.specularColorMap;
  28709. return this;
  28710. }
  28711. }
  28712. /**
  28713. * A material for shiny surfaces with specular highlights.
  28714. *
  28715. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28716. * model for calculating reflectance. Unlike the Lambertian model used in the
  28717. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28718. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28719. *
  28720. * Performance will generally be greater when using this material over the
  28721. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28722. * some graphical accuracy.
  28723. *
  28724. * @augments Material
  28725. * @demo scenes/material-browser.html#MeshPhongMaterial
  28726. */
  28727. class MeshPhongMaterial extends Material {
  28728. /**
  28729. * Constructs a new mesh phong material.
  28730. *
  28731. * @param {Object} [parameters] - An object with one or more properties
  28732. * defining the material's appearance. Any property of the material
  28733. * (including any property from inherited materials) can be passed
  28734. * in here. Color values can be passed any type of value accepted
  28735. * by {@link Color#set}.
  28736. */
  28737. constructor( parameters ) {
  28738. super();
  28739. /**
  28740. * This flag can be used for type testing.
  28741. *
  28742. * @type {boolean}
  28743. * @readonly
  28744. * @default true
  28745. */
  28746. this.isMeshPhongMaterial = true;
  28747. this.type = 'MeshPhongMaterial';
  28748. /**
  28749. * Color of the material.
  28750. *
  28751. * @type {Color}
  28752. * @default (1,1,1)
  28753. */
  28754. this.color = new Color( 0xffffff ); // diffuse
  28755. /**
  28756. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28757. *
  28758. * This defines how shiny the material is and the color of its shine.
  28759. *
  28760. * @type {Color}
  28761. */
  28762. this.specular = new Color( 0x111111 );
  28763. /**
  28764. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28765. *
  28766. * @type {number}
  28767. * @default 30
  28768. */
  28769. this.shininess = 30;
  28770. /**
  28771. * The color map. May optionally include an alpha channel, typically combined
  28772. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28773. * color is modulated by the diffuse `color`.
  28774. *
  28775. * `map` represents color data, and the texture must be assigned a
  28776. * {@link Texture#colorSpace}. Most `map` textures set
  28777. * `texture.colorSpace = SRGBColorSpace`.
  28778. *
  28779. * @type {?Texture}
  28780. * @default null
  28781. */
  28782. this.map = null;
  28783. /**
  28784. * The light map. Requires a second set of UVs.
  28785. *
  28786. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  28787. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  28788. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28789. * such as `.exr` or `.hdr`.
  28790. *
  28791. * @type {?Texture}
  28792. * @default null
  28793. */
  28794. this.lightMap = null;
  28795. /**
  28796. * Intensity of the baked light.
  28797. *
  28798. * @type {number}
  28799. * @default 1
  28800. */
  28801. this.lightMapIntensity = 1.0;
  28802. /**
  28803. * The red channel of this texture is used as the ambient occlusion map.
  28804. * Requires a second set of UVs.
  28805. *
  28806. * `aoMap` represents non-color data. Any texture assigned must have
  28807. * `texture.colorSpace = NoColorSpace` (default).
  28808. *
  28809. * @type {?Texture}
  28810. * @default null
  28811. */
  28812. this.aoMap = null;
  28813. /**
  28814. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28815. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28816. * red channel is also `1`, ambient light is fully occluded on a surface.
  28817. *
  28818. * @type {number}
  28819. * @default 1
  28820. */
  28821. this.aoMapIntensity = 1.0;
  28822. /**
  28823. * Emissive (light) color of the material, essentially a solid color
  28824. * unaffected by other lighting.
  28825. *
  28826. * @type {Color}
  28827. * @default (0,0,0)
  28828. */
  28829. this.emissive = new Color( 0x000000 );
  28830. /**
  28831. * Intensity of the emissive light. Modulates the emissive color.
  28832. *
  28833. * @type {number}
  28834. * @default 1
  28835. */
  28836. this.emissiveIntensity = 1.0;
  28837. /**
  28838. * Set emissive (glow) map. The emissive map color is modulated by the
  28839. * emissive color and the emissive intensity. If you have an emissive map,
  28840. * be sure to set the emissive color to something other than black.
  28841. *
  28842. * `emissiveMap` represents color data, and the texture must be assigned a
  28843. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  28844. * `texture.colorSpace = SRGBColorSpace`.
  28845. *
  28846. * @type {?Texture}
  28847. * @default null
  28848. */
  28849. this.emissiveMap = null;
  28850. /**
  28851. * The texture to create a bump map. The black and white values map to the
  28852. * perceived depth in relation to the lights. Bump doesn't actually affect
  28853. * the geometry of the object, only the lighting. If a normal map is defined
  28854. * this will be ignored.
  28855. *
  28856. * `bumpMap` represents non-color data. Any texture assigned must have
  28857. * `texture.colorSpace = NoColorSpace` (default).
  28858. *
  28859. * @type {?Texture}
  28860. * @default null
  28861. */
  28862. this.bumpMap = null;
  28863. /**
  28864. * How much the bump map affects the material. Typical range is `[0,1]`.
  28865. *
  28866. * @type {number}
  28867. * @default 1
  28868. */
  28869. this.bumpScale = 1;
  28870. /**
  28871. * The texture to create a normal map. The RGB values affect the surface
  28872. * normal for each pixel fragment and change the way the color is lit. Normal
  28873. * maps do not change the actual shape of the surface, only the lighting. In
  28874. * case the material has a normal map authored using the left handed
  28875. * convention, the `y` component of `normalScale` should be negated to compensate
  28876. * for the different handedness.
  28877. *
  28878. * `normalMap` represents non-color data. Any texture assigned must have
  28879. * `texture.colorSpace = NoColorSpace` (default).
  28880. *
  28881. * @type {?Texture}
  28882. * @default null
  28883. */
  28884. this.normalMap = null;
  28885. /**
  28886. * The type of normal map.
  28887. *
  28888. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28889. * @default TangentSpaceNormalMap
  28890. */
  28891. this.normalMapType = TangentSpaceNormalMap;
  28892. /**
  28893. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28894. *
  28895. * @type {Vector2}
  28896. * @default (1,1)
  28897. */
  28898. this.normalScale = new Vector2( 1, 1 );
  28899. /**
  28900. * The displacement map affects the position of the mesh's vertices. Unlike
  28901. * other maps which only affect the light and shade of the material the
  28902. * displaced vertices can cast shadows, block other objects, and otherwise
  28903. * act as real geometry. The displacement texture is an image where the value
  28904. * of each pixel (white being the highest) is mapped against, and
  28905. * repositions, the vertices of the mesh. For best results, pair a
  28906. * displacement map with a matching normal map, since the renderer can
  28907. * not recompute surface normals from the displaced vertices.
  28908. *
  28909. * `displacementMap` represents non-color data. Any texture assigned must have
  28910. * `texture.colorSpace = NoColorSpace` (default).
  28911. *
  28912. * @type {?Texture}
  28913. * @default null
  28914. */
  28915. this.displacementMap = null;
  28916. /**
  28917. * How much the displacement map affects the mesh (where black is no
  28918. * displacement, and white is maximum displacement). Without a displacement
  28919. * map set, this value is not applied.
  28920. *
  28921. * @type {number}
  28922. * @default 0
  28923. */
  28924. this.displacementScale = 1;
  28925. /**
  28926. * The offset of the displacement map's values on the mesh's vertices.
  28927. * The bias is added to the scaled sample of the displacement map.
  28928. * Without a displacement map set, this value is not applied.
  28929. *
  28930. * @type {number}
  28931. * @default 0
  28932. */
  28933. this.displacementBias = 0;
  28934. /**
  28935. * The specular map value affects both how much the specular surface
  28936. * highlight contributes and how much of the environment map affects the
  28937. * surface.
  28938. *
  28939. * `specularMap` represents color data, and the texture must be assigned a
  28940. * {@link Texture#colorSpace}. Most `specularMap` textures set
  28941. * `texture.colorSpace = SRGBColorSpace`.
  28942. *
  28943. * @type {?Texture}
  28944. * @default null
  28945. */
  28946. this.specularMap = null;
  28947. /**
  28948. * The alpha map is a grayscale texture that controls the opacity across the
  28949. * surface (black: fully transparent; white: fully opaque).
  28950. *
  28951. * Only the color of the texture is used, ignoring the alpha channel if one
  28952. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28953. * when sampling this texture due to the extra bit of precision provided for
  28954. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28955. * luminance/alpha textures will also still work as expected.
  28956. *
  28957. * `alphaMap` represents non-color data. Any texture assigned must have
  28958. * `texture.colorSpace = NoColorSpace` (default).
  28959. *
  28960. * @type {?Texture}
  28961. * @default null
  28962. */
  28963. this.alphaMap = null;
  28964. /**
  28965. * The environment map.
  28966. *
  28967. * `envMap` represents luminance data, and the texture must be assigned
  28968. * a {@link Texture#colorSpace}. Most `envMap` textures set
  28969. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  28970. * such as `.exr` or `.hdr`.
  28971. *
  28972. * @type {?Texture}
  28973. * @default null
  28974. */
  28975. this.envMap = null;
  28976. /**
  28977. * The rotation of the environment map in radians.
  28978. *
  28979. * @type {Euler}
  28980. * @default (0,0,0)
  28981. */
  28982. this.envMapRotation = new Euler();
  28983. /**
  28984. * How to combine the result of the surface's color with the environment map, if any.
  28985. *
  28986. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28987. * blend between the two colors.
  28988. *
  28989. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28990. * @default MultiplyOperation
  28991. */
  28992. this.combine = MultiplyOperation;
  28993. /**
  28994. * How much the environment map affects the surface.
  28995. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28996. *
  28997. * @type {number}
  28998. * @default 1
  28999. */
  29000. this.reflectivity = 1;
  29001. /**
  29002. * Scales the effect of the environment map by multiplying its color.
  29003. *
  29004. * @type {number}
  29005. * @default 1
  29006. */
  29007. this.envMapIntensity = 1.0;
  29008. /**
  29009. * The index of refraction (IOR) of air (approximately 1) divided by the
  29010. * index of refraction of the material. It is used with environment mapping
  29011. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29012. * The refraction ratio should not exceed `1`.
  29013. *
  29014. * @type {number}
  29015. * @default 0.98
  29016. */
  29017. this.refractionRatio = 0.98;
  29018. /**
  29019. * Renders the geometry as a wireframe.
  29020. *
  29021. * @type {boolean}
  29022. * @default false
  29023. */
  29024. this.wireframe = false;
  29025. /**
  29026. * Controls the thickness of the wireframe.
  29027. *
  29028. * Can only be used with {@link SVGRenderer}.
  29029. *
  29030. * @type {number}
  29031. * @default 1
  29032. */
  29033. this.wireframeLinewidth = 1;
  29034. /**
  29035. * Defines appearance of wireframe ends.
  29036. *
  29037. * Can only be used with {@link SVGRenderer}.
  29038. *
  29039. * @type {('round'|'bevel'|'miter')}
  29040. * @default 'round'
  29041. */
  29042. this.wireframeLinecap = 'round';
  29043. /**
  29044. * Defines appearance of wireframe joints.
  29045. *
  29046. * Can only be used with {@link SVGRenderer}.
  29047. *
  29048. * @type {('round'|'bevel'|'miter')}
  29049. * @default 'round'
  29050. */
  29051. this.wireframeLinejoin = 'round';
  29052. /**
  29053. * Whether the material is rendered with flat shading or not.
  29054. *
  29055. * @type {boolean}
  29056. * @default false
  29057. */
  29058. this.flatShading = false;
  29059. /**
  29060. * Whether the material is affected by fog or not.
  29061. *
  29062. * @type {boolean}
  29063. * @default true
  29064. */
  29065. this.fog = true;
  29066. this.setValues( parameters );
  29067. }
  29068. copy( source ) {
  29069. super.copy( source );
  29070. this.color.copy( source.color );
  29071. this.specular.copy( source.specular );
  29072. this.shininess = source.shininess;
  29073. this.map = source.map;
  29074. this.lightMap = source.lightMap;
  29075. this.lightMapIntensity = source.lightMapIntensity;
  29076. this.aoMap = source.aoMap;
  29077. this.aoMapIntensity = source.aoMapIntensity;
  29078. this.emissive.copy( source.emissive );
  29079. this.emissiveMap = source.emissiveMap;
  29080. this.emissiveIntensity = source.emissiveIntensity;
  29081. this.bumpMap = source.bumpMap;
  29082. this.bumpScale = source.bumpScale;
  29083. this.normalMap = source.normalMap;
  29084. this.normalMapType = source.normalMapType;
  29085. this.normalScale.copy( source.normalScale );
  29086. this.displacementMap = source.displacementMap;
  29087. this.displacementScale = source.displacementScale;
  29088. this.displacementBias = source.displacementBias;
  29089. this.specularMap = source.specularMap;
  29090. this.alphaMap = source.alphaMap;
  29091. this.envMap = source.envMap;
  29092. this.envMapRotation.copy( source.envMapRotation );
  29093. this.combine = source.combine;
  29094. this.reflectivity = source.reflectivity;
  29095. this.envMapIntensity = source.envMapIntensity;
  29096. this.refractionRatio = source.refractionRatio;
  29097. this.wireframe = source.wireframe;
  29098. this.wireframeLinewidth = source.wireframeLinewidth;
  29099. this.wireframeLinecap = source.wireframeLinecap;
  29100. this.wireframeLinejoin = source.wireframeLinejoin;
  29101. this.flatShading = source.flatShading;
  29102. this.fog = source.fog;
  29103. return this;
  29104. }
  29105. }
  29106. /**
  29107. * A material implementing toon shading.
  29108. *
  29109. * @augments Material
  29110. * @demo scenes/material-browser.html#MeshToonMaterial
  29111. */
  29112. class MeshToonMaterial extends Material {
  29113. /**
  29114. * Constructs a new mesh toon material.
  29115. *
  29116. * @param {Object} [parameters] - An object with one or more properties
  29117. * defining the material's appearance. Any property of the material
  29118. * (including any property from inherited materials) can be passed
  29119. * in here. Color values can be passed any type of value accepted
  29120. * by {@link Color#set}.
  29121. */
  29122. constructor( parameters ) {
  29123. super();
  29124. /**
  29125. * This flag can be used for type testing.
  29126. *
  29127. * @type {boolean}
  29128. * @readonly
  29129. * @default true
  29130. */
  29131. this.isMeshToonMaterial = true;
  29132. this.defines = { 'TOON': '' };
  29133. this.type = 'MeshToonMaterial';
  29134. /**
  29135. * Color of the material.
  29136. *
  29137. * @type {Color}
  29138. * @default (1,1,1)
  29139. */
  29140. this.color = new Color( 0xffffff );
  29141. /**
  29142. * The color map. May optionally include an alpha channel, typically combined
  29143. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29144. * color is modulated by the diffuse `color`.
  29145. *
  29146. * `map` represents color data, and the texture must be assigned a
  29147. * {@link Texture#colorSpace}. Most `map` textures set
  29148. * `texture.colorSpace = SRGBColorSpace`.
  29149. *
  29150. * @type {?Texture}
  29151. * @default null
  29152. */
  29153. this.map = null;
  29154. /**
  29155. * Gradient map for toon shading. It's required to set
  29156. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@link NearestFilter}
  29157. * when using this type of texture.
  29158. *
  29159. * `gradientMap` represents non-color data. Any texture assigned must have
  29160. * `texture.colorSpace = NoColorSpace` (default).
  29161. *
  29162. * @type {?Texture}
  29163. * @default null
  29164. */
  29165. this.gradientMap = null;
  29166. /**
  29167. * The light map. Requires a second set of UVs.
  29168. *
  29169. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  29170. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  29171. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29172. * such as `.exr` or `.hdr`.
  29173. *
  29174. * @type {?Texture}
  29175. * @default null
  29176. */
  29177. this.lightMap = null;
  29178. /**
  29179. * Intensity of the baked light.
  29180. *
  29181. * @type {number}
  29182. * @default 1
  29183. */
  29184. this.lightMapIntensity = 1.0;
  29185. /**
  29186. * The red channel of this texture is used as the ambient occlusion map.
  29187. * Requires a second set of UVs.
  29188. *
  29189. * `aoMap` represents non-color data. Any texture assigned must have
  29190. * `texture.colorSpace = NoColorSpace` (default).
  29191. *
  29192. * @type {?Texture}
  29193. * @default null
  29194. */
  29195. this.aoMap = null;
  29196. /**
  29197. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29198. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29199. * red channel is also `1`, ambient light is fully occluded on a surface.
  29200. *
  29201. * @type {number}
  29202. * @default 1
  29203. */
  29204. this.aoMapIntensity = 1.0;
  29205. /**
  29206. * Emissive (light) color of the material, essentially a solid color
  29207. * unaffected by other lighting.
  29208. *
  29209. * @type {Color}
  29210. * @default (0,0,0)
  29211. */
  29212. this.emissive = new Color( 0x000000 );
  29213. /**
  29214. * Intensity of the emissive light. Modulates the emissive color.
  29215. *
  29216. * @type {number}
  29217. * @default 1
  29218. */
  29219. this.emissiveIntensity = 1.0;
  29220. /**
  29221. * Set emissive (glow) map. The emissive map color is modulated by the
  29222. * emissive color and the emissive intensity. If you have an emissive map,
  29223. * be sure to set the emissive color to something other than black.
  29224. *
  29225. * `emissiveMap` represents color data, and the texture must be assigned a
  29226. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  29227. * `texture.colorSpace = SRGBColorSpace`.
  29228. *
  29229. * @type {?Texture}
  29230. * @default null
  29231. */
  29232. this.emissiveMap = null;
  29233. /**
  29234. * The texture to create a bump map. The black and white values map to the
  29235. * perceived depth in relation to the lights. Bump doesn't actually affect
  29236. * the geometry of the object, only the lighting. If a normal map is defined
  29237. * this will be ignored.
  29238. *
  29239. * `bumpMap` represents non-color data. Any texture assigned must have
  29240. * `texture.colorSpace = NoColorSpace` (default).
  29241. *
  29242. * @type {?Texture}
  29243. * @default null
  29244. */
  29245. this.bumpMap = null;
  29246. /**
  29247. * How much the bump map affects the material. Typical range is `[0,1]`.
  29248. *
  29249. * @type {number}
  29250. * @default 1
  29251. */
  29252. this.bumpScale = 1;
  29253. /**
  29254. * The texture to create a normal map. The RGB values affect the surface
  29255. * normal for each pixel fragment and change the way the color is lit. Normal
  29256. * maps do not change the actual shape of the surface, only the lighting. In
  29257. * case the material has a normal map authored using the left handed
  29258. * convention, the `y` component of `normalScale` should be negated to compensate
  29259. * for the different handedness.
  29260. *
  29261. * `normalMap` represents non-color data. Any texture assigned must have
  29262. * `texture.colorSpace = NoColorSpace` (default).
  29263. *
  29264. * @type {?Texture}
  29265. * @default null
  29266. */
  29267. this.normalMap = null;
  29268. /**
  29269. * The type of normal map.
  29270. *
  29271. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29272. * @default TangentSpaceNormalMap
  29273. */
  29274. this.normalMapType = TangentSpaceNormalMap;
  29275. /**
  29276. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29277. *
  29278. * @type {Vector2}
  29279. * @default (1,1)
  29280. */
  29281. this.normalScale = new Vector2( 1, 1 );
  29282. /**
  29283. * The displacement map affects the position of the mesh's vertices. Unlike
  29284. * other maps which only affect the light and shade of the material the
  29285. * displaced vertices can cast shadows, block other objects, and otherwise
  29286. * act as real geometry. The displacement texture is an image where the value
  29287. * of each pixel (white being the highest) is mapped against, and
  29288. * repositions, the vertices of the mesh. For best results, pair a
  29289. * displacement map with a matching normal map, since the renderer can
  29290. * not recompute surface normals from the displaced vertices.
  29291. *
  29292. * `displacementMap` represents non-color data. Any texture assigned must have
  29293. * `texture.colorSpace = NoColorSpace` (default).
  29294. *
  29295. * @type {?Texture}
  29296. * @default null
  29297. */
  29298. this.displacementMap = null;
  29299. /**
  29300. * How much the displacement map affects the mesh (where black is no
  29301. * displacement, and white is maximum displacement). Without a displacement
  29302. * map set, this value is not applied.
  29303. *
  29304. * @type {number}
  29305. * @default 0
  29306. */
  29307. this.displacementScale = 1;
  29308. /**
  29309. * The offset of the displacement map's values on the mesh's vertices.
  29310. * The bias is added to the scaled sample of the displacement map.
  29311. * Without a displacement map set, this value is not applied.
  29312. *
  29313. * @type {number}
  29314. * @default 0
  29315. */
  29316. this.displacementBias = 0;
  29317. /**
  29318. * The alpha map is a grayscale texture that controls the opacity across the
  29319. * surface (black: fully transparent; white: fully opaque).
  29320. *
  29321. * Only the color of the texture is used, ignoring the alpha channel if one
  29322. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29323. * when sampling this texture due to the extra bit of precision provided for
  29324. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29325. * luminance/alpha textures will also still work as expected.
  29326. *
  29327. * `alphaMap` represents non-color data. Any texture assigned must have
  29328. * `texture.colorSpace = NoColorSpace` (default).
  29329. *
  29330. * @type {?Texture}
  29331. * @default null
  29332. */
  29333. this.alphaMap = null;
  29334. /**
  29335. * Renders the geometry as a wireframe.
  29336. *
  29337. * @type {boolean}
  29338. * @default false
  29339. */
  29340. this.wireframe = false;
  29341. /**
  29342. * Controls the thickness of the wireframe.
  29343. *
  29344. * Can only be used with {@link SVGRenderer}.
  29345. *
  29346. * @type {number}
  29347. * @default 1
  29348. */
  29349. this.wireframeLinewidth = 1;
  29350. /**
  29351. * Defines appearance of wireframe ends.
  29352. *
  29353. * Can only be used with {@link SVGRenderer}.
  29354. *
  29355. * @type {('round'|'bevel'|'miter')}
  29356. * @default 'round'
  29357. */
  29358. this.wireframeLinecap = 'round';
  29359. /**
  29360. * Defines appearance of wireframe joints.
  29361. *
  29362. * Can only be used with {@link SVGRenderer}.
  29363. *
  29364. * @type {('round'|'bevel'|'miter')}
  29365. * @default 'round'
  29366. */
  29367. this.wireframeLinejoin = 'round';
  29368. /**
  29369. * Whether the material is affected by fog or not.
  29370. *
  29371. * @type {boolean}
  29372. * @default true
  29373. */
  29374. this.fog = true;
  29375. this.setValues( parameters );
  29376. }
  29377. copy( source ) {
  29378. super.copy( source );
  29379. this.color.copy( source.color );
  29380. this.map = source.map;
  29381. this.gradientMap = source.gradientMap;
  29382. this.lightMap = source.lightMap;
  29383. this.lightMapIntensity = source.lightMapIntensity;
  29384. this.aoMap = source.aoMap;
  29385. this.aoMapIntensity = source.aoMapIntensity;
  29386. this.emissive.copy( source.emissive );
  29387. this.emissiveMap = source.emissiveMap;
  29388. this.emissiveIntensity = source.emissiveIntensity;
  29389. this.bumpMap = source.bumpMap;
  29390. this.bumpScale = source.bumpScale;
  29391. this.normalMap = source.normalMap;
  29392. this.normalMapType = source.normalMapType;
  29393. this.normalScale.copy( source.normalScale );
  29394. this.displacementMap = source.displacementMap;
  29395. this.displacementScale = source.displacementScale;
  29396. this.displacementBias = source.displacementBias;
  29397. this.alphaMap = source.alphaMap;
  29398. this.wireframe = source.wireframe;
  29399. this.wireframeLinewidth = source.wireframeLinewidth;
  29400. this.wireframeLinecap = source.wireframeLinecap;
  29401. this.wireframeLinejoin = source.wireframeLinejoin;
  29402. this.fog = source.fog;
  29403. return this;
  29404. }
  29405. }
  29406. /**
  29407. * A material that maps the normal vectors to RGB colors.
  29408. *
  29409. * @augments Material
  29410. * @demo scenes/material-browser.html#MeshNormalMaterial
  29411. */
  29412. class MeshNormalMaterial extends Material {
  29413. /**
  29414. * Constructs a new mesh normal material.
  29415. *
  29416. * @param {Object} [parameters] - An object with one or more properties
  29417. * defining the material's appearance. Any property of the material
  29418. * (including any property from inherited materials) can be passed
  29419. * in here. Color values can be passed any type of value accepted
  29420. * by {@link Color#set}.
  29421. */
  29422. constructor( parameters ) {
  29423. super();
  29424. /**
  29425. * This flag can be used for type testing.
  29426. *
  29427. * @type {boolean}
  29428. * @readonly
  29429. * @default true
  29430. */
  29431. this.isMeshNormalMaterial = true;
  29432. this.type = 'MeshNormalMaterial';
  29433. /**
  29434. * The texture to create a bump map. The black and white values map to the
  29435. * perceived depth in relation to the lights. Bump doesn't actually affect
  29436. * the geometry of the object, only the lighting. If a normal map is defined
  29437. * this will be ignored.
  29438. *
  29439. * `bumpMap` represents non-color data. Any texture assigned must have
  29440. * `texture.colorSpace = NoColorSpace` (default).
  29441. *
  29442. * @type {?Texture}
  29443. * @default null
  29444. */
  29445. this.bumpMap = null;
  29446. /**
  29447. * How much the bump map affects the material. Typical range is `[0,1]`.
  29448. *
  29449. * @type {number}
  29450. * @default 1
  29451. */
  29452. this.bumpScale = 1;
  29453. /**
  29454. * The texture to create a normal map. The RGB values affect the surface
  29455. * normal for each pixel fragment and change the way the color is lit. Normal
  29456. * maps do not change the actual shape of the surface, only the lighting. In
  29457. * case the material has a normal map authored using the left handed
  29458. * convention, the `y` component of `normalScale` should be negated to compensate
  29459. * for the different handedness.
  29460. *
  29461. * `normalMap` represents non-color data. Any texture assigned must have
  29462. * `texture.colorSpace = NoColorSpace` (default).
  29463. *
  29464. * @type {?Texture}
  29465. * @default null
  29466. */
  29467. this.normalMap = null;
  29468. /**
  29469. * The type of normal map.
  29470. *
  29471. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29472. * @default TangentSpaceNormalMap
  29473. */
  29474. this.normalMapType = TangentSpaceNormalMap;
  29475. /**
  29476. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29477. *
  29478. * @type {Vector2}
  29479. * @default (1,1)
  29480. */
  29481. this.normalScale = new Vector2( 1, 1 );
  29482. /**
  29483. * The displacement map affects the position of the mesh's vertices. Unlike
  29484. * other maps which only affect the light and shade of the material the
  29485. * displaced vertices can cast shadows, block other objects, and otherwise
  29486. * act as real geometry. The displacement texture is an image where the value
  29487. * of each pixel (white being the highest) is mapped against, and
  29488. * repositions, the vertices of the mesh. For best results, pair a
  29489. * displacement map with a matching normal map, since the renderer can
  29490. * not recompute surface normals from the displaced vertices.
  29491. *
  29492. * @type {?Texture}
  29493. * @default null
  29494. */
  29495. this.displacementMap = null;
  29496. /**
  29497. * How much the displacement map affects the mesh (where black is no
  29498. * displacement, and white is maximum displacement). Without a displacement
  29499. * map set, this value is not applied.
  29500. *
  29501. * @type {number}
  29502. * @default 0
  29503. */
  29504. this.displacementScale = 1;
  29505. /**
  29506. * The offset of the displacement map's values on the mesh's vertices.
  29507. * The bias is added to the scaled sample of the displacement map.
  29508. * Without a displacement map set, this value is not applied.
  29509. *
  29510. * @type {number}
  29511. * @default 0
  29512. */
  29513. this.displacementBias = 0;
  29514. /**
  29515. * Renders the geometry as a wireframe.
  29516. *
  29517. * @type {boolean}
  29518. * @default false
  29519. */
  29520. this.wireframe = false;
  29521. /**
  29522. * Controls the thickness of the wireframe.
  29523. *
  29524. * WebGL and WebGPU ignore this property and always render
  29525. * 1 pixel wide lines.
  29526. *
  29527. * @type {number}
  29528. * @default 1
  29529. */
  29530. this.wireframeLinewidth = 1;
  29531. /**
  29532. * Whether the material is rendered with flat shading or not.
  29533. *
  29534. * @type {boolean}
  29535. * @default false
  29536. */
  29537. this.flatShading = false;
  29538. this.setValues( parameters );
  29539. }
  29540. copy( source ) {
  29541. super.copy( source );
  29542. this.bumpMap = source.bumpMap;
  29543. this.bumpScale = source.bumpScale;
  29544. this.normalMap = source.normalMap;
  29545. this.normalMapType = source.normalMapType;
  29546. this.normalScale.copy( source.normalScale );
  29547. this.displacementMap = source.displacementMap;
  29548. this.displacementScale = source.displacementScale;
  29549. this.displacementBias = source.displacementBias;
  29550. this.wireframe = source.wireframe;
  29551. this.wireframeLinewidth = source.wireframeLinewidth;
  29552. this.flatShading = source.flatShading;
  29553. return this;
  29554. }
  29555. }
  29556. /**
  29557. * A material for non-shiny surfaces, without specular highlights.
  29558. *
  29559. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29560. * model for calculating reflectance. This can simulate some surfaces (such
  29561. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29562. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29563. * shading.
  29564. *
  29565. * Due to the simplicity of the reflectance and illumination models,
  29566. * performance will be greater when using this material over the
  29567. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29568. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29569. *
  29570. * @augments Material
  29571. * @demo scenes/material-browser.html#MeshLambertMaterial
  29572. */
  29573. class MeshLambertMaterial extends Material {
  29574. /**
  29575. * Constructs a new mesh lambert material.
  29576. *
  29577. * @param {Object} [parameters] - An object with one or more properties
  29578. * defining the material's appearance. Any property of the material
  29579. * (including any property from inherited materials) can be passed
  29580. * in here. Color values can be passed any type of value accepted
  29581. * by {@link Color#set}.
  29582. */
  29583. constructor( parameters ) {
  29584. super();
  29585. /**
  29586. * This flag can be used for type testing.
  29587. *
  29588. * @type {boolean}
  29589. * @readonly
  29590. * @default true
  29591. */
  29592. this.isMeshLambertMaterial = true;
  29593. this.type = 'MeshLambertMaterial';
  29594. /**
  29595. * Color of the material.
  29596. *
  29597. * @type {Color}
  29598. * @default (1,1,1)
  29599. */
  29600. this.color = new Color( 0xffffff ); // diffuse
  29601. /**
  29602. * The color map. May optionally include an alpha channel, typically combined
  29603. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29604. * color is modulated by the diffuse `color`.
  29605. *
  29606. * `map` represents color data, and the texture must be assigned a
  29607. * {@link Texture#colorSpace}. Most `map` textures set
  29608. * `texture.colorSpace = SRGBColorSpace`.
  29609. *
  29610. * @type {?Texture}
  29611. * @default null
  29612. */
  29613. this.map = null;
  29614. /**
  29615. * The light map. Requires a second set of UVs.
  29616. *
  29617. * `lightMap` represents pre-baked illuminance data, and the texture must be assigned
  29618. * a {@link Texture#colorSpace}. Most `lightMap` textures set
  29619. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29620. * such as `.exr` or `.hdr`.
  29621. *
  29622. * @type {?Texture}
  29623. * @default null
  29624. */
  29625. this.lightMap = null;
  29626. /**
  29627. * Intensity of the baked light.
  29628. *
  29629. * @type {number}
  29630. * @default 1
  29631. */
  29632. this.lightMapIntensity = 1.0;
  29633. /**
  29634. * The red channel of this texture is used as the ambient occlusion map.
  29635. * Requires a second set of UVs.
  29636. *
  29637. * `aoMap` represents non-color data. Any texture assigned must have
  29638. * `texture.colorSpace = NoColorSpace` (default).
  29639. *
  29640. * @type {?Texture}
  29641. * @default null
  29642. */
  29643. this.aoMap = null;
  29644. /**
  29645. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29646. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29647. * red channel is also `1`, ambient light is fully occluded on a surface.
  29648. *
  29649. * @type {number}
  29650. * @default 1
  29651. */
  29652. this.aoMapIntensity = 1.0;
  29653. /**
  29654. * Emissive (light) color of the material, essentially a solid color
  29655. * unaffected by other lighting.
  29656. *
  29657. * @type {Color}
  29658. * @default (0,0,0)
  29659. */
  29660. this.emissive = new Color( 0x000000 );
  29661. /**
  29662. * Intensity of the emissive light. Modulates the emissive color.
  29663. *
  29664. * @type {number}
  29665. * @default 1
  29666. */
  29667. this.emissiveIntensity = 1.0;
  29668. /**
  29669. * Set emissive (glow) map. The emissive map color is modulated by the
  29670. * emissive color and the emissive intensity. If you have an emissive map,
  29671. * be sure to set the emissive color to something other than black.
  29672. *
  29673. * `emissiveMap` represents color data, and the texture must be assigned a
  29674. * {@link Texture#colorSpace}. Most `emissiveMap` textures set
  29675. * `texture.colorSpace = SRGBColorSpace`.
  29676. *
  29677. * @type {?Texture}
  29678. * @default null
  29679. */
  29680. this.emissiveMap = null;
  29681. /**
  29682. * The texture to create a bump map. The black and white values map to the
  29683. * perceived depth in relation to the lights. Bump doesn't actually affect
  29684. * the geometry of the object, only the lighting. If a normal map is defined
  29685. * this will be ignored.
  29686. *
  29687. * `bumpMap` represents non-color data. Any texture assigned must have
  29688. * `texture.colorSpace = NoColorSpace` (default).
  29689. *
  29690. * @type {?Texture}
  29691. * @default null
  29692. */
  29693. this.bumpMap = null;
  29694. /**
  29695. * How much the bump map affects the material. Typical range is `[0,1]`.
  29696. *
  29697. * @type {number}
  29698. * @default 1
  29699. */
  29700. this.bumpScale = 1;
  29701. /**
  29702. * The texture to create a normal map. The RGB values affect the surface
  29703. * normal for each pixel fragment and change the way the color is lit. Normal
  29704. * maps do not change the actual shape of the surface, only the lighting. In
  29705. * case the material has a normal map authored using the left handed
  29706. * convention, the `y` component of `normalScale` should be negated to compensate
  29707. * for the different handedness.
  29708. *
  29709. * `normalMap` represents non-color data. Any texture assigned must have
  29710. * `texture.colorSpace = NoColorSpace` (default).
  29711. *
  29712. * @type {?Texture}
  29713. * @default null
  29714. */
  29715. this.normalMap = null;
  29716. /**
  29717. * The type of normal map.
  29718. *
  29719. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29720. * @default TangentSpaceNormalMap
  29721. */
  29722. this.normalMapType = TangentSpaceNormalMap;
  29723. /**
  29724. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29725. *
  29726. * @type {Vector2}
  29727. * @default (1,1)
  29728. */
  29729. this.normalScale = new Vector2( 1, 1 );
  29730. /**
  29731. * The displacement map affects the position of the mesh's vertices. Unlike
  29732. * other maps which only affect the light and shade of the material the
  29733. * displaced vertices can cast shadows, block other objects, and otherwise
  29734. * act as real geometry. The displacement texture is an image where the value
  29735. * of each pixel (white being the highest) is mapped against, and
  29736. * repositions, the vertices of the mesh. For best results, pair a
  29737. * displacement map with a matching normal map, since the renderer can
  29738. * not recompute surface normals from the displaced vertices.
  29739. *
  29740. * `displacementMap` represents non-color data. Any texture assigned must have
  29741. * `texture.colorSpace = NoColorSpace` (default).
  29742. *
  29743. * @type {?Texture}
  29744. * @default null
  29745. */
  29746. this.displacementMap = null;
  29747. /**
  29748. * How much the displacement map affects the mesh (where black is no
  29749. * displacement, and white is maximum displacement). Without a displacement
  29750. * map set, this value is not applied.
  29751. *
  29752. * @type {number}
  29753. * @default 0
  29754. */
  29755. this.displacementScale = 1;
  29756. /**
  29757. * The offset of the displacement map's values on the mesh's vertices.
  29758. * The bias is added to the scaled sample of the displacement map.
  29759. * Without a displacement map set, this value is not applied.
  29760. *
  29761. * @type {number}
  29762. * @default 0
  29763. */
  29764. this.displacementBias = 0;
  29765. /**
  29766. * Specular map used by the material.
  29767. *
  29768. * `specularMap` represents color data, and the texture must be assigned a
  29769. * {@link Texture#colorSpace}. Most `specularMap` textures set
  29770. * `texture.colorSpace = SRGBColorSpace`.
  29771. *
  29772. * @type {?Texture}
  29773. * @default null
  29774. */
  29775. this.specularMap = null;
  29776. /**
  29777. * The alpha map is a grayscale texture that controls the opacity across the
  29778. * surface (black: fully transparent; white: fully opaque).
  29779. *
  29780. * Only the color of the texture is used, ignoring the alpha channel if one
  29781. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29782. * when sampling this texture due to the extra bit of precision provided for
  29783. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29784. * luminance/alpha textures will also still work as expected.
  29785. *
  29786. * `alphaMap` represents non-color data. Any texture assigned must have
  29787. * `texture.colorSpace = NoColorSpace` (default).
  29788. *
  29789. * @type {?Texture}
  29790. * @default null
  29791. */
  29792. this.alphaMap = null;
  29793. /**
  29794. * The environment map.
  29795. *
  29796. * `envMap` represents luminance data, and the texture must be assigned
  29797. * a {@link Texture#colorSpace}. Most `envMap` textures set
  29798. * `texture.colorSpace = LinearSRGBColorSpace` and use float-type formats
  29799. * such as `.exr` or `.hdr`.
  29800. *
  29801. * @type {?Texture}
  29802. * @default null
  29803. */
  29804. this.envMap = null;
  29805. /**
  29806. * The rotation of the environment map in radians.
  29807. *
  29808. * @type {Euler}
  29809. * @default (0,0,0)
  29810. */
  29811. this.envMapRotation = new Euler();
  29812. /**
  29813. * How to combine the result of the surface's color with the environment map, if any.
  29814. *
  29815. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29816. * blend between the two colors.
  29817. *
  29818. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29819. * @default MultiplyOperation
  29820. */
  29821. this.combine = MultiplyOperation;
  29822. /**
  29823. * How much the environment map affects the surface.
  29824. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29825. *
  29826. * @type {number}
  29827. * @default 1
  29828. */
  29829. this.reflectivity = 1;
  29830. /**
  29831. * Scales the effect of the environment map by multiplying its color.
  29832. *
  29833. * @type {number}
  29834. * @default 1
  29835. */
  29836. this.envMapIntensity = 1.0;
  29837. /**
  29838. * The index of refraction (IOR) of air (approximately 1) divided by the
  29839. * index of refraction of the material. It is used with environment mapping
  29840. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29841. * The refraction ratio should not exceed `1`.
  29842. *
  29843. * @type {number}
  29844. * @default 0.98
  29845. */
  29846. this.refractionRatio = 0.98;
  29847. /**
  29848. * Renders the geometry as a wireframe.
  29849. *
  29850. * @type {boolean}
  29851. * @default false
  29852. */
  29853. this.wireframe = false;
  29854. /**
  29855. * Controls the thickness of the wireframe.
  29856. *
  29857. * Can only be used with {@link SVGRenderer}.
  29858. *
  29859. * @type {number}
  29860. * @default 1
  29861. */
  29862. this.wireframeLinewidth = 1;
  29863. /**
  29864. * Defines appearance of wireframe ends.
  29865. *
  29866. * Can only be used with {@link SVGRenderer}.
  29867. *
  29868. * @type {('round'|'bevel'|'miter')}
  29869. * @default 'round'
  29870. */
  29871. this.wireframeLinecap = 'round';
  29872. /**
  29873. * Defines appearance of wireframe joints.
  29874. *
  29875. * Can only be used with {@link SVGRenderer}.
  29876. *
  29877. * @type {('round'|'bevel'|'miter')}
  29878. * @default 'round'
  29879. */
  29880. this.wireframeLinejoin = 'round';
  29881. /**
  29882. * Whether the material is rendered with flat shading or not.
  29883. *
  29884. * @type {boolean}
  29885. * @default false
  29886. */
  29887. this.flatShading = false;
  29888. /**
  29889. * Whether the material is affected by fog or not.
  29890. *
  29891. * @type {boolean}
  29892. * @default true
  29893. */
  29894. this.fog = true;
  29895. this.setValues( parameters );
  29896. }
  29897. copy( source ) {
  29898. super.copy( source );
  29899. this.color.copy( source.color );
  29900. this.map = source.map;
  29901. this.lightMap = source.lightMap;
  29902. this.lightMapIntensity = source.lightMapIntensity;
  29903. this.aoMap = source.aoMap;
  29904. this.aoMapIntensity = source.aoMapIntensity;
  29905. this.emissive.copy( source.emissive );
  29906. this.emissiveMap = source.emissiveMap;
  29907. this.emissiveIntensity = source.emissiveIntensity;
  29908. this.bumpMap = source.bumpMap;
  29909. this.bumpScale = source.bumpScale;
  29910. this.normalMap = source.normalMap;
  29911. this.normalMapType = source.normalMapType;
  29912. this.normalScale.copy( source.normalScale );
  29913. this.displacementMap = source.displacementMap;
  29914. this.displacementScale = source.displacementScale;
  29915. this.displacementBias = source.displacementBias;
  29916. this.specularMap = source.specularMap;
  29917. this.alphaMap = source.alphaMap;
  29918. this.envMap = source.envMap;
  29919. this.envMapRotation.copy( source.envMapRotation );
  29920. this.combine = source.combine;
  29921. this.reflectivity = source.reflectivity;
  29922. this.envMapIntensity = source.envMapIntensity;
  29923. this.refractionRatio = source.refractionRatio;
  29924. this.wireframe = source.wireframe;
  29925. this.wireframeLinewidth = source.wireframeLinewidth;
  29926. this.wireframeLinecap = source.wireframeLinecap;
  29927. this.wireframeLinejoin = source.wireframeLinejoin;
  29928. this.flatShading = source.flatShading;
  29929. this.fog = source.fog;
  29930. return this;
  29931. }
  29932. }
  29933. /**
  29934. * A material for drawing geometry by depth. Depth is based off of the camera
  29935. * near and far plane. White is nearest, black is farthest.
  29936. *
  29937. * @augments Material
  29938. * @demo scenes/material-browser.html#MeshDepthMaterial
  29939. */
  29940. class MeshDepthMaterial extends Material {
  29941. /**
  29942. * Constructs a new mesh depth material.
  29943. *
  29944. * @param {Object} [parameters] - An object with one or more properties
  29945. * defining the material's appearance. Any property of the material
  29946. * (including any property from inherited materials) can be passed
  29947. * in here. Color values can be passed any type of value accepted
  29948. * by {@link Color#set}.
  29949. */
  29950. constructor( parameters ) {
  29951. super();
  29952. /**
  29953. * This flag can be used for type testing.
  29954. *
  29955. * @type {boolean}
  29956. * @readonly
  29957. * @default true
  29958. */
  29959. this.isMeshDepthMaterial = true;
  29960. this.type = 'MeshDepthMaterial';
  29961. /**
  29962. * Type for depth packing.
  29963. *
  29964. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29965. * @default BasicDepthPacking
  29966. */
  29967. this.depthPacking = BasicDepthPacking;
  29968. /**
  29969. * The color map. May optionally include an alpha channel, typically combined
  29970. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29971. *
  29972. * `map` represents color data, and the texture must be assigned a
  29973. * {@link Texture#colorSpace}. Most `map` textures set
  29974. * `texture.colorSpace = SRGBColorSpace`.
  29975. *
  29976. * @type {?Texture}
  29977. * @default null
  29978. */
  29979. this.map = null;
  29980. /**
  29981. * The alpha map is a grayscale texture that controls the opacity across the
  29982. * surface (black: fully transparent; white: fully opaque).
  29983. *
  29984. * Only the color of the texture is used, ignoring the alpha channel if one
  29985. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29986. * when sampling this texture due to the extra bit of precision provided for
  29987. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29988. * luminance/alpha textures will also still work as expected.
  29989. *
  29990. * `alphaMap` represents non-color data. Any texture assigned must have
  29991. * `texture.colorSpace = NoColorSpace` (default).
  29992. *
  29993. * @type {?Texture}
  29994. * @default null
  29995. */
  29996. this.alphaMap = null;
  29997. /**
  29998. * The displacement map affects the position of the mesh's vertices. Unlike
  29999. * other maps which only affect the light and shade of the material the
  30000. * displaced vertices can cast shadows, block other objects, and otherwise
  30001. * act as real geometry. The displacement texture is an image where the value
  30002. * of each pixel (white being the highest) is mapped against, and
  30003. * repositions, the vertices of the mesh.
  30004. *
  30005. * `displacementMap` represents non-color data. Any texture assigned must have
  30006. * `texture.colorSpace = NoColorSpace` (default).
  30007. *
  30008. * @type {?Texture}
  30009. * @default null
  30010. */
  30011. this.displacementMap = null;
  30012. /**
  30013. * How much the displacement map affects the mesh (where black is no
  30014. * displacement, and white is maximum displacement). Without a displacement
  30015. * map set, this value is not applied.
  30016. *
  30017. * @type {number}
  30018. * @default 0
  30019. */
  30020. this.displacementScale = 1;
  30021. /**
  30022. * The offset of the displacement map's values on the mesh's vertices.
  30023. * The bias is added to the scaled sample of the displacement map.
  30024. * Without a displacement map set, this value is not applied.
  30025. *
  30026. * @type {number}
  30027. * @default 0
  30028. */
  30029. this.displacementBias = 0;
  30030. /**
  30031. * Renders the geometry as a wireframe.
  30032. *
  30033. * @type {boolean}
  30034. * @default false
  30035. */
  30036. this.wireframe = false;
  30037. /**
  30038. * Controls the thickness of the wireframe.
  30039. *
  30040. * WebGL and WebGPU ignore this property and always render
  30041. * 1 pixel wide lines.
  30042. *
  30043. * @type {number}
  30044. * @default 1
  30045. */
  30046. this.wireframeLinewidth = 1;
  30047. this.setValues( parameters );
  30048. }
  30049. copy( source ) {
  30050. super.copy( source );
  30051. this.depthPacking = source.depthPacking;
  30052. this.map = source.map;
  30053. this.alphaMap = source.alphaMap;
  30054. this.displacementMap = source.displacementMap;
  30055. this.displacementScale = source.displacementScale;
  30056. this.displacementBias = source.displacementBias;
  30057. this.wireframe = source.wireframe;
  30058. this.wireframeLinewidth = source.wireframeLinewidth;
  30059. return this;
  30060. }
  30061. }
  30062. /**
  30063. * A material used internally for implementing shadow mapping with
  30064. * point lights.
  30065. *
  30066. * Can also be used to customize the shadow casting of an object by assigning
  30067. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30068. * The following examples demonstrates this approach in order to ensure
  30069. * transparent parts of objects do not cast shadows.
  30070. *
  30071. * @augments Material
  30072. */
  30073. class MeshDistanceMaterial extends Material {
  30074. /**
  30075. * Constructs a new mesh distance material.
  30076. *
  30077. * @param {Object} [parameters] - An object with one or more properties
  30078. * defining the material's appearance. Any property of the material
  30079. * (including any property from inherited materials) can be passed
  30080. * in here. Color values can be passed any type of value accepted
  30081. * by {@link Color#set}.
  30082. */
  30083. constructor( parameters ) {
  30084. super();
  30085. /**
  30086. * This flag can be used for type testing.
  30087. *
  30088. * @type {boolean}
  30089. * @readonly
  30090. * @default true
  30091. */
  30092. this.isMeshDistanceMaterial = true;
  30093. this.type = 'MeshDistanceMaterial';
  30094. /**
  30095. * The color map. May optionally include an alpha channel, typically combined
  30096. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30097. *
  30098. * `map` represents color data, and the texture must be assigned a
  30099. * {@link Texture#colorSpace}. Most `map` textures set
  30100. * `texture.colorSpace = SRGBColorSpace`.
  30101. *
  30102. * @type {?Texture}
  30103. * @default null
  30104. */
  30105. this.map = null;
  30106. /**
  30107. * The alpha map is a grayscale texture that controls the opacity across the
  30108. * surface (black: fully transparent; white: fully opaque).
  30109. *
  30110. * Only the color of the texture is used, ignoring the alpha channel if one
  30111. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30112. * when sampling this texture due to the extra bit of precision provided for
  30113. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30114. * luminance/alpha textures will also still work as expected.
  30115. *
  30116. * `alphaMap` represents non-color data. Any texture assigned must have
  30117. * `texture.colorSpace = NoColorSpace` (default).
  30118. *
  30119. * @type {?Texture}
  30120. * @default null
  30121. */
  30122. this.alphaMap = null;
  30123. /**
  30124. * The displacement map affects the position of the mesh's vertices. Unlike
  30125. * other maps which only affect the light and shade of the material the
  30126. * displaced vertices can cast shadows, block other objects, and otherwise
  30127. * act as real geometry. The displacement texture is an image where the value
  30128. * of each pixel (white being the highest) is mapped against, and
  30129. * repositions, the vertices of the mesh.
  30130. *
  30131. * `displacementMap` represents non-color data. Any texture assigned must have
  30132. * `texture.colorSpace = NoColorSpace` (default).
  30133. *
  30134. * @type {?Texture}
  30135. * @default null
  30136. */
  30137. this.displacementMap = null;
  30138. /**
  30139. * How much the displacement map affects the mesh (where black is no
  30140. * displacement, and white is maximum displacement). Without a displacement
  30141. * map set, this value is not applied.
  30142. *
  30143. * @type {number}
  30144. * @default 0
  30145. */
  30146. this.displacementScale = 1;
  30147. /**
  30148. * The offset of the displacement map's values on the mesh's vertices.
  30149. * The bias is added to the scaled sample of the displacement map.
  30150. * Without a displacement map set, this value is not applied.
  30151. *
  30152. * @type {number}
  30153. * @default 0
  30154. */
  30155. this.displacementBias = 0;
  30156. this.setValues( parameters );
  30157. }
  30158. copy( source ) {
  30159. super.copy( source );
  30160. this.map = source.map;
  30161. this.alphaMap = source.alphaMap;
  30162. this.displacementMap = source.displacementMap;
  30163. this.displacementScale = source.displacementScale;
  30164. this.displacementBias = source.displacementBias;
  30165. return this;
  30166. }
  30167. }
  30168. /**
  30169. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30170. * material color and shading.
  30171. *
  30172. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30173. * baked lighting. It will cast a shadow onto an object that receives shadows
  30174. * (and shadow clipping works), but it will not self-shadow or receive
  30175. * shadows.
  30176. *
  30177. * @augments Material
  30178. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30179. */
  30180. class MeshMatcapMaterial extends Material {
  30181. /**
  30182. * Constructs a new mesh matcap material.
  30183. *
  30184. * @param {Object} [parameters] - An object with one or more properties
  30185. * defining the material's appearance. Any property of the material
  30186. * (including any property from inherited materials) can be passed
  30187. * in here. Color values can be passed any type of value accepted
  30188. * by {@link Color#set}.
  30189. */
  30190. constructor( parameters ) {
  30191. super();
  30192. /**
  30193. * This flag can be used for type testing.
  30194. *
  30195. * @type {boolean}
  30196. * @readonly
  30197. * @default true
  30198. */
  30199. this.isMeshMatcapMaterial = true;
  30200. this.defines = { 'MATCAP': '' };
  30201. this.type = 'MeshMatcapMaterial';
  30202. /**
  30203. * Color of the material.
  30204. *
  30205. * @type {Color}
  30206. * @default (1,1,1)
  30207. */
  30208. this.color = new Color( 0xffffff ); // diffuse
  30209. /**
  30210. * The matcap map.
  30211. *
  30212. * `matcap` represents luminance data, and the texture must be assigned
  30213. * a {@link Texture#colorSpace}. HDR `matcap` textures (e.g. `.exr`)
  30214. * typically set `texture.colorSpace = LinearSRGBColorSpace`, while LDR
  30215. * `matcap` textures (e.g. `.png`, `.jpg`, `.webp`) typically set
  30216. * `texture.colorSpace = SRGBColorSpace`.
  30217. *
  30218. * @type {?Texture}
  30219. * @default null
  30220. */
  30221. this.matcap = null;
  30222. /**
  30223. * The color map. May optionally include an alpha channel, typically combined
  30224. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30225. * color is modulated by the diffuse `color`.
  30226. *
  30227. * `map` represents color data, and the texture must be assigned a
  30228. * {@link Texture#colorSpace}. Most `map` textures set
  30229. * `texture.colorSpace = SRGBColorSpace`.
  30230. *
  30231. * @type {?Texture}
  30232. * @default null
  30233. */
  30234. this.map = null;
  30235. /**
  30236. * The texture to create a bump map. The black and white values map to the
  30237. * perceived depth in relation to the lights. Bump doesn't actually affect
  30238. * the geometry of the object, only the lighting. If a normal map is defined
  30239. * this will be ignored.
  30240. *
  30241. * `bumpMap` represents non-color data. Any texture assigned must have
  30242. * `texture.colorSpace = NoColorSpace` (default).
  30243. *
  30244. * @type {?Texture}
  30245. * @default null
  30246. */
  30247. this.bumpMap = null;
  30248. /**
  30249. * How much the bump map affects the material. Typical range is `[0,1]`.
  30250. *
  30251. * @type {number}
  30252. * @default 1
  30253. */
  30254. this.bumpScale = 1;
  30255. /**
  30256. * The texture to create a normal map. The RGB values affect the surface
  30257. * normal for each pixel fragment and change the way the color is lit. Normal
  30258. * maps do not change the actual shape of the surface, only the lighting. In
  30259. * case the material has a normal map authored using the left handed
  30260. * convention, the `y` component of `normalScale` should be negated to compensate
  30261. * for the different handedness.
  30262. *
  30263. * `normalMap` represents non-color data. Any texture assigned must have
  30264. * `texture.colorSpace = NoColorSpace` (default).
  30265. *
  30266. * @type {?Texture}
  30267. * @default null
  30268. */
  30269. this.normalMap = null;
  30270. /**
  30271. * The type of normal map.
  30272. *
  30273. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30274. * @default TangentSpaceNormalMap
  30275. */
  30276. this.normalMapType = TangentSpaceNormalMap;
  30277. /**
  30278. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30279. *
  30280. * @type {Vector2}
  30281. * @default (1,1)
  30282. */
  30283. this.normalScale = new Vector2( 1, 1 );
  30284. /**
  30285. * The displacement map affects the position of the mesh's vertices. Unlike
  30286. * other maps which only affect the light and shade of the material the
  30287. * displaced vertices can cast shadows, block other objects, and otherwise
  30288. * act as real geometry. The displacement texture is an image where the value
  30289. * of each pixel (white being the highest) is mapped against, and
  30290. * repositions, the vertices of the mesh. For best results, pair a
  30291. * displacement map with a matching normal map, since the renderer can
  30292. * not recompute surface normals from the displaced vertices.
  30293. *
  30294. * `displacementMap` represents non-color data. Any texture assigned must have
  30295. * `texture.colorSpace = NoColorSpace` (default).
  30296. *
  30297. * @type {?Texture}
  30298. * @default null
  30299. */
  30300. this.displacementMap = null;
  30301. /**
  30302. * How much the displacement map affects the mesh (where black is no
  30303. * displacement, and white is maximum displacement). Without a displacement
  30304. * map set, this value is not applied.
  30305. *
  30306. * @type {number}
  30307. * @default 0
  30308. */
  30309. this.displacementScale = 1;
  30310. /**
  30311. * The offset of the displacement map's values on the mesh's vertices.
  30312. * The bias is added to the scaled sample of the displacement map.
  30313. * Without a displacement map set, this value is not applied.
  30314. *
  30315. * @type {number}
  30316. * @default 0
  30317. */
  30318. this.displacementBias = 0;
  30319. /**
  30320. * The alpha map is a grayscale texture that controls the opacity across the
  30321. * surface (black: fully transparent; white: fully opaque).
  30322. *
  30323. * Only the color of the texture is used, ignoring the alpha channel if one
  30324. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30325. * when sampling this texture due to the extra bit of precision provided for
  30326. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30327. * luminance/alpha textures will also still work as expected.
  30328. *
  30329. * `alphaMap` represents non-color data. Any texture assigned must have
  30330. * `texture.colorSpace = NoColorSpace` (default).
  30331. *
  30332. * @type {?Texture}
  30333. * @default null
  30334. */
  30335. this.alphaMap = null;
  30336. /**
  30337. * Renders the geometry as a wireframe.
  30338. *
  30339. * @type {boolean}
  30340. * @default false
  30341. */
  30342. this.wireframe = false;
  30343. /**
  30344. * Controls the thickness of the wireframe.
  30345. *
  30346. * Can only be used with {@link SVGRenderer}.
  30347. *
  30348. * @type {number}
  30349. * @default 1
  30350. */
  30351. this.wireframeLinewidth = 1;
  30352. /**
  30353. * Whether the material is rendered with flat shading or not.
  30354. *
  30355. * @type {boolean}
  30356. * @default false
  30357. */
  30358. this.flatShading = false;
  30359. /**
  30360. * Whether the material is affected by fog or not.
  30361. *
  30362. * @type {boolean}
  30363. * @default true
  30364. */
  30365. this.fog = true;
  30366. this.setValues( parameters );
  30367. }
  30368. copy( source ) {
  30369. super.copy( source );
  30370. this.defines = { 'MATCAP': '' };
  30371. this.color.copy( source.color );
  30372. this.matcap = source.matcap;
  30373. this.map = source.map;
  30374. this.bumpMap = source.bumpMap;
  30375. this.bumpScale = source.bumpScale;
  30376. this.normalMap = source.normalMap;
  30377. this.normalMapType = source.normalMapType;
  30378. this.normalScale.copy( source.normalScale );
  30379. this.displacementMap = source.displacementMap;
  30380. this.displacementScale = source.displacementScale;
  30381. this.displacementBias = source.displacementBias;
  30382. this.alphaMap = source.alphaMap;
  30383. this.wireframe = source.wireframe;
  30384. this.wireframeLinewidth = source.wireframeLinewidth;
  30385. this.flatShading = source.flatShading;
  30386. this.fog = source.fog;
  30387. return this;
  30388. }
  30389. }
  30390. /**
  30391. * A material for rendering line primitives.
  30392. *
  30393. * Materials define the appearance of renderable 3D objects.
  30394. *
  30395. * ```js
  30396. * const material = new THREE.LineDashedMaterial( {
  30397. * color: 0xffffff,
  30398. * scale: 1,
  30399. * dashSize: 3,
  30400. * gapSize: 1,
  30401. * } );
  30402. * ```
  30403. *
  30404. * @augments LineBasicMaterial
  30405. */
  30406. class LineDashedMaterial extends LineBasicMaterial {
  30407. /**
  30408. * Constructs a new line dashed material.
  30409. *
  30410. * @param {Object} [parameters] - An object with one or more properties
  30411. * defining the material's appearance. Any property of the material
  30412. * (including any property from inherited materials) can be passed
  30413. * in here. Color values can be passed any type of value accepted
  30414. * by {@link Color#set}.
  30415. */
  30416. constructor( parameters ) {
  30417. super();
  30418. /**
  30419. * This flag can be used for type testing.
  30420. *
  30421. * @type {boolean}
  30422. * @readonly
  30423. * @default true
  30424. */
  30425. this.isLineDashedMaterial = true;
  30426. this.type = 'LineDashedMaterial';
  30427. /**
  30428. * The scale of the dashed part of a line.
  30429. *
  30430. * @type {number}
  30431. * @default 1
  30432. */
  30433. this.scale = 1;
  30434. /**
  30435. * The size of the dash. This is both the gap with the stroke.
  30436. *
  30437. * @type {number}
  30438. * @default 3
  30439. */
  30440. this.dashSize = 3;
  30441. /**
  30442. * The size of the gap.
  30443. *
  30444. * @type {number}
  30445. * @default 1
  30446. */
  30447. this.gapSize = 1;
  30448. this.setValues( parameters );
  30449. }
  30450. copy( source ) {
  30451. super.copy( source );
  30452. this.scale = source.scale;
  30453. this.dashSize = source.dashSize;
  30454. this.gapSize = source.gapSize;
  30455. return this;
  30456. }
  30457. }
  30458. /**
  30459. * Converts an array to a specific type.
  30460. *
  30461. * @param {TypedArray|Array} array - The array to convert.
  30462. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30463. * @return {TypedArray} The converted array.
  30464. */
  30465. function convertArray( array, type ) {
  30466. if ( ! array || array.constructor === type ) return array;
  30467. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30468. return new type( array ); // create typed array
  30469. }
  30470. return Array.prototype.slice.call( array ); // create Array
  30471. }
  30472. /**
  30473. * Returns an array by which times and values can be sorted.
  30474. *
  30475. * @param {Array<number>} times - The keyframe time values.
  30476. * @return {Array<number>} The array.
  30477. */
  30478. function getKeyframeOrder( times ) {
  30479. function compareTime( i, j ) {
  30480. return times[ i ] - times[ j ];
  30481. }
  30482. const n = times.length;
  30483. const result = new Array( n );
  30484. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30485. result.sort( compareTime );
  30486. return result;
  30487. }
  30488. /**
  30489. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30490. *
  30491. * @param {Array<number>} values - The values to sort.
  30492. * @param {number} stride - The stride.
  30493. * @param {Array<number>} order - The sort order.
  30494. * @return {Array<number>} The sorted values.
  30495. */
  30496. function sortedArray( values, stride, order ) {
  30497. const nValues = values.length;
  30498. const result = new values.constructor( nValues );
  30499. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30500. const srcOffset = order[ i ] * stride;
  30501. for ( let j = 0; j !== stride; ++ j ) {
  30502. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30503. }
  30504. }
  30505. return result;
  30506. }
  30507. /**
  30508. * Used for parsing AOS keyframe formats.
  30509. *
  30510. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30511. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30512. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30513. * @param {string} valuePropertyName - The name of the property to use.
  30514. */
  30515. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30516. let i = 1, key = jsonKeys[ 0 ];
  30517. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30518. key = jsonKeys[ i ++ ];
  30519. }
  30520. if ( key === undefined ) return; // no data
  30521. let value = key[ valuePropertyName ];
  30522. if ( value === undefined ) return; // no data
  30523. if ( Array.isArray( value ) ) {
  30524. do {
  30525. value = key[ valuePropertyName ];
  30526. if ( value !== undefined ) {
  30527. times.push( key.time );
  30528. values.push( ...value ); // push all elements
  30529. }
  30530. key = jsonKeys[ i ++ ];
  30531. } while ( key !== undefined );
  30532. } else if ( value.toArray !== undefined ) {
  30533. // ...assume THREE.Math-ish
  30534. do {
  30535. value = key[ valuePropertyName ];
  30536. if ( value !== undefined ) {
  30537. times.push( key.time );
  30538. value.toArray( values, values.length );
  30539. }
  30540. key = jsonKeys[ i ++ ];
  30541. } while ( key !== undefined );
  30542. } else {
  30543. // otherwise push as-is
  30544. do {
  30545. value = key[ valuePropertyName ];
  30546. if ( value !== undefined ) {
  30547. times.push( key.time );
  30548. values.push( value );
  30549. }
  30550. key = jsonKeys[ i ++ ];
  30551. } while ( key !== undefined );
  30552. }
  30553. }
  30554. /**
  30555. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30556. *
  30557. * @param {AnimationClip} sourceClip - The values to sort.
  30558. * @param {string} name - The name of the clip.
  30559. * @param {number} startFrame - The start frame.
  30560. * @param {number} endFrame - The end frame.
  30561. * @param {number} [fps=30] - The FPS.
  30562. * @return {AnimationClip} The new sub clip.
  30563. */
  30564. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30565. const clip = sourceClip.clone();
  30566. clip.name = name;
  30567. const tracks = [];
  30568. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30569. const track = clip.tracks[ i ];
  30570. const valueSize = track.getValueSize();
  30571. const times = [];
  30572. const values = [];
  30573. for ( let j = 0; j < track.times.length; ++ j ) {
  30574. const frame = track.times[ j ] * fps;
  30575. if ( frame < startFrame || frame >= endFrame ) continue;
  30576. times.push( track.times[ j ] );
  30577. for ( let k = 0; k < valueSize; ++ k ) {
  30578. values.push( track.values[ j * valueSize + k ] );
  30579. }
  30580. }
  30581. if ( times.length === 0 ) continue;
  30582. track.times = convertArray( times, track.times.constructor );
  30583. track.values = convertArray( values, track.values.constructor );
  30584. tracks.push( track );
  30585. }
  30586. clip.tracks = tracks;
  30587. // find minimum .times value across all tracks in the trimmed clip
  30588. let minStartTime = Infinity;
  30589. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30590. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30591. minStartTime = clip.tracks[ i ].times[ 0 ];
  30592. }
  30593. }
  30594. // shift all tracks such that clip begins at t=0
  30595. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30596. clip.tracks[ i ].shift( -1 * minStartTime );
  30597. }
  30598. clip.resetDuration();
  30599. return clip;
  30600. }
  30601. /**
  30602. * Converts the keyframes of the given animation clip to an additive format.
  30603. *
  30604. * @param {AnimationClip} targetClip - The clip to make additive.
  30605. * @param {number} [referenceFrame=0] - The reference frame.
  30606. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30607. * @param {number} [fps=30] - The FPS.
  30608. * @return {AnimationClip} The updated clip which is now additive.
  30609. */
  30610. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30611. if ( fps <= 0 ) fps = 30;
  30612. const numTracks = referenceClip.tracks.length;
  30613. const referenceTime = referenceFrame / fps;
  30614. // Make each track's values relative to the values at the reference frame
  30615. for ( let i = 0; i < numTracks; ++ i ) {
  30616. const referenceTrack = referenceClip.tracks[ i ];
  30617. const referenceTrackType = referenceTrack.ValueTypeName;
  30618. // Skip this track if it's non-numeric
  30619. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30620. // Find the track in the target clip whose name and type matches the reference track
  30621. const targetTrack = targetClip.tracks.find( function ( track ) {
  30622. return track.name === referenceTrack.name
  30623. && track.ValueTypeName === referenceTrackType;
  30624. } );
  30625. if ( targetTrack === undefined ) continue;
  30626. let referenceOffset = 0;
  30627. const referenceValueSize = referenceTrack.getValueSize();
  30628. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30629. referenceOffset = referenceValueSize / 3;
  30630. }
  30631. let targetOffset = 0;
  30632. const targetValueSize = targetTrack.getValueSize();
  30633. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30634. targetOffset = targetValueSize / 3;
  30635. }
  30636. const lastIndex = referenceTrack.times.length - 1;
  30637. let referenceValue;
  30638. // Find the value to subtract out of the track
  30639. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30640. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30641. const startIndex = referenceOffset;
  30642. const endIndex = referenceValueSize - referenceOffset;
  30643. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30644. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30645. // Reference frame is after the last keyframe, so just use the last keyframe
  30646. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30647. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30648. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30649. } else {
  30650. // Interpolate to the reference value
  30651. const interpolant = referenceTrack.createInterpolant();
  30652. const startIndex = referenceOffset;
  30653. const endIndex = referenceValueSize - referenceOffset;
  30654. interpolant.evaluate( referenceTime );
  30655. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30656. }
  30657. // Conjugate the quaternion
  30658. if ( referenceTrackType === 'quaternion' ) {
  30659. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30660. referenceQuat.toArray( referenceValue );
  30661. }
  30662. // Subtract the reference value from all of the track values
  30663. const numTimes = targetTrack.times.length;
  30664. for ( let j = 0; j < numTimes; ++ j ) {
  30665. const valueStart = j * targetValueSize + targetOffset;
  30666. if ( referenceTrackType === 'quaternion' ) {
  30667. // Multiply the conjugate for quaternion track types
  30668. Quaternion.multiplyQuaternionsFlat(
  30669. targetTrack.values,
  30670. valueStart,
  30671. referenceValue,
  30672. 0,
  30673. targetTrack.values,
  30674. valueStart
  30675. );
  30676. } else {
  30677. const valueEnd = targetValueSize - targetOffset * 2;
  30678. // Subtract each value for all other numeric track types
  30679. for ( let k = 0; k < valueEnd; ++ k ) {
  30680. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30681. }
  30682. }
  30683. }
  30684. }
  30685. targetClip.blendMode = AdditiveAnimationBlendMode;
  30686. return targetClip;
  30687. }
  30688. /**
  30689. * A class with various methods to assist with animations.
  30690. *
  30691. * @hideconstructor
  30692. */
  30693. class AnimationUtils {
  30694. /**
  30695. * Converts an array to a specific type
  30696. *
  30697. * @static
  30698. * @param {TypedArray|Array} array - The array to convert.
  30699. * @param {TypedArray.constructor} type - The constructor of a type array.
  30700. * @return {TypedArray} The converted array
  30701. */
  30702. static convertArray( array, type ) {
  30703. return convertArray( array, type );
  30704. }
  30705. /**
  30706. * Returns `true` if the given object is a typed array.
  30707. *
  30708. * @static
  30709. * @param {any} object - The object to check.
  30710. * @return {boolean} Whether the given object is a typed array.
  30711. */
  30712. static isTypedArray( object ) {
  30713. return isTypedArray( object );
  30714. }
  30715. /**
  30716. * Returns an array by which times and values can be sorted.
  30717. *
  30718. * @static
  30719. * @param {Array<number>} times - The keyframe time values.
  30720. * @return {Array<number>} The array.
  30721. */
  30722. static getKeyframeOrder( times ) {
  30723. return getKeyframeOrder( times );
  30724. }
  30725. /**
  30726. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30727. *
  30728. * @static
  30729. * @param {Array<number>} values - The values to sort.
  30730. * @param {number} stride - The stride.
  30731. * @param {Array<number>} order - The sort order.
  30732. * @return {Array<number>} The sorted values.
  30733. */
  30734. static sortedArray( values, stride, order ) {
  30735. return sortedArray( values, stride, order );
  30736. }
  30737. /**
  30738. * Used for parsing AOS keyframe formats.
  30739. *
  30740. * @static
  30741. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30742. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30743. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30744. * @param {string} valuePropertyName - The name of the property to use.
  30745. */
  30746. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30747. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30748. }
  30749. /**
  30750. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30751. *
  30752. * @static
  30753. * @param {AnimationClip} sourceClip - The values to sort.
  30754. * @param {string} name - The name of the clip.
  30755. * @param {number} startFrame - The start frame.
  30756. * @param {number} endFrame - The end frame.
  30757. * @param {number} [fps=30] - The FPS.
  30758. * @return {AnimationClip} The new sub clip.
  30759. */
  30760. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30761. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30762. }
  30763. /**
  30764. * Converts the keyframes of the given animation clip to an additive format.
  30765. *
  30766. * @static
  30767. * @param {AnimationClip} targetClip - The clip to make additive.
  30768. * @param {number} [referenceFrame=0] - The reference frame.
  30769. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30770. * @param {number} [fps=30] - The FPS.
  30771. * @return {AnimationClip} The updated clip which is now additive.
  30772. */
  30773. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30774. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30775. }
  30776. }
  30777. /**
  30778. * Abstract base class of interpolants over parametric samples.
  30779. *
  30780. * The parameter domain is one dimensional, typically the time or a path
  30781. * along a curve defined by the data.
  30782. *
  30783. * The sample values can have any dimensionality and derived classes may
  30784. * apply special interpretations to the data.
  30785. *
  30786. * This class provides the interval seek in a Template Method, deferring
  30787. * the actual interpolation to derived classes.
  30788. *
  30789. * Time complexity is O(1) for linear access crossing at most two points
  30790. * and O(log N) for random access, where N is the number of positions.
  30791. *
  30792. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30793. *
  30794. * @abstract
  30795. */
  30796. class Interpolant {
  30797. /**
  30798. * Constructs a new interpolant.
  30799. *
  30800. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30801. * @param {TypedArray} sampleValues - The sample values.
  30802. * @param {number} sampleSize - The sample size
  30803. * @param {TypedArray} [resultBuffer] - The result buffer.
  30804. */
  30805. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30806. /**
  30807. * The parameter positions.
  30808. *
  30809. * @type {TypedArray}
  30810. */
  30811. this.parameterPositions = parameterPositions;
  30812. /**
  30813. * A cache index.
  30814. *
  30815. * @private
  30816. * @type {number}
  30817. * @default 0
  30818. */
  30819. this._cachedIndex = 0;
  30820. /**
  30821. * The result buffer.
  30822. *
  30823. * @type {TypedArray}
  30824. */
  30825. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30826. /**
  30827. * The sample values.
  30828. *
  30829. * @type {TypedArray}
  30830. */
  30831. this.sampleValues = sampleValues;
  30832. /**
  30833. * The value size.
  30834. *
  30835. * @type {TypedArray}
  30836. */
  30837. this.valueSize = sampleSize;
  30838. /**
  30839. * The interpolation settings.
  30840. *
  30841. * @type {?Object}
  30842. * @default null
  30843. */
  30844. this.settings = null;
  30845. /**
  30846. * The default settings object.
  30847. *
  30848. * @type {Object}
  30849. */
  30850. this.DefaultSettings_ = {};
  30851. }
  30852. /**
  30853. * Evaluate the interpolant at position `t`.
  30854. *
  30855. * @param {number} t - The interpolation factor.
  30856. * @return {TypedArray} The result buffer.
  30857. */
  30858. evaluate( t ) {
  30859. const pp = this.parameterPositions;
  30860. let i1 = this._cachedIndex,
  30861. t1 = pp[ i1 ],
  30862. t0 = pp[ i1 - 1 ];
  30863. validate_interval: {
  30864. seek: {
  30865. let right;
  30866. linear_scan: {
  30867. //- See http://jsperf.com/comparison-to-undefined/3
  30868. //- slower code:
  30869. //-
  30870. //- if ( t >= t1 || t1 === undefined ) {
  30871. forward_scan: if ( ! ( t < t1 ) ) {
  30872. for ( let giveUpAt = i1 + 2; ; ) {
  30873. if ( t1 === undefined ) {
  30874. if ( t < t0 ) break forward_scan;
  30875. // after end
  30876. i1 = pp.length;
  30877. this._cachedIndex = i1;
  30878. return this.copySampleValue_( i1 - 1 );
  30879. }
  30880. if ( i1 === giveUpAt ) break; // this loop
  30881. t0 = t1;
  30882. t1 = pp[ ++ i1 ];
  30883. if ( t < t1 ) {
  30884. // we have arrived at the sought interval
  30885. break seek;
  30886. }
  30887. }
  30888. // prepare binary search on the right side of the index
  30889. right = pp.length;
  30890. break linear_scan;
  30891. }
  30892. //- slower code:
  30893. //- if ( t < t0 || t0 === undefined ) {
  30894. if ( ! ( t >= t0 ) ) {
  30895. // looping?
  30896. const t1global = pp[ 1 ];
  30897. if ( t < t1global ) {
  30898. i1 = 2; // + 1, using the scan for the details
  30899. t0 = t1global;
  30900. }
  30901. // linear reverse scan
  30902. for ( let giveUpAt = i1 - 2; ; ) {
  30903. if ( t0 === undefined ) {
  30904. // before start
  30905. this._cachedIndex = 0;
  30906. return this.copySampleValue_( 0 );
  30907. }
  30908. if ( i1 === giveUpAt ) break; // this loop
  30909. t1 = t0;
  30910. t0 = pp[ -- i1 - 1 ];
  30911. if ( t >= t0 ) {
  30912. // we have arrived at the sought interval
  30913. break seek;
  30914. }
  30915. }
  30916. // prepare binary search on the left side of the index
  30917. right = i1;
  30918. i1 = 0;
  30919. break linear_scan;
  30920. }
  30921. // the interval is valid
  30922. break validate_interval;
  30923. } // linear scan
  30924. // binary search
  30925. while ( i1 < right ) {
  30926. const mid = ( i1 + right ) >>> 1;
  30927. if ( t < pp[ mid ] ) {
  30928. right = mid;
  30929. } else {
  30930. i1 = mid + 1;
  30931. }
  30932. }
  30933. t1 = pp[ i1 ];
  30934. t0 = pp[ i1 - 1 ];
  30935. // check boundary cases, again
  30936. if ( t0 === undefined ) {
  30937. this._cachedIndex = 0;
  30938. return this.copySampleValue_( 0 );
  30939. }
  30940. if ( t1 === undefined ) {
  30941. i1 = pp.length;
  30942. this._cachedIndex = i1;
  30943. return this.copySampleValue_( i1 - 1 );
  30944. }
  30945. } // seek
  30946. this._cachedIndex = i1;
  30947. this.intervalChanged_( i1, t0, t1 );
  30948. } // validate_interval
  30949. return this.interpolate_( i1, t0, t, t1 );
  30950. }
  30951. /**
  30952. * Returns the interpolation settings.
  30953. *
  30954. * @return {Object} The interpolation settings.
  30955. */
  30956. getSettings_() {
  30957. return this.settings || this.DefaultSettings_;
  30958. }
  30959. /**
  30960. * Copies a sample value to the result buffer.
  30961. *
  30962. * @param {number} index - An index into the sample value buffer.
  30963. * @return {TypedArray} The result buffer.
  30964. */
  30965. copySampleValue_( index ) {
  30966. // copies a sample value to the result buffer
  30967. const result = this.resultBuffer,
  30968. values = this.sampleValues,
  30969. stride = this.valueSize,
  30970. offset = index * stride;
  30971. for ( let i = 0; i !== stride; ++ i ) {
  30972. result[ i ] = values[ offset + i ];
  30973. }
  30974. return result;
  30975. }
  30976. /**
  30977. * Copies a sample value to the result buffer.
  30978. *
  30979. * @abstract
  30980. * @param {number} i1 - An index into the sample value buffer.
  30981. * @param {number} t0 - The previous interpolation factor.
  30982. * @param {number} t - The current interpolation factor.
  30983. * @param {number} t1 - The next interpolation factor.
  30984. * @return {TypedArray} The result buffer.
  30985. */
  30986. interpolate_( /* i1, t0, t, t1 */ ) {
  30987. throw new Error( 'THREE.Interpolant: Call to abstract method.' );
  30988. // implementations shall return this.resultBuffer
  30989. }
  30990. /**
  30991. * Optional method that is executed when the interval has changed.
  30992. *
  30993. * @param {number} i1 - An index into the sample value buffer.
  30994. * @param {number} t0 - The previous interpolation factor.
  30995. * @param {number} t - The current interpolation factor.
  30996. */
  30997. intervalChanged_( /* i1, t0, t1 */ ) {
  30998. // empty
  30999. }
  31000. }
  31001. /**
  31002. * Fast and simple cubic spline interpolant.
  31003. *
  31004. * It was derived from a Hermitian construction setting the first derivative
  31005. * at each sample position to the linear slope between neighboring positions
  31006. * over their parameter interval.
  31007. *
  31008. * @augments Interpolant
  31009. */
  31010. class CubicInterpolant extends Interpolant {
  31011. /**
  31012. * Constructs a new cubic interpolant.
  31013. *
  31014. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31015. * @param {TypedArray} sampleValues - The sample values.
  31016. * @param {number} sampleSize - The sample size
  31017. * @param {TypedArray} [resultBuffer] - The result buffer.
  31018. */
  31019. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31020. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31021. this._weightPrev = -0;
  31022. this._offsetPrev = -0;
  31023. this._weightNext = -0;
  31024. this._offsetNext = -0;
  31025. this.DefaultSettings_ = {
  31026. endingStart: ZeroCurvatureEnding,
  31027. endingEnd: ZeroCurvatureEnding
  31028. };
  31029. }
  31030. intervalChanged_( i1, t0, t1 ) {
  31031. const pp = this.parameterPositions;
  31032. let iPrev = i1 - 2,
  31033. iNext = i1 + 1,
  31034. tPrev = pp[ iPrev ],
  31035. tNext = pp[ iNext ];
  31036. if ( tPrev === undefined ) {
  31037. switch ( this.getSettings_().endingStart ) {
  31038. case ZeroSlopeEnding:
  31039. // f'(t0) = 0
  31040. iPrev = i1;
  31041. tPrev = 2 * t0 - t1;
  31042. break;
  31043. case WrapAroundEnding:
  31044. // use the other end of the curve
  31045. iPrev = pp.length - 2;
  31046. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31047. break;
  31048. default: // ZeroCurvatureEnding
  31049. // f''(t0) = 0 a.k.a. Natural Spline
  31050. iPrev = i1;
  31051. tPrev = t1;
  31052. }
  31053. }
  31054. if ( tNext === undefined ) {
  31055. switch ( this.getSettings_().endingEnd ) {
  31056. case ZeroSlopeEnding:
  31057. // f'(tN) = 0
  31058. iNext = i1;
  31059. tNext = 2 * t1 - t0;
  31060. break;
  31061. case WrapAroundEnding:
  31062. // use the other end of the curve
  31063. iNext = 1;
  31064. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31065. break;
  31066. default: // ZeroCurvatureEnding
  31067. // f''(tN) = 0, a.k.a. Natural Spline
  31068. iNext = i1 - 1;
  31069. tNext = t0;
  31070. }
  31071. }
  31072. const halfDt = ( t1 - t0 ) * 0.5,
  31073. stride = this.valueSize;
  31074. this._weightPrev = halfDt / ( t0 - tPrev );
  31075. this._weightNext = halfDt / ( tNext - t1 );
  31076. this._offsetPrev = iPrev * stride;
  31077. this._offsetNext = iNext * stride;
  31078. }
  31079. interpolate_( i1, t0, t, t1 ) {
  31080. const result = this.resultBuffer,
  31081. values = this.sampleValues,
  31082. stride = this.valueSize,
  31083. o1 = i1 * stride, o0 = o1 - stride,
  31084. oP = this._offsetPrev, oN = this._offsetNext,
  31085. wP = this._weightPrev, wN = this._weightNext,
  31086. p = ( t - t0 ) / ( t1 - t0 ),
  31087. pp = p * p,
  31088. ppp = pp * p;
  31089. // evaluate polynomials
  31090. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31091. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31092. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31093. const sN = wN * ppp - wN * pp;
  31094. // combine data linearly
  31095. for ( let i = 0; i !== stride; ++ i ) {
  31096. result[ i ] =
  31097. sP * values[ oP + i ] +
  31098. s0 * values[ o0 + i ] +
  31099. s1 * values[ o1 + i ] +
  31100. sN * values[ oN + i ];
  31101. }
  31102. return result;
  31103. }
  31104. }
  31105. /**
  31106. * A basic linear interpolant.
  31107. *
  31108. * @augments Interpolant
  31109. */
  31110. class LinearInterpolant extends Interpolant {
  31111. /**
  31112. * Constructs a new linear interpolant.
  31113. *
  31114. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31115. * @param {TypedArray} sampleValues - The sample values.
  31116. * @param {number} sampleSize - The sample size
  31117. * @param {TypedArray} [resultBuffer] - The result buffer.
  31118. */
  31119. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31120. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31121. }
  31122. interpolate_( i1, t0, t, t1 ) {
  31123. const result = this.resultBuffer,
  31124. values = this.sampleValues,
  31125. stride = this.valueSize,
  31126. offset1 = i1 * stride,
  31127. offset0 = offset1 - stride,
  31128. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31129. weight0 = 1 - weight1;
  31130. for ( let i = 0; i !== stride; ++ i ) {
  31131. result[ i ] =
  31132. values[ offset0 + i ] * weight0 +
  31133. values[ offset1 + i ] * weight1;
  31134. }
  31135. return result;
  31136. }
  31137. }
  31138. /**
  31139. * Interpolant that evaluates to the sample value at the position preceding
  31140. * the parameter.
  31141. *
  31142. * @augments Interpolant
  31143. */
  31144. class DiscreteInterpolant extends Interpolant {
  31145. /**
  31146. * Constructs a new discrete interpolant.
  31147. *
  31148. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31149. * @param {TypedArray} sampleValues - The sample values.
  31150. * @param {number} sampleSize - The sample size
  31151. * @param {TypedArray} [resultBuffer] - The result buffer.
  31152. */
  31153. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31154. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31155. }
  31156. interpolate_( i1 /*, t0, t, t1 */ ) {
  31157. return this.copySampleValue_( i1 - 1 );
  31158. }
  31159. }
  31160. /**
  31161. * A Bezier interpolant using cubic Bezier curves with 2D control points.
  31162. *
  31163. * This interpolant supports the COLLADA/Maya style of Bezier animation where
  31164. * each keyframe has explicit in/out tangent control points specified as
  31165. * 2D coordinates (time, value).
  31166. *
  31167. * Tangent data is read from `inTangents` and `outTangents` on the interpolant
  31168. * (populated by `KeyframeTrack.InterpolantFactoryMethodBezier`).
  31169. *
  31170. * For a track with N keyframes and stride S:
  31171. * - Each tangent array has N * S * 2 values
  31172. * - Layout: [k0_c0_time, k0_c0_value, k0_c1_time, k0_c1_value, ..., k0_cS_time, k0_cS_value,
  31173. * k1_c0_time, k1_c0_value, ...]
  31174. *
  31175. * @augments Interpolant
  31176. */
  31177. class BezierInterpolant extends Interpolant {
  31178. interpolate_( i1, t0, t, t1 ) {
  31179. const result = this.resultBuffer;
  31180. const values = this.sampleValues;
  31181. const stride = this.valueSize;
  31182. const offset1 = i1 * stride;
  31183. const offset0 = offset1 - stride;
  31184. const inTangents = this.inTangents;
  31185. const outTangents = this.outTangents;
  31186. // If no tangent data, fall back to linear interpolation
  31187. if ( ! inTangents || ! outTangents ) {
  31188. const weight1 = ( t - t0 ) / ( t1 - t0 );
  31189. const weight0 = 1 - weight1;
  31190. for ( let i = 0; i !== stride; ++ i ) {
  31191. result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1;
  31192. }
  31193. return result;
  31194. }
  31195. const tangentStride = stride * 2;
  31196. const i0 = i1 - 1;
  31197. for ( let i = 0; i !== stride; ++ i ) {
  31198. const v0 = values[ offset0 + i ];
  31199. const v1 = values[ offset1 + i ];
  31200. // outTangent of previous keyframe (C0)
  31201. const outTangentOffset = i0 * tangentStride + i * 2;
  31202. const c0x = outTangents[ outTangentOffset ];
  31203. const c0y = outTangents[ outTangentOffset + 1 ];
  31204. // inTangent of current keyframe (C1)
  31205. const inTangentOffset = i1 * tangentStride + i * 2;
  31206. const c1x = inTangents[ inTangentOffset ];
  31207. const c1y = inTangents[ inTangentOffset + 1 ];
  31208. // Solve for Bezier parameter s where Bx(s) = t using Newton-Raphson
  31209. let s = ( t - t0 ) / ( t1 - t0 );
  31210. let s2, s3, oneMinusS, oneMinusS2, oneMinusS3;
  31211. for ( let iter = 0; iter < 8; iter ++ ) {
  31212. s2 = s * s;
  31213. s3 = s2 * s;
  31214. oneMinusS = 1 - s;
  31215. oneMinusS2 = oneMinusS * oneMinusS;
  31216. oneMinusS3 = oneMinusS2 * oneMinusS;
  31217. // Bezier X(s) = (1-s)³·t0 + 3(1-s)²s·c0x + 3(1-s)s²·c1x + s³·t1
  31218. const bx = oneMinusS3 * t0 + 3 * oneMinusS2 * s * c0x + 3 * oneMinusS * s2 * c1x + s3 * t1;
  31219. const error = bx - t;
  31220. if ( Math.abs( error ) < 1e-10 ) break;
  31221. // Derivative dX/ds
  31222. const dbx = 3 * oneMinusS2 * ( c0x - t0 ) + 6 * oneMinusS * s * ( c1x - c0x ) + 3 * s2 * ( t1 - c1x );
  31223. if ( Math.abs( dbx ) < 1e-10 ) break;
  31224. s = s - error / dbx;
  31225. s = Math.max( 0, Math.min( 1, s ) );
  31226. }
  31227. // Evaluate Bezier Y(s)
  31228. result[ i ] = oneMinusS3 * v0 + 3 * oneMinusS2 * s * c0y + 3 * oneMinusS * s2 * c1y + s3 * v1;
  31229. }
  31230. return result;
  31231. }
  31232. }
  31233. /**
  31234. * Represents a timed sequence of keyframes, which are composed of lists of
  31235. * times and related values, and which are used to animate a specific property
  31236. * of an object.
  31237. */
  31238. class KeyframeTrack {
  31239. /**
  31240. * Constructs a new keyframe track.
  31241. *
  31242. * @param {string} name - The keyframe track's name.
  31243. * @param {Array<number>} times - A list of keyframe times.
  31244. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31245. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} [interpolation] - The interpolation type.
  31246. */
  31247. constructor( name, times, values, interpolation ) {
  31248. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31249. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31250. /**
  31251. * The track's name can refer to morph targets or bones or
  31252. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31253. * for the forms of strings that can be parsed for property binding.
  31254. *
  31255. * @type {string}
  31256. */
  31257. this.name = name;
  31258. /**
  31259. * The keyframe times.
  31260. *
  31261. * @type {Float32Array}
  31262. */
  31263. this.times = convertArray( times, this.TimeBufferType );
  31264. /**
  31265. * The keyframe values.
  31266. *
  31267. * @type {Float32Array}
  31268. */
  31269. this.values = convertArray( values, this.ValueBufferType );
  31270. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31271. }
  31272. /**
  31273. * Converts the keyframe track to JSON.
  31274. *
  31275. * @static
  31276. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31277. * @return {Object} The serialized keyframe track as JSON.
  31278. */
  31279. static toJSON( track ) {
  31280. const trackType = track.constructor;
  31281. let json;
  31282. // derived classes can define a static toJSON method
  31283. if ( trackType.toJSON !== this.toJSON ) {
  31284. json = trackType.toJSON( track );
  31285. } else {
  31286. // by default, we assume the data can be serialized as-is
  31287. json = {
  31288. 'name': track.name,
  31289. 'times': convertArray( track.times, Array ),
  31290. 'values': convertArray( track.values, Array )
  31291. };
  31292. const interpolation = track.getInterpolation();
  31293. if ( interpolation !== track.DefaultInterpolation ) {
  31294. json.interpolation = interpolation;
  31295. }
  31296. }
  31297. json.type = track.ValueTypeName; // mandatory
  31298. return json;
  31299. }
  31300. /**
  31301. * Factory method for creating a new discrete interpolant.
  31302. *
  31303. * @static
  31304. * @param {TypedArray} [result] - The result buffer.
  31305. * @return {DiscreteInterpolant} The new interpolant.
  31306. */
  31307. InterpolantFactoryMethodDiscrete( result ) {
  31308. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31309. }
  31310. /**
  31311. * Factory method for creating a new linear interpolant.
  31312. *
  31313. * @static
  31314. * @param {TypedArray} [result] - The result buffer.
  31315. * @return {LinearInterpolant} The new interpolant.
  31316. */
  31317. InterpolantFactoryMethodLinear( result ) {
  31318. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31319. }
  31320. /**
  31321. * Factory method for creating a new smooth interpolant.
  31322. *
  31323. * @static
  31324. * @param {TypedArray} [result] - The result buffer.
  31325. * @return {CubicInterpolant} The new interpolant.
  31326. */
  31327. InterpolantFactoryMethodSmooth( result ) {
  31328. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31329. }
  31330. /**
  31331. * Factory method for creating a new Bezier interpolant.
  31332. *
  31333. * The Bezier interpolant requires tangent data to be set via the `settings` property
  31334. * on the track before creating the interpolant. The settings should contain:
  31335. * - `inTangents`: Float32Array with [time, value] pairs per keyframe per component
  31336. * - `outTangents`: Float32Array with [time, value] pairs per keyframe per component
  31337. *
  31338. * @static
  31339. * @param {TypedArray} [result] - The result buffer.
  31340. * @return {BezierInterpolant} The new interpolant.
  31341. */
  31342. InterpolantFactoryMethodBezier( result ) {
  31343. const interpolant = new BezierInterpolant( this.times, this.values, this.getValueSize(), result );
  31344. if ( this.settings ) {
  31345. interpolant.inTangents = this.settings.inTangents;
  31346. interpolant.outTangents = this.settings.outTangents;
  31347. }
  31348. return interpolant;
  31349. }
  31350. /**
  31351. * Defines the interpolation factor method for this keyframe track.
  31352. *
  31353. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} interpolation - The interpolation type.
  31354. * @return {KeyframeTrack} A reference to this keyframe track.
  31355. */
  31356. setInterpolation( interpolation ) {
  31357. let factoryMethod;
  31358. switch ( interpolation ) {
  31359. case InterpolateDiscrete:
  31360. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31361. break;
  31362. case InterpolateLinear:
  31363. factoryMethod = this.InterpolantFactoryMethodLinear;
  31364. break;
  31365. case InterpolateSmooth:
  31366. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31367. break;
  31368. case InterpolateBezier:
  31369. factoryMethod = this.InterpolantFactoryMethodBezier;
  31370. break;
  31371. }
  31372. if ( factoryMethod === undefined ) {
  31373. const message = 'unsupported interpolation for ' +
  31374. this.ValueTypeName + ' keyframe track named ' + this.name;
  31375. if ( this.createInterpolant === undefined ) {
  31376. // fall back to default, unless the default itself is messed up
  31377. if ( interpolation !== this.DefaultInterpolation ) {
  31378. this.setInterpolation( this.DefaultInterpolation );
  31379. } else {
  31380. throw new Error( message ); // fatal, in this case
  31381. }
  31382. }
  31383. warn( 'KeyframeTrack:', message );
  31384. return this;
  31385. }
  31386. this.createInterpolant = factoryMethod;
  31387. return this;
  31388. }
  31389. /**
  31390. * Returns the current interpolation type.
  31391. *
  31392. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)} The interpolation type.
  31393. */
  31394. getInterpolation() {
  31395. switch ( this.createInterpolant ) {
  31396. case this.InterpolantFactoryMethodDiscrete:
  31397. return InterpolateDiscrete;
  31398. case this.InterpolantFactoryMethodLinear:
  31399. return InterpolateLinear;
  31400. case this.InterpolantFactoryMethodSmooth:
  31401. return InterpolateSmooth;
  31402. case this.InterpolantFactoryMethodBezier:
  31403. return InterpolateBezier;
  31404. }
  31405. }
  31406. /**
  31407. * Returns the value size.
  31408. *
  31409. * @return {number} The value size.
  31410. */
  31411. getValueSize() {
  31412. return this.values.length / this.times.length;
  31413. }
  31414. /**
  31415. * Moves all keyframes either forward or backward in time.
  31416. *
  31417. * @param {number} timeOffset - The offset to move the time values.
  31418. * @return {KeyframeTrack} A reference to this keyframe track.
  31419. */
  31420. shift( timeOffset ) {
  31421. if ( timeOffset !== 0.0 ) {
  31422. const times = this.times;
  31423. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31424. times[ i ] += timeOffset;
  31425. }
  31426. }
  31427. return this;
  31428. }
  31429. /**
  31430. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31431. *
  31432. * @param {number} timeScale - The time scale.
  31433. * @return {KeyframeTrack} A reference to this keyframe track.
  31434. */
  31435. scale( timeScale ) {
  31436. if ( timeScale !== 1.0 ) {
  31437. const times = this.times;
  31438. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31439. times[ i ] *= timeScale;
  31440. }
  31441. }
  31442. return this;
  31443. }
  31444. /**
  31445. * Removes keyframes before and after animation without changing any values within the defined time range.
  31446. *
  31447. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31448. * keys this will change their values
  31449. *
  31450. * @param {number} startTime - The start time.
  31451. * @param {number} endTime - The end time.
  31452. * @return {KeyframeTrack} A reference to this keyframe track.
  31453. */
  31454. trim( startTime, endTime ) {
  31455. const times = this.times,
  31456. nKeys = times.length;
  31457. let from = 0,
  31458. to = nKeys - 1;
  31459. while ( from !== nKeys && times[ from ] < startTime ) {
  31460. ++ from;
  31461. }
  31462. while ( to !== -1 && times[ to ] > endTime ) {
  31463. -- to;
  31464. }
  31465. ++ to; // inclusive -> exclusive bound
  31466. if ( from !== 0 || to !== nKeys ) {
  31467. // empty tracks are forbidden, so keep at least one keyframe
  31468. if ( from >= to ) {
  31469. to = Math.max( to, 1 );
  31470. from = to - 1;
  31471. }
  31472. const stride = this.getValueSize();
  31473. this.times = times.slice( from, to );
  31474. this.values = this.values.slice( from * stride, to * stride );
  31475. }
  31476. return this;
  31477. }
  31478. /**
  31479. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31480. * are valid.
  31481. *
  31482. * @return {boolean} Whether the keyframes are valid or not.
  31483. */
  31484. validate() {
  31485. let valid = true;
  31486. const valueSize = this.getValueSize();
  31487. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31488. error( 'KeyframeTrack: Invalid value size in track.', this );
  31489. valid = false;
  31490. }
  31491. const times = this.times,
  31492. values = this.values,
  31493. nKeys = times.length;
  31494. if ( nKeys === 0 ) {
  31495. error( 'KeyframeTrack: Track is empty.', this );
  31496. valid = false;
  31497. }
  31498. let prevTime = null;
  31499. for ( let i = 0; i !== nKeys; i ++ ) {
  31500. const currTime = times[ i ];
  31501. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31502. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31503. valid = false;
  31504. break;
  31505. }
  31506. if ( prevTime !== null && prevTime > currTime ) {
  31507. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31508. valid = false;
  31509. break;
  31510. }
  31511. prevTime = currTime;
  31512. }
  31513. if ( values !== undefined ) {
  31514. if ( isTypedArray( values ) ) {
  31515. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31516. const value = values[ i ];
  31517. if ( isNaN( value ) ) {
  31518. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31519. valid = false;
  31520. break;
  31521. }
  31522. }
  31523. }
  31524. }
  31525. return valid;
  31526. }
  31527. /**
  31528. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31529. * common in morph target sequences).
  31530. *
  31531. * @return {KeyframeTrack} A reference to this keyframe track.
  31532. */
  31533. optimize() {
  31534. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31535. // times or values may be shared with other tracks, so overwriting is unsafe
  31536. const times = this.times.slice(),
  31537. values = this.values.slice(),
  31538. stride = this.getValueSize(),
  31539. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31540. lastIndex = times.length - 1;
  31541. let writeIndex = 1;
  31542. for ( let i = 1; i < lastIndex; ++ i ) {
  31543. let keep = false;
  31544. const time = times[ i ];
  31545. const timeNext = times[ i + 1 ];
  31546. // remove adjacent keyframes scheduled at the same time
  31547. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31548. if ( ! smoothInterpolation ) {
  31549. // remove unnecessary keyframes same as their neighbors
  31550. const offset = i * stride,
  31551. offsetP = offset - stride,
  31552. offsetN = offset + stride;
  31553. for ( let j = 0; j !== stride; ++ j ) {
  31554. const value = values[ offset + j ];
  31555. if ( value !== values[ offsetP + j ] ||
  31556. value !== values[ offsetN + j ] ) {
  31557. keep = true;
  31558. break;
  31559. }
  31560. }
  31561. } else {
  31562. keep = true;
  31563. }
  31564. }
  31565. // in-place compaction
  31566. if ( keep ) {
  31567. if ( i !== writeIndex ) {
  31568. times[ writeIndex ] = times[ i ];
  31569. const readOffset = i * stride,
  31570. writeOffset = writeIndex * stride;
  31571. for ( let j = 0; j !== stride; ++ j ) {
  31572. values[ writeOffset + j ] = values[ readOffset + j ];
  31573. }
  31574. }
  31575. ++ writeIndex;
  31576. }
  31577. }
  31578. // flush last keyframe (compaction looks ahead)
  31579. if ( lastIndex > 0 ) {
  31580. times[ writeIndex ] = times[ lastIndex ];
  31581. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31582. values[ writeOffset + j ] = values[ readOffset + j ];
  31583. }
  31584. ++ writeIndex;
  31585. }
  31586. if ( writeIndex !== times.length ) {
  31587. this.times = times.slice( 0, writeIndex );
  31588. this.values = values.slice( 0, writeIndex * stride );
  31589. } else {
  31590. this.times = times;
  31591. this.values = values;
  31592. }
  31593. return this;
  31594. }
  31595. /**
  31596. * Returns a new keyframe track with copied values from this instance.
  31597. *
  31598. * @return {KeyframeTrack} A clone of this instance.
  31599. */
  31600. clone() {
  31601. const times = this.times.slice();
  31602. const values = this.values.slice();
  31603. const TypedKeyframeTrack = this.constructor;
  31604. const track = new TypedKeyframeTrack( this.name, times, values );
  31605. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31606. track.createInterpolant = this.createInterpolant;
  31607. return track;
  31608. }
  31609. }
  31610. /**
  31611. * The value type name.
  31612. *
  31613. * @type {string}
  31614. * @default ''
  31615. */
  31616. KeyframeTrack.prototype.ValueTypeName = '';
  31617. /**
  31618. * The time buffer type of this keyframe track.
  31619. *
  31620. * @type {TypedArray|Array}
  31621. * @default Float32Array.constructor
  31622. */
  31623. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31624. /**
  31625. * The value buffer type of this keyframe track.
  31626. *
  31627. * @type {TypedArray|Array}
  31628. * @default Float32Array.constructor
  31629. */
  31630. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31631. /**
  31632. * The default interpolation type of this keyframe track.
  31633. *
  31634. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth|InterpolateBezier)}
  31635. * @default InterpolateLinear
  31636. */
  31637. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31638. /**
  31639. * A track for boolean keyframe values.
  31640. *
  31641. * @augments KeyframeTrack
  31642. */
  31643. class BooleanKeyframeTrack extends KeyframeTrack {
  31644. /**
  31645. * Constructs a new boolean keyframe track.
  31646. *
  31647. * This keyframe track type has no `interpolation` parameter because the
  31648. * interpolation is always discrete.
  31649. *
  31650. * @param {string} name - The keyframe track's name.
  31651. * @param {Array<number>} times - A list of keyframe times.
  31652. * @param {Array<boolean>} values - A list of keyframe values.
  31653. */
  31654. constructor( name, times, values ) {
  31655. super( name, times, values );
  31656. }
  31657. }
  31658. /**
  31659. * The value type name.
  31660. *
  31661. * @type {string}
  31662. * @default 'bool'
  31663. */
  31664. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31665. /**
  31666. * The value buffer type of this keyframe track.
  31667. *
  31668. * @type {TypedArray|Array}
  31669. * @default Array.constructor
  31670. */
  31671. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31672. /**
  31673. * The default interpolation type of this keyframe track.
  31674. *
  31675. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31676. * @default InterpolateDiscrete
  31677. */
  31678. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31679. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31680. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31681. /**
  31682. * A track for color keyframe values.
  31683. *
  31684. * @augments KeyframeTrack
  31685. */
  31686. class ColorKeyframeTrack extends KeyframeTrack {
  31687. /**
  31688. * Constructs a new color keyframe track.
  31689. *
  31690. * @param {string} name - The keyframe track's name.
  31691. * @param {Array<number>} times - A list of keyframe times.
  31692. * @param {Array<number>} values - A list of keyframe values.
  31693. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31694. */
  31695. constructor( name, times, values, interpolation ) {
  31696. super( name, times, values, interpolation );
  31697. }
  31698. }
  31699. /**
  31700. * The value type name.
  31701. *
  31702. * @type {string}
  31703. * @default 'color'
  31704. */
  31705. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31706. /**
  31707. * A track for numeric keyframe values.
  31708. *
  31709. * @augments KeyframeTrack
  31710. */
  31711. class NumberKeyframeTrack extends KeyframeTrack {
  31712. /**
  31713. * Constructs a new number keyframe track.
  31714. *
  31715. * @param {string} name - The keyframe track's name.
  31716. * @param {Array<number>} times - A list of keyframe times.
  31717. * @param {Array<number>} values - A list of keyframe values.
  31718. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31719. */
  31720. constructor( name, times, values, interpolation ) {
  31721. super( name, times, values, interpolation );
  31722. }
  31723. }
  31724. /**
  31725. * The value type name.
  31726. *
  31727. * @type {string}
  31728. * @default 'number'
  31729. */
  31730. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31731. /**
  31732. * Spherical linear unit quaternion interpolant.
  31733. *
  31734. * @augments Interpolant
  31735. */
  31736. class QuaternionLinearInterpolant extends Interpolant {
  31737. /**
  31738. * Constructs a new SLERP interpolant.
  31739. *
  31740. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31741. * @param {TypedArray} sampleValues - The sample values.
  31742. * @param {number} sampleSize - The sample size
  31743. * @param {TypedArray} [resultBuffer] - The result buffer.
  31744. */
  31745. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31746. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31747. }
  31748. interpolate_( i1, t0, t, t1 ) {
  31749. const result = this.resultBuffer,
  31750. values = this.sampleValues,
  31751. stride = this.valueSize,
  31752. alpha = ( t - t0 ) / ( t1 - t0 );
  31753. let offset = i1 * stride;
  31754. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31755. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31756. }
  31757. return result;
  31758. }
  31759. }
  31760. /**
  31761. * A track for Quaternion keyframe values.
  31762. *
  31763. * @augments KeyframeTrack
  31764. */
  31765. class QuaternionKeyframeTrack extends KeyframeTrack {
  31766. /**
  31767. * Constructs a new Quaternion keyframe track.
  31768. *
  31769. * @param {string} name - The keyframe track's name.
  31770. * @param {Array<number>} times - A list of keyframe times.
  31771. * @param {Array<number>} values - A list of keyframe values.
  31772. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31773. */
  31774. constructor( name, times, values, interpolation ) {
  31775. super( name, times, values, interpolation );
  31776. }
  31777. /**
  31778. * Overwritten so the method returns Quaternion based interpolant.
  31779. *
  31780. * @static
  31781. * @param {TypedArray} [result] - The result buffer.
  31782. * @return {QuaternionLinearInterpolant} The new interpolant.
  31783. */
  31784. InterpolantFactoryMethodLinear( result ) {
  31785. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31786. }
  31787. }
  31788. /**
  31789. * The value type name.
  31790. *
  31791. * @type {string}
  31792. * @default 'quaternion'
  31793. */
  31794. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31795. // ValueBufferType is inherited
  31796. // DefaultInterpolation is inherited;
  31797. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31798. /**
  31799. * A track for string keyframe values.
  31800. *
  31801. * @augments KeyframeTrack
  31802. */
  31803. class StringKeyframeTrack extends KeyframeTrack {
  31804. /**
  31805. * Constructs a new string keyframe track.
  31806. *
  31807. * This keyframe track type has no `interpolation` parameter because the
  31808. * interpolation is always discrete.
  31809. *
  31810. * @param {string} name - The keyframe track's name.
  31811. * @param {Array<number>} times - A list of keyframe times.
  31812. * @param {Array<string>} values - A list of keyframe values.
  31813. */
  31814. constructor( name, times, values ) {
  31815. super( name, times, values );
  31816. }
  31817. }
  31818. /**
  31819. * The value type name.
  31820. *
  31821. * @type {string}
  31822. * @default 'string'
  31823. */
  31824. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31825. /**
  31826. * The value buffer type of this keyframe track.
  31827. *
  31828. * @type {TypedArray|Array}
  31829. * @default Array.constructor
  31830. */
  31831. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31832. /**
  31833. * The default interpolation type of this keyframe track.
  31834. *
  31835. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31836. * @default InterpolateDiscrete
  31837. */
  31838. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31839. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31840. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31841. /**
  31842. * A track for vector keyframe values.
  31843. *
  31844. * @augments KeyframeTrack
  31845. */
  31846. class VectorKeyframeTrack extends KeyframeTrack {
  31847. /**
  31848. * Constructs a new vector keyframe track.
  31849. *
  31850. * @param {string} name - The keyframe track's name.
  31851. * @param {Array<number>} times - A list of keyframe times.
  31852. * @param {Array<number>} values - A list of keyframe values.
  31853. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31854. */
  31855. constructor( name, times, values, interpolation ) {
  31856. super( name, times, values, interpolation );
  31857. }
  31858. }
  31859. /**
  31860. * The value type name.
  31861. *
  31862. * @type {string}
  31863. * @default 'vector'
  31864. */
  31865. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31866. /**
  31867. * A reusable set of keyframe tracks which represent an animation.
  31868. */
  31869. class AnimationClip {
  31870. /**
  31871. * Constructs a new animation clip.
  31872. *
  31873. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31874. * use the static interface of this class for creating clips. In most cases though, animation clips
  31875. * will automatically be created by loaders when importing animated 3D assets.
  31876. *
  31877. * @param {string} [name=''] - The clip's name.
  31878. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31879. * the duration will be calculated from the passed keyframes.
  31880. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31881. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31882. * is blended/combined when two or more animations are simultaneously played.
  31883. */
  31884. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31885. /**
  31886. * The clip's name.
  31887. *
  31888. * @type {string}
  31889. */
  31890. this.name = name;
  31891. /**
  31892. * An array of keyframe tracks.
  31893. *
  31894. * @type {Array<KeyframeTrack>}
  31895. */
  31896. this.tracks = tracks;
  31897. /**
  31898. * The clip's duration in seconds.
  31899. *
  31900. * @type {number}
  31901. */
  31902. this.duration = duration;
  31903. /**
  31904. * Defines how the animation is blended/combined when two or more animations
  31905. * are simultaneously played.
  31906. *
  31907. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31908. */
  31909. this.blendMode = blendMode;
  31910. /**
  31911. * The UUID of the animation clip.
  31912. *
  31913. * @type {string}
  31914. * @readonly
  31915. */
  31916. this.uuid = generateUUID();
  31917. /**
  31918. * An object that can be used to store custom data about the animation clip.
  31919. * It should not hold references to functions as these will not be cloned.
  31920. *
  31921. * @type {Object}
  31922. */
  31923. this.userData = {};
  31924. // this means it should figure out its duration by scanning the tracks
  31925. if ( this.duration < 0 ) {
  31926. this.resetDuration();
  31927. }
  31928. }
  31929. /**
  31930. * Factory method for creating an animation clip from the given JSON.
  31931. *
  31932. * @static
  31933. * @param {Object} json - The serialized animation clip.
  31934. * @return {AnimationClip} The new animation clip.
  31935. */
  31936. static parse( json ) {
  31937. const tracks = [],
  31938. jsonTracks = json.tracks,
  31939. frameTime = 1.0 / ( json.fps || 1.0 );
  31940. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31941. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31942. }
  31943. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31944. clip.uuid = json.uuid;
  31945. clip.userData = JSON.parse( json.userData || '{}' );
  31946. return clip;
  31947. }
  31948. /**
  31949. * Serializes the given animation clip into JSON.
  31950. *
  31951. * @static
  31952. * @param {AnimationClip} clip - The animation clip to serialize.
  31953. * @return {Object} The JSON object.
  31954. */
  31955. static toJSON( clip ) {
  31956. const tracks = [],
  31957. clipTracks = clip.tracks;
  31958. const json = {
  31959. 'name': clip.name,
  31960. 'duration': clip.duration,
  31961. 'tracks': tracks,
  31962. 'uuid': clip.uuid,
  31963. 'blendMode': clip.blendMode,
  31964. 'userData': JSON.stringify( clip.userData ),
  31965. };
  31966. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31967. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31968. }
  31969. return json;
  31970. }
  31971. /**
  31972. * Returns a new animation clip from the passed morph targets array of a
  31973. * geometry, taking a name and the number of frames per second.
  31974. *
  31975. * Note: The fps parameter is required, but the animation speed can be
  31976. * overridden via {@link AnimationAction#setDuration}.
  31977. *
  31978. * @static
  31979. * @param {string} name - The name of the animation clip.
  31980. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31981. * @param {number} fps - The Frames-Per-Second value.
  31982. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31983. * @return {AnimationClip} The new animation clip.
  31984. */
  31985. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31986. const numMorphTargets = morphTargetSequence.length;
  31987. const tracks = [];
  31988. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31989. let times = [];
  31990. let values = [];
  31991. times.push(
  31992. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31993. i,
  31994. ( i + 1 ) % numMorphTargets );
  31995. values.push( 0, 1, 0 );
  31996. const order = getKeyframeOrder( times );
  31997. times = sortedArray( times, 1, order );
  31998. values = sortedArray( values, 1, order );
  31999. // if there is a key at the first frame, duplicate it as the
  32000. // last frame as well for perfect loop.
  32001. if ( ! noLoop && times[ 0 ] === 0 ) {
  32002. times.push( numMorphTargets );
  32003. values.push( values[ 0 ] );
  32004. }
  32005. tracks.push(
  32006. new NumberKeyframeTrack(
  32007. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  32008. times, values
  32009. ).scale( 1.0 / fps ) );
  32010. }
  32011. return new this( name, -1, tracks );
  32012. }
  32013. /**
  32014. * Searches for an animation clip by name, taking as its first parameter
  32015. * either an array of clips, or a mesh or geometry that contains an
  32016. * array named "animations" property.
  32017. *
  32018. * @static
  32019. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  32020. * @param {string} name - The name to search for.
  32021. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  32022. */
  32023. static findByName( objectOrClipArray, name ) {
  32024. let clipArray = objectOrClipArray;
  32025. if ( ! Array.isArray( objectOrClipArray ) ) {
  32026. const o = objectOrClipArray;
  32027. clipArray = o.geometry && o.geometry.animations || o.animations;
  32028. }
  32029. for ( let i = 0; i < clipArray.length; i ++ ) {
  32030. if ( clipArray[ i ].name === name ) {
  32031. return clipArray[ i ];
  32032. }
  32033. }
  32034. return null;
  32035. }
  32036. /**
  32037. * Returns an array of new AnimationClips created from the morph target
  32038. * sequences of a geometry, trying to sort morph target names into
  32039. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  32040. *
  32041. * See {@link MD2Loader#parse} as an example for how the method should be used.
  32042. *
  32043. * @static
  32044. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  32045. * @param {number} fps - The Frames-Per-Second value.
  32046. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  32047. * @return {Array<AnimationClip>} An array of new animation clips.
  32048. */
  32049. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  32050. const animationToMorphTargets = {};
  32051. // tested with https://regex101.com/ on trick sequences
  32052. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  32053. const pattern = /^([\w-]*?)([\d]+)$/;
  32054. // sort morph target names into animation groups based
  32055. // patterns like Walk_001, Walk_002, Run_001, Run_002
  32056. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  32057. const morphTarget = morphTargets[ i ];
  32058. const parts = morphTarget.name.match( pattern );
  32059. if ( parts && parts.length > 1 ) {
  32060. const name = parts[ 1 ];
  32061. let animationMorphTargets = animationToMorphTargets[ name ];
  32062. if ( ! animationMorphTargets ) {
  32063. animationToMorphTargets[ name ] = animationMorphTargets = [];
  32064. }
  32065. animationMorphTargets.push( morphTarget );
  32066. }
  32067. }
  32068. const clips = [];
  32069. for ( const name in animationToMorphTargets ) {
  32070. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  32071. }
  32072. return clips;
  32073. }
  32074. /**
  32075. * Sets the duration of this clip to the duration of its longest keyframe track.
  32076. *
  32077. * @return {AnimationClip} A reference to this animation clip.
  32078. */
  32079. resetDuration() {
  32080. const tracks = this.tracks;
  32081. let duration = 0;
  32082. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32083. const track = this.tracks[ i ];
  32084. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32085. }
  32086. this.duration = duration;
  32087. return this;
  32088. }
  32089. /**
  32090. * Trims all tracks to the clip's duration.
  32091. *
  32092. * @return {AnimationClip} A reference to this animation clip.
  32093. */
  32094. trim() {
  32095. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32096. this.tracks[ i ].trim( 0, this.duration );
  32097. }
  32098. return this;
  32099. }
  32100. /**
  32101. * Performs minimal validation on each track in the clip. Returns `true` if all
  32102. * tracks are valid.
  32103. *
  32104. * @return {boolean} Whether the clip's keyframes are valid or not.
  32105. */
  32106. validate() {
  32107. let valid = true;
  32108. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32109. valid = valid && this.tracks[ i ].validate();
  32110. }
  32111. return valid;
  32112. }
  32113. /**
  32114. * Optimizes each track by removing equivalent sequential keys (which are
  32115. * common in morph target sequences).
  32116. *
  32117. * @return {AnimationClip} A reference to this animation clip.
  32118. */
  32119. optimize() {
  32120. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32121. this.tracks[ i ].optimize();
  32122. }
  32123. return this;
  32124. }
  32125. /**
  32126. * Returns a new animation clip with copied values from this instance.
  32127. *
  32128. * @return {AnimationClip} A clone of this instance.
  32129. */
  32130. clone() {
  32131. const tracks = [];
  32132. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32133. tracks.push( this.tracks[ i ].clone() );
  32134. }
  32135. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32136. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32137. return clip;
  32138. }
  32139. /**
  32140. * Serializes this animation clip into JSON.
  32141. *
  32142. * @return {Object} The JSON object.
  32143. */
  32144. toJSON() {
  32145. return this.constructor.toJSON( this );
  32146. }
  32147. }
  32148. function getTrackTypeForValueTypeName( typeName ) {
  32149. switch ( typeName.toLowerCase() ) {
  32150. case 'scalar':
  32151. case 'double':
  32152. case 'float':
  32153. case 'number':
  32154. case 'integer':
  32155. return NumberKeyframeTrack;
  32156. case 'vector':
  32157. case 'vector2':
  32158. case 'vector3':
  32159. case 'vector4':
  32160. return VectorKeyframeTrack;
  32161. case 'color':
  32162. return ColorKeyframeTrack;
  32163. case 'quaternion':
  32164. return QuaternionKeyframeTrack;
  32165. case 'bool':
  32166. case 'boolean':
  32167. return BooleanKeyframeTrack;
  32168. case 'string':
  32169. return StringKeyframeTrack;
  32170. }
  32171. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32172. }
  32173. function parseKeyframeTrack( json ) {
  32174. if ( json.type === undefined ) {
  32175. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32176. }
  32177. const trackType = getTrackTypeForValueTypeName( json.type );
  32178. if ( json.times === undefined ) {
  32179. const times = [], values = [];
  32180. flattenJSON( json.keys, times, values, 'value' );
  32181. json.times = times;
  32182. json.values = values;
  32183. }
  32184. // derived classes can define a static parse method
  32185. if ( trackType.parse !== undefined ) {
  32186. return trackType.parse( json );
  32187. } else {
  32188. // by default, we assume a constructor compatible with the base
  32189. return new trackType( json.name, json.times, json.values, json.interpolation );
  32190. }
  32191. }
  32192. /**
  32193. * @class
  32194. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32195. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32196. * @hideconstructor
  32197. */
  32198. const Cache = {
  32199. /**
  32200. * Whether caching is enabled or not.
  32201. *
  32202. * @static
  32203. * @type {boolean}
  32204. * @default false
  32205. */
  32206. enabled: false,
  32207. /**
  32208. * A dictionary that holds cached files.
  32209. *
  32210. * @static
  32211. * @type {Object<string,Object>}
  32212. */
  32213. files: {},
  32214. /**
  32215. * Adds a cache entry with a key to reference the file. If this key already
  32216. * holds a file, it is overwritten.
  32217. *
  32218. * @static
  32219. * @param {string} key - The key to reference the cached file.
  32220. * @param {Object} file - The file to be cached.
  32221. */
  32222. add: function ( key, file ) {
  32223. if ( this.enabled === false ) return;
  32224. if ( isBlobURL( key ) ) return;
  32225. // log( 'Cache', 'Adding key:', key );
  32226. this.files[ key ] = file;
  32227. },
  32228. /**
  32229. * Gets the cached value for the given key.
  32230. *
  32231. * @static
  32232. * @param {string} key - The key to reference the cached file.
  32233. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32234. */
  32235. get: function ( key ) {
  32236. if ( this.enabled === false ) return;
  32237. if ( isBlobURL( key ) ) return;
  32238. // log( 'Cache', 'Checking key:', key );
  32239. return this.files[ key ];
  32240. },
  32241. /**
  32242. * Removes the cached file associated with the given key.
  32243. *
  32244. * @static
  32245. * @param {string} key - The key to reference the cached file.
  32246. */
  32247. remove: function ( key ) {
  32248. delete this.files[ key ];
  32249. },
  32250. /**
  32251. * Remove all values from the cache.
  32252. *
  32253. * @static
  32254. */
  32255. clear: function () {
  32256. this.files = {};
  32257. }
  32258. };
  32259. /**
  32260. * Returns true if the given cache key contains the blob: scheme.
  32261. *
  32262. * @private
  32263. * @param {string} key - The cache key.
  32264. * @return {boolean} Whether the given cache key contains the blob: scheme or not.
  32265. */
  32266. function isBlobURL( key ) {
  32267. try {
  32268. const urlString = key.slice( key.indexOf( ':' ) + 1 ); // remove type identifier
  32269. const url = new URL( urlString );
  32270. return url.protocol === 'blob:';
  32271. } catch ( e ) {
  32272. // If the string is not a valid URL, it throws an error
  32273. return false;
  32274. }
  32275. }
  32276. /**
  32277. * Handles and keeps track of loaded and pending data. A default global
  32278. * instance of this class is created and used by loaders if not supplied
  32279. * manually.
  32280. *
  32281. * In general that should be sufficient, however there are times when it can
  32282. * be useful to have separate loaders - for example if you want to show
  32283. * separate loading bars for objects and textures.
  32284. *
  32285. * ```js
  32286. * const manager = new THREE.LoadingManager();
  32287. * manager.onLoad = () => console.log( 'Loading complete!' );
  32288. *
  32289. * const loader1 = new OBJLoader( manager );
  32290. * const loader2 = new ColladaLoader( manager );
  32291. * ```
  32292. */
  32293. class LoadingManager {
  32294. /**
  32295. * Constructs a new loading manager.
  32296. *
  32297. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32298. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32299. * @param {Function} [onError] - Executes when an error occurs.
  32300. */
  32301. constructor( onLoad, onProgress, onError ) {
  32302. const scope = this;
  32303. let isLoading = false;
  32304. let itemsLoaded = 0;
  32305. let itemsTotal = 0;
  32306. let urlModifier = undefined;
  32307. const handlers = [];
  32308. // Refer to #5689 for the reason why we don't set .onStart
  32309. // in the constructor
  32310. /**
  32311. * Executes when an item starts loading.
  32312. *
  32313. * @type {Function|undefined}
  32314. * @default undefined
  32315. */
  32316. this.onStart = undefined;
  32317. /**
  32318. * Executes when all items have been loaded.
  32319. *
  32320. * @type {Function|undefined}
  32321. * @default undefined
  32322. */
  32323. this.onLoad = onLoad;
  32324. /**
  32325. * Executes when single items have been loaded.
  32326. *
  32327. * @type {Function|undefined}
  32328. * @default undefined
  32329. */
  32330. this.onProgress = onProgress;
  32331. /**
  32332. * Executes when an error occurs.
  32333. *
  32334. * @type {Function|undefined}
  32335. * @default undefined
  32336. */
  32337. this.onError = onError;
  32338. /**
  32339. * Used for aborting ongoing requests in loaders using this manager.
  32340. *
  32341. * @private
  32342. * @type {AbortController | null}
  32343. */
  32344. this._abortController = null;
  32345. /**
  32346. * This should be called by any loader using the manager when the loader
  32347. * starts loading an item.
  32348. *
  32349. * @param {string} url - The URL to load.
  32350. */
  32351. this.itemStart = function ( url ) {
  32352. itemsTotal ++;
  32353. if ( isLoading === false ) {
  32354. if ( scope.onStart !== undefined ) {
  32355. scope.onStart( url, itemsLoaded, itemsTotal );
  32356. }
  32357. }
  32358. isLoading = true;
  32359. };
  32360. /**
  32361. * This should be called by any loader using the manager when the loader
  32362. * ended loading an item.
  32363. *
  32364. * @param {string} url - The URL of the loaded item.
  32365. */
  32366. this.itemEnd = function ( url ) {
  32367. itemsLoaded ++;
  32368. if ( scope.onProgress !== undefined ) {
  32369. scope.onProgress( url, itemsLoaded, itemsTotal );
  32370. }
  32371. if ( itemsLoaded === itemsTotal ) {
  32372. isLoading = false;
  32373. if ( scope.onLoad !== undefined ) {
  32374. scope.onLoad();
  32375. }
  32376. }
  32377. };
  32378. /**
  32379. * This should be called by any loader using the manager when the loader
  32380. * encounters an error when loading an item.
  32381. *
  32382. * @param {string} url - The URL of the item that produces an error.
  32383. */
  32384. this.itemError = function ( url ) {
  32385. if ( scope.onError !== undefined ) {
  32386. scope.onError( url );
  32387. }
  32388. };
  32389. /**
  32390. * Given a URL, uses the URL modifier callback (if any) and returns a
  32391. * resolved URL. If no URL modifier is set, returns the original URL.
  32392. *
  32393. * @param {string} url - The URL to load.
  32394. * @return {string} The resolved URL.
  32395. */
  32396. this.resolveURL = function ( url ) {
  32397. // Normalize to NFC so that Unicode URIs (e.g. from glTF)
  32398. // are percent-encoded correctly per RFC 3987.
  32399. url = url.normalize( 'NFC' );
  32400. if ( urlModifier ) {
  32401. return urlModifier( url );
  32402. }
  32403. return url;
  32404. };
  32405. /**
  32406. * If provided, the callback will be passed each resource URL before a
  32407. * request is sent. The callback may return the original URL, or a new URL to
  32408. * override loading behavior. This behavior can be used to load assets from
  32409. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32410. *
  32411. * ```js
  32412. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32413. *
  32414. * const manager = new THREE.LoadingManager();
  32415. *
  32416. * // Initialize loading manager with URL callback.
  32417. * const objectURLs = [];
  32418. * manager.setURLModifier( ( url ) => {
  32419. *
  32420. * url = URL.createObjectURL( blobs[ url ] );
  32421. * objectURLs.push( url );
  32422. * return url;
  32423. *
  32424. * } );
  32425. *
  32426. * // Load as usual, then revoke the blob URLs.
  32427. * const loader = new GLTFLoader( manager );
  32428. * loader.load( 'fish.gltf', (gltf) => {
  32429. *
  32430. * scene.add( gltf.scene );
  32431. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32432. *
  32433. * } );
  32434. * ```
  32435. *
  32436. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32437. * @return {LoadingManager} A reference to this loading manager.
  32438. */
  32439. this.setURLModifier = function ( transform ) {
  32440. urlModifier = transform;
  32441. return this;
  32442. };
  32443. /**
  32444. * Registers a loader with the given regular expression. Can be used to
  32445. * define what loader should be used in order to load specific files. A
  32446. * typical use case is to overwrite the default loader for textures.
  32447. *
  32448. * ```js
  32449. * // add handler for TGA textures
  32450. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32451. * ```
  32452. *
  32453. * @param {string} regex - A regular expression.
  32454. * @param {Loader} loader - A loader that should handle matched cases.
  32455. * @return {LoadingManager} A reference to this loading manager.
  32456. */
  32457. this.addHandler = function ( regex, loader ) {
  32458. handlers.push( regex, loader );
  32459. return this;
  32460. };
  32461. /**
  32462. * Removes the loader for the given regular expression.
  32463. *
  32464. * @param {string} regex - A regular expression.
  32465. * @return {LoadingManager} A reference to this loading manager.
  32466. */
  32467. this.removeHandler = function ( regex ) {
  32468. const index = handlers.indexOf( regex );
  32469. if ( index !== -1 ) {
  32470. handlers.splice( index, 2 );
  32471. }
  32472. return this;
  32473. };
  32474. /**
  32475. * Can be used to retrieve the registered loader for the given file path.
  32476. *
  32477. * @param {string} file - The file path.
  32478. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32479. */
  32480. this.getHandler = function ( file ) {
  32481. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32482. const regex = handlers[ i ];
  32483. const loader = handlers[ i + 1 ];
  32484. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32485. if ( regex.test( file ) ) {
  32486. return loader;
  32487. }
  32488. }
  32489. return null;
  32490. };
  32491. /**
  32492. * Can be used to abort ongoing loading requests in loaders using this manager.
  32493. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32494. * is supported in the browser.
  32495. *
  32496. * @return {LoadingManager} A reference to this loading manager.
  32497. */
  32498. this.abort = function () {
  32499. this.abortController.abort();
  32500. this._abortController = null;
  32501. return this;
  32502. };
  32503. }
  32504. // TODO: Revert this back to a single member variable once this issue has been fixed
  32505. // https://github.com/cloudflare/workerd/issues/3657
  32506. /**
  32507. * Used for aborting ongoing requests in loaders using this manager.
  32508. *
  32509. * @type {AbortController}
  32510. */
  32511. get abortController() {
  32512. if ( ! this._abortController ) {
  32513. this._abortController = new AbortController();
  32514. }
  32515. return this._abortController;
  32516. }
  32517. }
  32518. /**
  32519. * The global default loading manager.
  32520. *
  32521. * @constant
  32522. * @type {LoadingManager}
  32523. */
  32524. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32525. /**
  32526. * Abstract base class for loaders.
  32527. *
  32528. * @abstract
  32529. */
  32530. class Loader {
  32531. /**
  32532. * Constructs a new loader.
  32533. *
  32534. * @param {LoadingManager} [manager] - The loading manager.
  32535. */
  32536. constructor( manager ) {
  32537. /**
  32538. * The loading manager.
  32539. *
  32540. * @type {LoadingManager}
  32541. * @default DefaultLoadingManager
  32542. */
  32543. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32544. /**
  32545. * The crossOrigin string to implement CORS for loading the url from a
  32546. * different domain that allows CORS.
  32547. *
  32548. * @type {string}
  32549. * @default 'anonymous'
  32550. */
  32551. this.crossOrigin = 'anonymous';
  32552. /**
  32553. * Whether the XMLHttpRequest uses credentials.
  32554. *
  32555. * @type {boolean}
  32556. * @default false
  32557. */
  32558. this.withCredentials = false;
  32559. /**
  32560. * The base path from which the asset will be loaded.
  32561. *
  32562. * @type {string}
  32563. */
  32564. this.path = '';
  32565. /**
  32566. * The base path from which additional resources like textures will be loaded.
  32567. *
  32568. * @type {string}
  32569. */
  32570. this.resourcePath = '';
  32571. /**
  32572. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32573. * used in HTTP request.
  32574. *
  32575. * @type {Object<string, any>}
  32576. */
  32577. this.requestHeader = {};
  32578. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32579. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32580. }
  32581. }
  32582. /**
  32583. * This method needs to be implemented by all concrete loaders. It holds the
  32584. * logic for loading assets from the backend.
  32585. *
  32586. * @abstract
  32587. * @param {string} url - The path/URL of the file to be loaded.
  32588. * @param {Function} onLoad - Executed when the loading process has been finished.
  32589. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32590. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32591. */
  32592. load( /* url, onLoad, onProgress, onError */ ) {}
  32593. /**
  32594. * A async version of {@link Loader#load}.
  32595. *
  32596. * @param {string} url - The path/URL of the file to be loaded.
  32597. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32598. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32599. */
  32600. loadAsync( url, onProgress ) {
  32601. const scope = this;
  32602. return new Promise( function ( resolve, reject ) {
  32603. scope.load( url, resolve, onProgress, reject );
  32604. } );
  32605. }
  32606. /**
  32607. * This method needs to be implemented by all concrete loaders. It holds the
  32608. * logic for parsing the asset into three.js entities.
  32609. *
  32610. * @abstract
  32611. * @param {any} data - The data to parse.
  32612. */
  32613. parse( /* data */ ) {}
  32614. /**
  32615. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32616. * from a different domain that allows CORS.
  32617. *
  32618. * @param {string} crossOrigin - The `crossOrigin` value.
  32619. * @return {Loader} A reference to this instance.
  32620. */
  32621. setCrossOrigin( crossOrigin ) {
  32622. this.crossOrigin = crossOrigin;
  32623. return this;
  32624. }
  32625. /**
  32626. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32627. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32628. *
  32629. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32630. *
  32631. * @param {boolean} value - The `withCredentials` value.
  32632. * @return {Loader} A reference to this instance.
  32633. */
  32634. setWithCredentials( value ) {
  32635. this.withCredentials = value;
  32636. return this;
  32637. }
  32638. /**
  32639. * Sets the base path for the asset.
  32640. *
  32641. * @param {string} path - The base path.
  32642. * @return {Loader} A reference to this instance.
  32643. */
  32644. setPath( path ) {
  32645. this.path = path;
  32646. return this;
  32647. }
  32648. /**
  32649. * Sets the base path for dependent resources like textures.
  32650. *
  32651. * @param {string} resourcePath - The resource path.
  32652. * @return {Loader} A reference to this instance.
  32653. */
  32654. setResourcePath( resourcePath ) {
  32655. this.resourcePath = resourcePath;
  32656. return this;
  32657. }
  32658. /**
  32659. * Sets the given request header.
  32660. *
  32661. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32662. * for configuring the HTTP request.
  32663. * @return {Loader} A reference to this instance.
  32664. */
  32665. setRequestHeader( requestHeader ) {
  32666. this.requestHeader = requestHeader;
  32667. return this;
  32668. }
  32669. /**
  32670. * This method can be implemented in loaders for aborting ongoing requests.
  32671. *
  32672. * @abstract
  32673. * @return {Loader} A reference to this instance.
  32674. */
  32675. abort() {
  32676. return this;
  32677. }
  32678. }
  32679. /**
  32680. * Callback for onProgress in loaders.
  32681. *
  32682. * @callback onProgressCallback
  32683. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32684. */
  32685. /**
  32686. * Callback for onError in loaders.
  32687. *
  32688. * @callback onErrorCallback
  32689. * @param {Error} error - The error which occurred during the loading process.
  32690. */
  32691. /**
  32692. * The default material name that is used by loaders
  32693. * when creating materials for loaded 3D objects.
  32694. *
  32695. * Note: Not all loaders might honor this setting.
  32696. *
  32697. * @static
  32698. * @type {string}
  32699. * @default '__DEFAULT'
  32700. */
  32701. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32702. const loading = {};
  32703. class HttpError extends Error {
  32704. constructor( message, response ) {
  32705. super( message );
  32706. this.response = response;
  32707. }
  32708. }
  32709. /**
  32710. * A low level class for loading resources with the Fetch API, used internally by
  32711. * most loaders. It can also be used directly to load any file type that does
  32712. * not have a loader.
  32713. *
  32714. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32715. * once to your application.
  32716. *
  32717. * ```js
  32718. * const loader = new THREE.FileLoader();
  32719. * const data = await loader.loadAsync( 'example.txt' );
  32720. * ```
  32721. *
  32722. * @augments Loader
  32723. */
  32724. class FileLoader extends Loader {
  32725. /**
  32726. * Constructs a new file loader.
  32727. *
  32728. * @param {LoadingManager} [manager] - The loading manager.
  32729. */
  32730. constructor( manager ) {
  32731. super( manager );
  32732. /**
  32733. * The expected mime type. Valid values can be found
  32734. * [here](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32735. *
  32736. * @type {string}
  32737. */
  32738. this.mimeType = '';
  32739. /**
  32740. * The expected response type.
  32741. *
  32742. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32743. * @default ''
  32744. */
  32745. this.responseType = '';
  32746. /**
  32747. * Used for aborting requests.
  32748. *
  32749. * @private
  32750. * @type {AbortController}
  32751. */
  32752. this._abortController = new AbortController();
  32753. }
  32754. /**
  32755. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32756. *
  32757. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32758. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32759. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32760. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32761. */
  32762. load( url, onLoad, onProgress, onError ) {
  32763. if ( url === undefined ) url = '';
  32764. if ( this.path !== undefined ) url = this.path + url;
  32765. url = this.manager.resolveURL( url );
  32766. const cached = Cache.get( `file:${url}` );
  32767. if ( cached !== undefined ) {
  32768. this.manager.itemStart( url );
  32769. setTimeout( () => {
  32770. if ( onLoad ) onLoad( cached );
  32771. this.manager.itemEnd( url );
  32772. }, 0 );
  32773. return;
  32774. }
  32775. // Check if request is duplicate
  32776. if ( loading[ url ] !== undefined ) {
  32777. loading[ url ].push( {
  32778. onLoad: onLoad,
  32779. onProgress: onProgress,
  32780. onError: onError
  32781. } );
  32782. return;
  32783. }
  32784. // Initialise array for duplicate requests
  32785. loading[ url ] = [];
  32786. loading[ url ].push( {
  32787. onLoad: onLoad,
  32788. onProgress: onProgress,
  32789. onError: onError,
  32790. } );
  32791. // create request
  32792. const req = new Request( url, {
  32793. headers: new Headers( this.requestHeader ),
  32794. credentials: this.withCredentials ? 'include' : 'same-origin',
  32795. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32796. } );
  32797. // record states ( avoid data race )
  32798. const mimeType = this.mimeType;
  32799. const responseType = this.responseType;
  32800. // start the fetch
  32801. fetch( req )
  32802. .then( response => {
  32803. if ( response.status === 200 || response.status === 0 ) {
  32804. // Some browsers return HTTP Status 0 when using non-http protocol
  32805. // e.g. 'file://' or 'data://'. Handle as success.
  32806. if ( response.status === 0 ) {
  32807. warn( 'FileLoader: HTTP Status 0 received.' );
  32808. }
  32809. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32810. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32811. return response;
  32812. }
  32813. const callbacks = loading[ url ];
  32814. const reader = response.body.getReader();
  32815. // Nginx needs X-File-Size check
  32816. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32817. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32818. const total = contentLength ? parseInt( contentLength ) : 0;
  32819. const lengthComputable = total !== 0;
  32820. let loaded = 0;
  32821. // periodically read data into the new stream tracking while download progress
  32822. const stream = new ReadableStream( {
  32823. start( controller ) {
  32824. readData();
  32825. function readData() {
  32826. reader.read().then( ( { done, value } ) => {
  32827. if ( done ) {
  32828. controller.close();
  32829. } else {
  32830. loaded += value.byteLength;
  32831. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32832. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32833. const callback = callbacks[ i ];
  32834. if ( callback.onProgress ) callback.onProgress( event );
  32835. }
  32836. controller.enqueue( value );
  32837. readData();
  32838. }
  32839. }, ( e ) => {
  32840. controller.error( e );
  32841. } );
  32842. }
  32843. }
  32844. } );
  32845. return new Response( stream );
  32846. } else {
  32847. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32848. }
  32849. } )
  32850. .then( response => {
  32851. switch ( responseType ) {
  32852. case 'arraybuffer':
  32853. return response.arrayBuffer();
  32854. case 'blob':
  32855. return response.blob();
  32856. case 'document':
  32857. return response.text()
  32858. .then( text => {
  32859. const parser = new DOMParser();
  32860. return parser.parseFromString( text, mimeType );
  32861. } );
  32862. case 'json':
  32863. return response.json();
  32864. default:
  32865. if ( mimeType === '' ) {
  32866. return response.text();
  32867. } else {
  32868. // sniff encoding
  32869. const re = /charset="?([^;"\s]*)"?/i;
  32870. const exec = re.exec( mimeType );
  32871. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32872. const decoder = new TextDecoder( label );
  32873. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32874. }
  32875. }
  32876. } )
  32877. .then( data => {
  32878. // Add to cache only on HTTP success, so that we do not cache
  32879. // error response bodies as proper responses to requests.
  32880. Cache.add( `file:${url}`, data );
  32881. const callbacks = loading[ url ];
  32882. delete loading[ url ];
  32883. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32884. const callback = callbacks[ i ];
  32885. if ( callback.onLoad ) callback.onLoad( data );
  32886. }
  32887. } )
  32888. .catch( err => {
  32889. // Abort errors and other errors are handled the same
  32890. const callbacks = loading[ url ];
  32891. if ( callbacks === undefined ) {
  32892. // When onLoad was called and url was deleted in `loading`
  32893. this.manager.itemError( url );
  32894. throw err;
  32895. }
  32896. delete loading[ url ];
  32897. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32898. const callback = callbacks[ i ];
  32899. if ( callback.onError ) callback.onError( err );
  32900. }
  32901. this.manager.itemError( url );
  32902. } )
  32903. .finally( () => {
  32904. this.manager.itemEnd( url );
  32905. } );
  32906. this.manager.itemStart( url );
  32907. }
  32908. /**
  32909. * Sets the expected response type.
  32910. *
  32911. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32912. * @return {FileLoader} A reference to this file loader.
  32913. */
  32914. setResponseType( value ) {
  32915. this.responseType = value;
  32916. return this;
  32917. }
  32918. /**
  32919. * Sets the expected mime type of the loaded file.
  32920. *
  32921. * @param {string} value - The mime type.
  32922. * @return {FileLoader} A reference to this file loader.
  32923. */
  32924. setMimeType( value ) {
  32925. this.mimeType = value;
  32926. return this;
  32927. }
  32928. /**
  32929. * Aborts ongoing fetch requests.
  32930. *
  32931. * @return {FileLoader} A reference to this instance.
  32932. */
  32933. abort() {
  32934. this._abortController.abort();
  32935. this._abortController = new AbortController();
  32936. return this;
  32937. }
  32938. }
  32939. /**
  32940. * Class for loading animation clips in the JSON format. The files are internally
  32941. * loaded via {@link FileLoader}.
  32942. *
  32943. * ```js
  32944. * const loader = new THREE.AnimationLoader();
  32945. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32946. * ```
  32947. *
  32948. * @augments Loader
  32949. */
  32950. class AnimationLoader extends Loader {
  32951. /**
  32952. * Constructs a new animation loader.
  32953. *
  32954. * @param {LoadingManager} [manager] - The loading manager.
  32955. */
  32956. constructor( manager ) {
  32957. super( manager );
  32958. }
  32959. /**
  32960. * Starts loading from the given URL and pass the loaded animations as an array
  32961. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32962. *
  32963. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32964. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32965. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32966. * @param {onErrorCallback} onError - Executed when errors occur.
  32967. */
  32968. load( url, onLoad, onProgress, onError ) {
  32969. const scope = this;
  32970. const loader = new FileLoader( this.manager );
  32971. loader.setPath( this.path );
  32972. loader.setRequestHeader( this.requestHeader );
  32973. loader.setWithCredentials( this.withCredentials );
  32974. loader.load( url, function ( text ) {
  32975. try {
  32976. onLoad( scope.parse( JSON.parse( text ) ) );
  32977. } catch ( e ) {
  32978. if ( onError ) {
  32979. onError( e );
  32980. } else {
  32981. error( e );
  32982. }
  32983. scope.manager.itemError( url );
  32984. }
  32985. }, onProgress, onError );
  32986. }
  32987. /**
  32988. * Parses the given JSON object and returns an array of animation clips.
  32989. *
  32990. * @param {Object} json - The serialized animation clips.
  32991. * @return {Array<AnimationClip>} The parsed animation clips.
  32992. */
  32993. parse( json ) {
  32994. const animations = [];
  32995. for ( let i = 0; i < json.length; i ++ ) {
  32996. const clip = AnimationClip.parse( json[ i ] );
  32997. animations.push( clip );
  32998. }
  32999. return animations;
  33000. }
  33001. }
  33002. /**
  33003. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  33004. * Textures are internally loaded via {@link FileLoader}.
  33005. *
  33006. * Derived classes have to implement the `parse()` method which holds the parsing
  33007. * for the respective format.
  33008. *
  33009. * @abstract
  33010. * @augments Loader
  33011. */
  33012. class CompressedTextureLoader extends Loader {
  33013. /**
  33014. * Constructs a new compressed texture loader.
  33015. *
  33016. * @param {LoadingManager} [manager] - The loading manager.
  33017. */
  33018. constructor( manager ) {
  33019. super( manager );
  33020. }
  33021. /**
  33022. * Starts loading from the given URL and passes the loaded compressed texture
  33023. * to the `onLoad()` callback. The method also returns a new texture object which can
  33024. * directly be used for material creation. If you do it this way, the texture
  33025. * may pop up in your scene once the respective loading process is finished.
  33026. *
  33027. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33028. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  33029. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33030. * @param {onErrorCallback} onError - Executed when errors occur.
  33031. * @return {CompressedTexture} The compressed texture.
  33032. */
  33033. load( url, onLoad, onProgress, onError ) {
  33034. const scope = this;
  33035. const images = [];
  33036. const texture = new CompressedTexture();
  33037. const loader = new FileLoader( this.manager );
  33038. loader.setPath( this.path );
  33039. loader.setResponseType( 'arraybuffer' );
  33040. loader.setRequestHeader( this.requestHeader );
  33041. loader.setWithCredentials( scope.withCredentials );
  33042. let loaded = 0;
  33043. function loadTexture( i ) {
  33044. loader.load( url[ i ], function ( buffer ) {
  33045. const texDatas = scope.parse( buffer, true );
  33046. images[ i ] = {
  33047. width: texDatas.width,
  33048. height: texDatas.height,
  33049. format: texDatas.format,
  33050. mipmaps: texDatas.mipmaps
  33051. };
  33052. loaded += 1;
  33053. if ( loaded === 6 ) {
  33054. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  33055. texture.image = images;
  33056. texture.format = texDatas.format;
  33057. texture.needsUpdate = true;
  33058. if ( onLoad ) onLoad( texture );
  33059. }
  33060. }, onProgress, onError );
  33061. }
  33062. if ( Array.isArray( url ) ) {
  33063. for ( let i = 0, il = url.length; i < il; ++ i ) {
  33064. loadTexture( i );
  33065. }
  33066. } else {
  33067. // compressed cubemap texture stored in a single DDS file
  33068. loader.load( url, function ( buffer ) {
  33069. const texDatas = scope.parse( buffer, true );
  33070. if ( texDatas.isCubemap ) {
  33071. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33072. for ( let f = 0; f < faces; f ++ ) {
  33073. images[ f ] = { mipmaps: [] };
  33074. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33075. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33076. images[ f ].format = texDatas.format;
  33077. images[ f ].width = texDatas.width;
  33078. images[ f ].height = texDatas.height;
  33079. }
  33080. }
  33081. texture.image = images;
  33082. } else {
  33083. texture.image.width = texDatas.width;
  33084. texture.image.height = texDatas.height;
  33085. texture.mipmaps = texDatas.mipmaps;
  33086. }
  33087. if ( texDatas.mipmapCount === 1 ) {
  33088. texture.minFilter = LinearFilter;
  33089. }
  33090. texture.format = texDatas.format;
  33091. texture.needsUpdate = true;
  33092. if ( onLoad ) onLoad( texture );
  33093. }, onProgress, onError );
  33094. }
  33095. return texture;
  33096. }
  33097. }
  33098. const _loading = new WeakMap();
  33099. /**
  33100. * A loader for loading images. The class loads images with the HTML `Image` API.
  33101. *
  33102. * ```js
  33103. * const loader = new THREE.ImageLoader();
  33104. * const image = await loader.loadAsync( 'image.png' );
  33105. * ```
  33106. * Please note that `ImageLoader` has dropped support for progress
  33107. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33108. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33109. *
  33110. * @augments Loader
  33111. */
  33112. class ImageLoader extends Loader {
  33113. /**
  33114. * Constructs a new image loader.
  33115. *
  33116. * @param {LoadingManager} [manager] - The loading manager.
  33117. */
  33118. constructor( manager ) {
  33119. super( manager );
  33120. }
  33121. /**
  33122. * Starts loading from the given URL and passes the loaded image
  33123. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33124. * directly be used for texture creation. If you do it this way, the texture
  33125. * may pop up in your scene once the respective loading process is finished.
  33126. *
  33127. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33128. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33129. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33130. * @param {onErrorCallback} onError - Executed when errors occur.
  33131. * @return {Image} The image.
  33132. */
  33133. load( url, onLoad, onProgress, onError ) {
  33134. if ( this.path !== undefined ) url = this.path + url;
  33135. url = this.manager.resolveURL( url );
  33136. const scope = this;
  33137. const cached = Cache.get( `image:${url}` );
  33138. if ( cached !== undefined ) {
  33139. if ( cached.complete === true ) {
  33140. scope.manager.itemStart( url );
  33141. setTimeout( function () {
  33142. if ( onLoad ) onLoad( cached );
  33143. scope.manager.itemEnd( url );
  33144. }, 0 );
  33145. } else {
  33146. let arr = _loading.get( cached );
  33147. if ( arr === undefined ) {
  33148. arr = [];
  33149. _loading.set( cached, arr );
  33150. }
  33151. arr.push( { onLoad, onError } );
  33152. }
  33153. return cached;
  33154. }
  33155. const image = createElementNS( 'img' );
  33156. function onImageLoad() {
  33157. removeEventListeners();
  33158. if ( onLoad ) onLoad( this );
  33159. //
  33160. const callbacks = _loading.get( this ) || [];
  33161. for ( let i = 0; i < callbacks.length; i ++ ) {
  33162. const callback = callbacks[ i ];
  33163. if ( callback.onLoad ) callback.onLoad( this );
  33164. }
  33165. _loading.delete( this );
  33166. scope.manager.itemEnd( url );
  33167. }
  33168. function onImageError( event ) {
  33169. removeEventListeners();
  33170. if ( onError ) onError( event );
  33171. Cache.remove( `image:${url}` );
  33172. //
  33173. const callbacks = _loading.get( this ) || [];
  33174. for ( let i = 0; i < callbacks.length; i ++ ) {
  33175. const callback = callbacks[ i ];
  33176. if ( callback.onError ) callback.onError( event );
  33177. }
  33178. _loading.delete( this );
  33179. scope.manager.itemError( url );
  33180. scope.manager.itemEnd( url );
  33181. }
  33182. function removeEventListeners() {
  33183. image.removeEventListener( 'load', onImageLoad, false );
  33184. image.removeEventListener( 'error', onImageError, false );
  33185. }
  33186. image.addEventListener( 'load', onImageLoad, false );
  33187. image.addEventListener( 'error', onImageError, false );
  33188. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33189. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33190. }
  33191. Cache.add( `image:${url}`, image );
  33192. scope.manager.itemStart( url );
  33193. image.src = url;
  33194. return image;
  33195. }
  33196. }
  33197. /**
  33198. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33199. *
  33200. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33201. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33202. * like vertical and horizontal cross, column and row layouts are not supported.
  33203. *
  33204. * Note that, by convention, cube maps are specified in a coordinate system
  33205. * in which positive-x is to the right when looking up the positive-z axis --
  33206. * in other words, using a left-handed coordinate system. Since three.js uses
  33207. * a right-handed coordinate system, environment maps used in three.js will
  33208. * have pos-x and neg-x swapped.
  33209. *
  33210. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33211. * is set to `SRGBColorSpace` by default.
  33212. *
  33213. * ```js
  33214. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33215. * const cubeTexture = await loader.loadAsync( [
  33216. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33217. * ] );
  33218. * scene.background = cubeTexture;
  33219. * ```
  33220. *
  33221. * @augments Loader
  33222. */
  33223. class CubeTextureLoader extends Loader {
  33224. /**
  33225. * Constructs a new cube texture loader.
  33226. *
  33227. * @param {LoadingManager} [manager] - The loading manager.
  33228. */
  33229. constructor( manager ) {
  33230. super( manager );
  33231. }
  33232. /**
  33233. * Starts loading from the given URL and pass the fully loaded cube texture
  33234. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33235. * directly be used for material creation. If you do it this way, the cube texture
  33236. * may pop up in your scene once the respective loading process is finished.
  33237. *
  33238. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33239. * cube texture. The urls should be specified in the following order: pos-x,
  33240. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33241. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33242. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33243. * @param {onErrorCallback} onError - Executed when errors occur.
  33244. * @return {CubeTexture} The cube texture.
  33245. */
  33246. load( urls, onLoad, onProgress, onError ) {
  33247. const texture = new CubeTexture();
  33248. texture.colorSpace = SRGBColorSpace;
  33249. const loader = new ImageLoader( this.manager );
  33250. loader.setCrossOrigin( this.crossOrigin );
  33251. loader.setPath( this.path );
  33252. let loaded = 0;
  33253. function loadTexture( i ) {
  33254. loader.load( urls[ i ], function ( image ) {
  33255. texture.images[ i ] = image;
  33256. loaded ++;
  33257. if ( loaded === 6 ) {
  33258. texture.needsUpdate = true;
  33259. if ( onLoad ) onLoad( texture );
  33260. }
  33261. }, undefined, onError );
  33262. }
  33263. for ( let i = 0; i < urls.length; ++ i ) {
  33264. loadTexture( i );
  33265. }
  33266. return texture;
  33267. }
  33268. }
  33269. /**
  33270. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33271. * Textures are internally loaded via {@link FileLoader}.
  33272. *
  33273. * Derived classes have to implement the `parse()` method which holds the parsing
  33274. * for the respective format.
  33275. *
  33276. * @abstract
  33277. * @augments Loader
  33278. */
  33279. class DataTextureLoader extends Loader {
  33280. /**
  33281. * Constructs a new data texture loader.
  33282. *
  33283. * @param {LoadingManager} [manager] - The loading manager.
  33284. */
  33285. constructor( manager ) {
  33286. super( manager );
  33287. }
  33288. /**
  33289. * Starts loading from the given URL and passes the loaded data texture
  33290. * to the `onLoad()` callback. The method also returns a new texture object which can
  33291. * directly be used for material creation. If you do it this way, the texture
  33292. * may pop up in your scene once the respective loading process is finished.
  33293. *
  33294. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33295. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33296. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33297. * @param {onErrorCallback} onError - Executed when errors occur.
  33298. * @return {DataTexture} The data texture.
  33299. */
  33300. load( url, onLoad, onProgress, onError ) {
  33301. const scope = this;
  33302. const texture = new DataTexture();
  33303. const loader = new FileLoader( this.manager );
  33304. loader.setResponseType( 'arraybuffer' );
  33305. loader.setRequestHeader( this.requestHeader );
  33306. loader.setPath( this.path );
  33307. loader.setWithCredentials( scope.withCredentials );
  33308. loader.load( url, function ( buffer ) {
  33309. let texData;
  33310. try {
  33311. texData = scope.parse( buffer );
  33312. } catch ( e ) {
  33313. if ( onError !== undefined ) {
  33314. onError( e );
  33315. } else {
  33316. error( e );
  33317. }
  33318. return;
  33319. }
  33320. scope._applyTexData( texture, texData );
  33321. if ( onLoad ) onLoad( texture, texData );
  33322. }, onProgress, onError );
  33323. return texture;
  33324. }
  33325. /**
  33326. * Parses the given buffer and returns a configured data texture. Use this method
  33327. * for parsing texture data that is already in memory (e.g. drag and drop or data
  33328. * loaded from a server) without going through {@link DataTextureLoader#load}.
  33329. *
  33330. * @param {ArrayBuffer} buffer - The raw texture data.
  33331. * @return {DataTexture} The data texture.
  33332. */
  33333. createDataTexture( buffer ) {
  33334. const texture = new DataTexture();
  33335. this._applyTexData( texture, this.parse( buffer ) );
  33336. return texture;
  33337. }
  33338. /**
  33339. * Applies the given parsed texture data to the given data texture.
  33340. *
  33341. * @private
  33342. * @param {DataTexture} texture - The data texture.
  33343. * @param {DataTextureLoader~TexData} texData - The parsed texture data.
  33344. */
  33345. _applyTexData( texture, texData ) {
  33346. if ( texData.image !== undefined ) {
  33347. texture.image = texData.image;
  33348. } else if ( texData.data !== undefined ) {
  33349. texture.image.width = texData.width;
  33350. texture.image.height = texData.height;
  33351. texture.image.data = texData.data;
  33352. }
  33353. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33354. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33355. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33356. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33357. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33358. if ( texData.colorSpace !== undefined ) {
  33359. texture.colorSpace = texData.colorSpace;
  33360. }
  33361. if ( texData.flipY !== undefined ) {
  33362. texture.flipY = texData.flipY;
  33363. }
  33364. if ( texData.format !== undefined ) {
  33365. texture.format = texData.format;
  33366. }
  33367. if ( texData.type !== undefined ) {
  33368. texture.type = texData.type;
  33369. }
  33370. if ( texData.mipmaps !== undefined ) {
  33371. texture.mipmaps = texData.mipmaps;
  33372. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33373. }
  33374. if ( texData.mipmapCount === 1 ) {
  33375. texture.minFilter = LinearFilter;
  33376. }
  33377. if ( texData.generateMipmaps !== undefined ) {
  33378. texture.generateMipmaps = texData.generateMipmaps;
  33379. }
  33380. texture.needsUpdate = true;
  33381. }
  33382. }
  33383. /**
  33384. * Class for loading textures. Images are internally
  33385. * loaded via {@link ImageLoader}.
  33386. *
  33387. * ```js
  33388. * const loader = new THREE.TextureLoader();
  33389. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33390. *
  33391. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33392. * ```
  33393. * Please note that `TextureLoader` has dropped support for progress
  33394. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33395. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33396. *
  33397. * @augments Loader
  33398. */
  33399. class TextureLoader extends Loader {
  33400. /**
  33401. * Constructs a new texture loader.
  33402. *
  33403. * @param {LoadingManager} [manager] - The loading manager.
  33404. */
  33405. constructor( manager ) {
  33406. super( manager );
  33407. }
  33408. /**
  33409. * Starts loading from the given URL and pass the fully loaded texture
  33410. * to the `onLoad()` callback. The method also returns a new texture object which can
  33411. * directly be used for material creation. If you do it this way, the texture
  33412. * may pop up in your scene once the respective loading process is finished.
  33413. *
  33414. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33415. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33416. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33417. * @param {onErrorCallback} onError - Executed when errors occur.
  33418. * @return {Texture} The texture.
  33419. */
  33420. load( url, onLoad, onProgress, onError ) {
  33421. const texture = new Texture();
  33422. const loader = new ImageLoader( this.manager );
  33423. loader.setCrossOrigin( this.crossOrigin );
  33424. loader.setPath( this.path );
  33425. loader.load( url, function ( image ) {
  33426. texture.image = image;
  33427. texture.needsUpdate = true;
  33428. if ( onLoad !== undefined ) {
  33429. onLoad( texture );
  33430. }
  33431. }, onProgress, onError );
  33432. return texture;
  33433. }
  33434. }
  33435. /**
  33436. * Abstract base class for lights - all other light types inherit the
  33437. * properties and methods described here.
  33438. *
  33439. * @abstract
  33440. * @augments Object3D
  33441. */
  33442. class Light extends Object3D {
  33443. /**
  33444. * Constructs a new light.
  33445. *
  33446. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33447. * @param {number} [intensity=1] - The light's strength/intensity.
  33448. */
  33449. constructor( color, intensity = 1 ) {
  33450. super();
  33451. /**
  33452. * This flag can be used for type testing.
  33453. *
  33454. * @type {boolean}
  33455. * @readonly
  33456. * @default true
  33457. */
  33458. this.isLight = true;
  33459. this.type = 'Light';
  33460. /**
  33461. * The light's color.
  33462. *
  33463. * @type {Color}
  33464. */
  33465. this.color = new Color( color );
  33466. /**
  33467. * The light's intensity.
  33468. *
  33469. * @type {number}
  33470. * @default 1
  33471. */
  33472. this.intensity = intensity;
  33473. }
  33474. /**
  33475. * Frees the GPU-related resources allocated by this instance. Call this
  33476. * method whenever this instance is no longer used in your app.
  33477. */
  33478. dispose() {
  33479. this.dispatchEvent( { type: 'dispose' } );
  33480. }
  33481. copy( source, recursive ) {
  33482. super.copy( source, recursive );
  33483. this.color.copy( source.color );
  33484. this.intensity = source.intensity;
  33485. return this;
  33486. }
  33487. toJSON( meta ) {
  33488. const data = super.toJSON( meta );
  33489. data.object.color = this.color.getHex();
  33490. data.object.intensity = this.intensity;
  33491. return data;
  33492. }
  33493. }
  33494. /**
  33495. * A light source positioned directly above the scene, with color fading from
  33496. * the sky color to the ground color.
  33497. *
  33498. * This light cannot be used to cast shadows.
  33499. *
  33500. * ```js
  33501. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33502. * scene.add( light );
  33503. * ```
  33504. *
  33505. * @augments Light
  33506. */
  33507. class HemisphereLight extends Light {
  33508. /**
  33509. * Constructs a new hemisphere light.
  33510. *
  33511. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33512. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33513. * @param {number} [intensity=1] - The light's strength/intensity.
  33514. */
  33515. constructor( skyColor, groundColor, intensity ) {
  33516. super( skyColor, intensity );
  33517. /**
  33518. * This flag can be used for type testing.
  33519. *
  33520. * @type {boolean}
  33521. * @readonly
  33522. * @default true
  33523. */
  33524. this.isHemisphereLight = true;
  33525. this.type = 'HemisphereLight';
  33526. this.position.copy( Object3D.DEFAULT_UP );
  33527. this.updateMatrix();
  33528. /**
  33529. * The light's ground color.
  33530. *
  33531. * @type {Color}
  33532. */
  33533. this.groundColor = new Color( groundColor );
  33534. }
  33535. copy( source, recursive ) {
  33536. super.copy( source, recursive );
  33537. this.groundColor.copy( source.groundColor );
  33538. return this;
  33539. }
  33540. toJSON( meta ) {
  33541. const data = super.toJSON( meta );
  33542. data.object.groundColor = this.groundColor.getHex();
  33543. return data;
  33544. }
  33545. }
  33546. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33547. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33548. const _lookTarget = /*@__PURE__*/ new Vector3();
  33549. /**
  33550. * Abstract base class for light shadow classes. These classes
  33551. * represent the shadow configuration for different light types.
  33552. *
  33553. * @abstract
  33554. */
  33555. class LightShadow {
  33556. /**
  33557. * Constructs a new light shadow.
  33558. *
  33559. * @param {Camera} camera - The light's view of the world.
  33560. */
  33561. constructor( camera ) {
  33562. /**
  33563. * The light's view of the world.
  33564. *
  33565. * @type {Camera}
  33566. */
  33567. this.camera = camera;
  33568. /**
  33569. * The intensity of the shadow. The default is `1`.
  33570. * Valid values are in the range `[0, 1]`.
  33571. *
  33572. * @type {number}
  33573. * @default 1
  33574. */
  33575. this.intensity = 1;
  33576. /**
  33577. * Shadow map bias, how much to add or subtract from the normalized depth
  33578. * when deciding whether a surface is in shadow.
  33579. *
  33580. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33581. * may help reduce artifacts in shadows.
  33582. *
  33583. * @type {number}
  33584. * @default 0
  33585. */
  33586. this.bias = 0;
  33587. /**
  33588. * A node version of `bias`. Only supported with `WebGPURenderer`.
  33589. *
  33590. * If a bias node is defined, `bias` has no effect.
  33591. *
  33592. * @type {?Node<float>}
  33593. * @default null
  33594. */
  33595. this.biasNode = null;
  33596. /**
  33597. * Defines how much the position used to query the shadow map is offset along
  33598. * the object normal. The default is `0`. Increasing this value can be used to
  33599. * reduce shadow acne especially in large scenes where light shines onto
  33600. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33601. *
  33602. * @type {number}
  33603. * @default 0
  33604. */
  33605. this.normalBias = 0;
  33606. /**
  33607. * Setting this to values greater than 1 will blur the edges of the shadow.
  33608. * High values will cause unwanted banding effects in the shadows - a greater
  33609. * map size will allow for a higher value to be used here before these effects
  33610. * become visible.
  33611. *
  33612. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33613. *
  33614. * @type {number}
  33615. * @default 1
  33616. */
  33617. this.radius = 1;
  33618. /**
  33619. * The amount of samples to use when blurring a VSM shadow map.
  33620. *
  33621. * @type {number}
  33622. * @default 8
  33623. */
  33624. this.blurSamples = 8;
  33625. /**
  33626. * Defines the width and height of the shadow map. Higher values give better quality
  33627. * shadows at the cost of computation time. Values must be powers of two.
  33628. *
  33629. * @type {Vector2}
  33630. * @default (512,512)
  33631. */
  33632. this.mapSize = new Vector2( 512, 512 );
  33633. /**
  33634. * The type of shadow texture. The default is `UnsignedByteType`.
  33635. *
  33636. * @type {number}
  33637. * @default UnsignedByteType
  33638. */
  33639. this.mapType = UnsignedByteType;
  33640. /**
  33641. * The depth map generated using the internal camera; a location beyond a
  33642. * pixel's depth is in shadow. Computed internally during rendering.
  33643. *
  33644. * @type {?RenderTarget}
  33645. * @default null
  33646. */
  33647. this.map = null;
  33648. /**
  33649. * The distribution map generated using the internal camera; an occlusion is
  33650. * calculated based on the distribution of depths. Computed internally during
  33651. * rendering.
  33652. *
  33653. * @type {?RenderTarget}
  33654. * @default null
  33655. */
  33656. this.mapPass = null;
  33657. /**
  33658. * Model to shadow camera space, to compute location and depth in shadow map.
  33659. * This is computed internally during rendering.
  33660. *
  33661. * @type {Matrix4}
  33662. */
  33663. this.matrix = new Matrix4();
  33664. /**
  33665. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33666. * lighting / shadows, you may set this to `false`.
  33667. *
  33668. * @type {boolean}
  33669. * @default true
  33670. */
  33671. this.autoUpdate = true;
  33672. /**
  33673. * When set to `true`, shadow maps will be updated in the next `render` call.
  33674. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33675. * set this property to `true` and then make a render call to update the light's shadow.
  33676. *
  33677. * @type {boolean}
  33678. * @default false
  33679. */
  33680. this.needsUpdate = false;
  33681. this._frustum = new Frustum();
  33682. this._frameExtents = new Vector2( 1, 1 );
  33683. this._viewportCount = 1;
  33684. this._viewports = [
  33685. new Vector4( 0, 0, 1, 1 )
  33686. ];
  33687. }
  33688. /**
  33689. * Used internally by the renderer to get the number of viewports that need
  33690. * to be rendered for this shadow.
  33691. *
  33692. * @return {number} The viewport count.
  33693. */
  33694. getViewportCount() {
  33695. return this._viewportCount;
  33696. }
  33697. /**
  33698. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33699. *
  33700. * @return {Frustum} The shadow camera frustum.
  33701. */
  33702. getFrustum() {
  33703. return this._frustum;
  33704. }
  33705. /**
  33706. * Update the matrices for the camera and shadow, used internally by the renderer.
  33707. *
  33708. * @param {Light} light - The light for which the shadow is being rendered.
  33709. */
  33710. updateMatrices( light ) {
  33711. const shadowCamera = this.camera;
  33712. const shadowMatrix = this.matrix;
  33713. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33714. shadowCamera.position.copy( _lightPositionWorld );
  33715. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  33716. shadowCamera.lookAt( _lookTarget );
  33717. shadowCamera.updateMatrixWorld();
  33718. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33719. this._frustum.setFromProjectionMatrix( _projScreenMatrix, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33720. if ( shadowCamera.coordinateSystem === WebGPUCoordinateSystem || shadowCamera.reversedDepth ) {
  33721. shadowMatrix.set(
  33722. 0.5, 0.0, 0.0, 0.5,
  33723. 0.0, 0.5, 0.0, 0.5,
  33724. 0.0, 0.0, 1.0, 0.0, // Identity Z (preserving the correct [0, 1] range from the projection matrix)
  33725. 0.0, 0.0, 0.0, 1.0
  33726. );
  33727. } else {
  33728. shadowMatrix.set(
  33729. 0.5, 0.0, 0.0, 0.5,
  33730. 0.0, 0.5, 0.0, 0.5,
  33731. 0.0, 0.0, 0.5, 0.5,
  33732. 0.0, 0.0, 0.0, 1.0
  33733. );
  33734. }
  33735. shadowMatrix.multiply( _projScreenMatrix );
  33736. }
  33737. /**
  33738. * Returns a viewport definition for the given viewport index.
  33739. *
  33740. * @param {number} viewportIndex - The viewport index.
  33741. * @return {Vector4} The viewport.
  33742. */
  33743. getViewport( viewportIndex ) {
  33744. return this._viewports[ viewportIndex ];
  33745. }
  33746. /**
  33747. * Returns the frame extends.
  33748. *
  33749. * @return {Vector2} The frame extends.
  33750. */
  33751. getFrameExtents() {
  33752. return this._frameExtents;
  33753. }
  33754. /**
  33755. * Frees the GPU-related resources allocated by this instance. Call this
  33756. * method whenever this instance is no longer used in your app.
  33757. */
  33758. dispose() {
  33759. if ( this.map ) {
  33760. this.map.dispose();
  33761. }
  33762. if ( this.mapPass ) {
  33763. this.mapPass.dispose();
  33764. }
  33765. }
  33766. /**
  33767. * Copies the values of the given light shadow instance to this instance.
  33768. *
  33769. * @param {LightShadow} source - The light shadow to copy.
  33770. * @return {LightShadow} A reference to this light shadow instance.
  33771. */
  33772. copy( source ) {
  33773. this.camera = source.camera.clone();
  33774. this.intensity = source.intensity;
  33775. this.bias = source.bias;
  33776. this.radius = source.radius;
  33777. this.autoUpdate = source.autoUpdate;
  33778. this.needsUpdate = source.needsUpdate;
  33779. this.normalBias = source.normalBias;
  33780. this.blurSamples = source.blurSamples;
  33781. this.mapSize.copy( source.mapSize );
  33782. this.biasNode = source.biasNode;
  33783. return this;
  33784. }
  33785. /**
  33786. * Returns a new light shadow instance with copied values from this instance.
  33787. *
  33788. * @return {LightShadow} A clone of this instance.
  33789. */
  33790. clone() {
  33791. return new this.constructor().copy( this );
  33792. }
  33793. /**
  33794. * Serializes the light shadow into JSON.
  33795. *
  33796. * @return {Object} A JSON object representing the serialized light shadow.
  33797. * @see {@link ObjectLoader#parse}
  33798. */
  33799. toJSON() {
  33800. const object = {};
  33801. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33802. if ( this.bias !== 0 ) object.bias = this.bias;
  33803. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33804. if ( this.radius !== 1 ) object.radius = this.radius;
  33805. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33806. object.camera = this.camera.toJSON( false ).object;
  33807. delete object.camera.matrix;
  33808. return object;
  33809. }
  33810. }
  33811. const _position$2 = /*@__PURE__*/ new Vector3();
  33812. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  33813. const _scale$2 = /*@__PURE__*/ new Vector3();
  33814. /**
  33815. * Abstract base class for cameras. This class should always be inherited
  33816. * when you build a new camera.
  33817. *
  33818. * @abstract
  33819. * @augments Object3D
  33820. */
  33821. class Camera extends Object3D {
  33822. /**
  33823. * Constructs a new camera.
  33824. */
  33825. constructor() {
  33826. super();
  33827. /**
  33828. * This flag can be used for type testing.
  33829. *
  33830. * @type {boolean}
  33831. * @readonly
  33832. * @default true
  33833. */
  33834. this.isCamera = true;
  33835. this.type = 'Camera';
  33836. /**
  33837. * The inverse of the camera's world matrix.
  33838. *
  33839. * @type {Matrix4}
  33840. */
  33841. this.matrixWorldInverse = new Matrix4();
  33842. /**
  33843. * The camera's projection matrix.
  33844. *
  33845. * @type {Matrix4}
  33846. */
  33847. this.projectionMatrix = new Matrix4();
  33848. /**
  33849. * The inverse of the camera's projection matrix.
  33850. *
  33851. * @type {Matrix4}
  33852. */
  33853. this.projectionMatrixInverse = new Matrix4();
  33854. /**
  33855. * The coordinate system in which the camera is used.
  33856. *
  33857. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  33858. */
  33859. this.coordinateSystem = WebGLCoordinateSystem;
  33860. this._reversedDepth = false;
  33861. }
  33862. /**
  33863. * The flag that indicates whether the camera uses a reversed depth buffer.
  33864. *
  33865. * @type {boolean}
  33866. * @default false
  33867. */
  33868. get reversedDepth() {
  33869. return this._reversedDepth;
  33870. }
  33871. copy( source, recursive ) {
  33872. super.copy( source, recursive );
  33873. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  33874. this.projectionMatrix.copy( source.projectionMatrix );
  33875. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  33876. this.coordinateSystem = source.coordinateSystem;
  33877. return this;
  33878. }
  33879. /**
  33880. * Returns a vector representing the ("look") direction of the 3D object in world space.
  33881. *
  33882. * This method is overwritten since cameras have a different forward vector compared to other
  33883. * 3D objects. A camera looks down its local, negative z-axis by default.
  33884. *
  33885. * @param {Vector3} target - The target vector the result is stored to.
  33886. * @return {Vector3} The 3D object's direction in world space.
  33887. */
  33888. getWorldDirection( target ) {
  33889. return super.getWorldDirection( target ).negate();
  33890. }
  33891. updateMatrixWorld( force ) {
  33892. super.updateMatrixWorld( force );
  33893. // exclude scale from view matrix to be glTF conform
  33894. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33895. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33896. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33897. } else {
  33898. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33899. }
  33900. }
  33901. updateWorldMatrix( updateParents, updateChildren ) {
  33902. super.updateWorldMatrix( updateParents, updateChildren );
  33903. // exclude scale from view matrix to be glTF conform
  33904. this.matrixWorld.decompose( _position$2, _quaternion$2, _scale$2 );
  33905. if ( _scale$2.x === 1 && _scale$2.y === 1 && _scale$2.z === 1 ) {
  33906. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  33907. } else {
  33908. this.matrixWorldInverse.compose( _position$2, _quaternion$2, _scale$2.set( 1, 1, 1 ) ).invert();
  33909. }
  33910. }
  33911. clone() {
  33912. return new this.constructor().copy( this );
  33913. }
  33914. }
  33915. const _v3$1 = /*@__PURE__*/ new Vector3();
  33916. const _minTarget = /*@__PURE__*/ new Vector2();
  33917. const _maxTarget = /*@__PURE__*/ new Vector2();
  33918. /**
  33919. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  33920. *
  33921. * This projection mode is designed to mimic the way the human eye sees. It
  33922. * is the most common projection mode used for rendering a 3D scene.
  33923. *
  33924. * ```js
  33925. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  33926. * scene.add( camera );
  33927. * ```
  33928. *
  33929. * @augments Camera
  33930. */
  33931. class PerspectiveCamera extends Camera {
  33932. /**
  33933. * Constructs a new perspective camera.
  33934. *
  33935. * @param {number} [fov=50] - The vertical field of view.
  33936. * @param {number} [aspect=1] - The aspect ratio.
  33937. * @param {number} [near=0.1] - The camera's near plane.
  33938. * @param {number} [far=2000] - The camera's far plane.
  33939. */
  33940. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  33941. super();
  33942. /**
  33943. * This flag can be used for type testing.
  33944. *
  33945. * @type {boolean}
  33946. * @readonly
  33947. * @default true
  33948. */
  33949. this.isPerspectiveCamera = true;
  33950. this.type = 'PerspectiveCamera';
  33951. /**
  33952. * The vertical field of view, from bottom to top of view,
  33953. * in degrees.
  33954. *
  33955. * @type {number}
  33956. * @default 50
  33957. */
  33958. this.fov = fov;
  33959. /**
  33960. * The zoom factor of the camera.
  33961. *
  33962. * @type {number}
  33963. * @default 1
  33964. */
  33965. this.zoom = 1;
  33966. /**
  33967. * The camera's near plane. The valid range is greater than `0`
  33968. * and less than the current value of {@link PerspectiveCamera#far}.
  33969. *
  33970. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  33971. * valid value for a perspective camera's near plane.
  33972. *
  33973. * @type {number}
  33974. * @default 0.1
  33975. */
  33976. this.near = near;
  33977. /**
  33978. * The camera's far plane. Must be greater than the
  33979. * current value of {@link PerspectiveCamera#near}.
  33980. *
  33981. * @type {number}
  33982. * @default 2000
  33983. */
  33984. this.far = far;
  33985. /**
  33986. * Object distance used for stereoscopy and depth-of-field effects. This
  33987. * parameter does not influence the projection matrix unless a
  33988. * {@link StereoCamera} is being used.
  33989. *
  33990. * @type {number}
  33991. * @default 10
  33992. */
  33993. this.focus = 10;
  33994. /**
  33995. * The aspect ratio, usually the canvas width / canvas height.
  33996. *
  33997. * @type {number}
  33998. * @default 1
  33999. */
  34000. this.aspect = aspect;
  34001. /**
  34002. * Represents the frustum window specification. This property should not be edited
  34003. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34004. *
  34005. * @type {?Object}
  34006. * @default null
  34007. */
  34008. this.view = null;
  34009. /**
  34010. * Film size used for the larger axis. Default is `35` (millimeters). This
  34011. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  34012. * is set to a nonzero value.
  34013. *
  34014. * @type {number}
  34015. * @default 35
  34016. */
  34017. this.filmGauge = 35;
  34018. /**
  34019. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  34020. *
  34021. * @type {number}
  34022. * @default 0
  34023. */
  34024. this.filmOffset = 0;
  34025. this.updateProjectionMatrix();
  34026. }
  34027. copy( source, recursive ) {
  34028. super.copy( source, recursive );
  34029. this.fov = source.fov;
  34030. this.zoom = source.zoom;
  34031. this.near = source.near;
  34032. this.far = source.far;
  34033. this.focus = source.focus;
  34034. this.aspect = source.aspect;
  34035. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34036. this.filmGauge = source.filmGauge;
  34037. this.filmOffset = source.filmOffset;
  34038. return this;
  34039. }
  34040. /**
  34041. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  34042. *
  34043. * The default film gauge is 35, so that the focal length can be specified for
  34044. * a 35mm (full frame) camera.
  34045. *
  34046. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  34047. */
  34048. setFocalLength( focalLength ) {
  34049. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  34050. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  34051. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  34052. this.updateProjectionMatrix();
  34053. }
  34054. /**
  34055. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  34056. * {@link PerspectiveCamera#filmGauge}.
  34057. *
  34058. * @return {number} The computed focal length.
  34059. */
  34060. getFocalLength() {
  34061. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  34062. return 0.5 * this.getFilmHeight() / vExtentSlope;
  34063. }
  34064. /**
  34065. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  34066. *
  34067. * @return {number} The effective FOV.
  34068. */
  34069. getEffectiveFOV() {
  34070. return RAD2DEG * 2 * Math.atan(
  34071. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  34072. }
  34073. /**
  34074. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  34075. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  34076. *
  34077. * @return {number} The film width.
  34078. */
  34079. getFilmWidth() {
  34080. // film not completely covered in portrait format (aspect < 1)
  34081. return this.filmGauge * Math.min( this.aspect, 1 );
  34082. }
  34083. /**
  34084. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  34085. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  34086. *
  34087. * @return {number} The film width.
  34088. */
  34089. getFilmHeight() {
  34090. // film not completely covered in landscape format (aspect > 1)
  34091. return this.filmGauge / Math.max( this.aspect, 1 );
  34092. }
  34093. /**
  34094. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  34095. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  34096. *
  34097. * @param {number} distance - The viewing distance.
  34098. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  34099. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  34100. */
  34101. getViewBounds( distance, minTarget, maxTarget ) {
  34102. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  34103. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  34104. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  34105. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  34106. }
  34107. /**
  34108. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  34109. *
  34110. * @param {number} distance - The viewing distance.
  34111. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  34112. * @returns {Vector2} The view size.
  34113. */
  34114. getViewSize( distance, target ) {
  34115. this.getViewBounds( distance, _minTarget, _maxTarget );
  34116. return target.subVectors( _maxTarget, _minTarget );
  34117. }
  34118. /**
  34119. * Sets an offset in a larger frustum. This is useful for multi-window or
  34120. * multi-monitor/multi-machine setups.
  34121. *
  34122. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  34123. * the monitors are in grid like this
  34124. *```
  34125. * +---+---+---+
  34126. * | A | B | C |
  34127. * +---+---+---+
  34128. * | D | E | F |
  34129. * +---+---+---+
  34130. *```
  34131. * then for each monitor you would call it like this:
  34132. *```js
  34133. * const w = 1920;
  34134. * const h = 1080;
  34135. * const fullWidth = w * 3;
  34136. * const fullHeight = h * 2;
  34137. *
  34138. * // --A--
  34139. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  34140. * // --B--
  34141. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  34142. * // --C--
  34143. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  34144. * // --D--
  34145. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  34146. * // --E--
  34147. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  34148. * // --F--
  34149. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  34150. * ```
  34151. *
  34152. * Note there is no reason monitors have to be the same size or in a grid.
  34153. *
  34154. * @param {number} fullWidth - The full width of multiview setup.
  34155. * @param {number} fullHeight - The full height of multiview setup.
  34156. * @param {number} x - The horizontal offset of the subcamera.
  34157. * @param {number} y - The vertical offset of the subcamera.
  34158. * @param {number} width - The width of subcamera.
  34159. * @param {number} height - The height of subcamera.
  34160. */
  34161. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34162. this.aspect = fullWidth / fullHeight;
  34163. if ( this.view === null ) {
  34164. this.view = {
  34165. enabled: true,
  34166. fullWidth: 1,
  34167. fullHeight: 1,
  34168. offsetX: 0,
  34169. offsetY: 0,
  34170. width: 1,
  34171. height: 1
  34172. };
  34173. }
  34174. this.view.enabled = true;
  34175. this.view.fullWidth = fullWidth;
  34176. this.view.fullHeight = fullHeight;
  34177. this.view.offsetX = x;
  34178. this.view.offsetY = y;
  34179. this.view.width = width;
  34180. this.view.height = height;
  34181. this.updateProjectionMatrix();
  34182. }
  34183. /**
  34184. * Removes the view offset from the projection matrix.
  34185. */
  34186. clearViewOffset() {
  34187. if ( this.view !== null ) {
  34188. this.view.enabled = false;
  34189. }
  34190. this.updateProjectionMatrix();
  34191. }
  34192. /**
  34193. * Updates the camera's projection matrix. Must be called after any change of
  34194. * camera properties.
  34195. */
  34196. updateProjectionMatrix() {
  34197. const near = this.near;
  34198. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  34199. let height = 2 * top;
  34200. let width = this.aspect * height;
  34201. let left = -0.5 * width;
  34202. const view = this.view;
  34203. if ( this.view !== null && this.view.enabled ) {
  34204. const fullWidth = view.fullWidth,
  34205. fullHeight = view.fullHeight;
  34206. left += view.offsetX * width / fullWidth;
  34207. top -= view.offsetY * height / fullHeight;
  34208. width *= view.width / fullWidth;
  34209. height *= view.height / fullHeight;
  34210. }
  34211. const skew = this.filmOffset;
  34212. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  34213. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  34214. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34215. }
  34216. toJSON( meta ) {
  34217. const data = super.toJSON( meta );
  34218. data.object.fov = this.fov;
  34219. data.object.zoom = this.zoom;
  34220. data.object.near = this.near;
  34221. data.object.far = this.far;
  34222. data.object.focus = this.focus;
  34223. data.object.aspect = this.aspect;
  34224. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34225. data.object.filmGauge = this.filmGauge;
  34226. data.object.filmOffset = this.filmOffset;
  34227. return data;
  34228. }
  34229. }
  34230. /**
  34231. * Represents the shadow configuration of directional lights.
  34232. *
  34233. * @augments LightShadow
  34234. */
  34235. class SpotLightShadow extends LightShadow {
  34236. /**
  34237. * Constructs a new spot light shadow.
  34238. */
  34239. constructor() {
  34240. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  34241. /**
  34242. * This flag can be used for type testing.
  34243. *
  34244. * @type {boolean}
  34245. * @readonly
  34246. * @default true
  34247. */
  34248. this.isSpotLightShadow = true;
  34249. /**
  34250. * Used to focus the shadow camera. The camera's field of view is set as a
  34251. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  34252. *
  34253. * @type {number}
  34254. * @default 1
  34255. */
  34256. this.focus = 1;
  34257. /**
  34258. * Texture aspect ratio.
  34259. *
  34260. * @type {number}
  34261. * @default 1
  34262. */
  34263. this.aspect = 1;
  34264. }
  34265. updateMatrices( light ) {
  34266. const camera = this.camera;
  34267. const fov = RAD2DEG * 2 * light.angle * this.focus;
  34268. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  34269. const far = light.distance || camera.far;
  34270. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  34271. camera.fov = fov;
  34272. camera.aspect = aspect;
  34273. camera.far = far;
  34274. camera.updateProjectionMatrix();
  34275. }
  34276. super.updateMatrices( light );
  34277. }
  34278. copy( source ) {
  34279. super.copy( source );
  34280. this.focus = source.focus;
  34281. return this;
  34282. }
  34283. }
  34284. /**
  34285. * This light gets emitted from a single point in one direction, along a cone
  34286. * that increases in size the further from the light it gets.
  34287. *
  34288. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  34289. *
  34290. * ```js
  34291. * // white spotlight shining from the side, modulated by a texture
  34292. * const spotLight = new THREE.SpotLight( 0xffffff );
  34293. * spotLight.position.set( 100, 1000, 100 );
  34294. * spotLight.map = new THREE.TextureLoader().load( url );
  34295. *
  34296. * spotLight.castShadow = true;
  34297. * spotLight.shadow.mapSize.width = 1024;
  34298. * spotLight.shadow.mapSize.height = 1024;
  34299. * spotLight.shadow.camera.near = 500;
  34300. * spotLight.shadow.camera.far = 4000;
  34301. * spotLight.shadow.camera.fov = 30;s
  34302. * ```
  34303. *
  34304. * @augments Light
  34305. */
  34306. class SpotLight extends Light {
  34307. /**
  34308. * Constructs a new spot light.
  34309. *
  34310. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34311. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34312. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34313. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  34314. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  34315. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34316. */
  34317. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  34318. super( color, intensity );
  34319. /**
  34320. * This flag can be used for type testing.
  34321. *
  34322. * @type {boolean}
  34323. * @readonly
  34324. * @default true
  34325. */
  34326. this.isSpotLight = true;
  34327. this.type = 'SpotLight';
  34328. this.position.copy( Object3D.DEFAULT_UP );
  34329. this.updateMatrix();
  34330. /**
  34331. * The spot light points from its position to the
  34332. * target's position.
  34333. *
  34334. * For the target's position to be changed to anything other
  34335. * than the default, it must be added to the scene.
  34336. *
  34337. * It is also possible to set the target to be another 3D object
  34338. * in the scene. The light will now track the target object.
  34339. *
  34340. * @type {Object3D}
  34341. */
  34342. this.target = new Object3D();
  34343. /**
  34344. * Maximum range of the light. `0` means no limit.
  34345. *
  34346. * @type {number}
  34347. * @default 0
  34348. */
  34349. this.distance = distance;
  34350. /**
  34351. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  34352. *
  34353. * @type {number}
  34354. * @default Math.PI/3
  34355. */
  34356. this.angle = angle;
  34357. /**
  34358. * Percent of the spotlight cone that is attenuated due to penumbra.
  34359. * Value range is `[0,1]`.
  34360. *
  34361. * @type {number}
  34362. * @default 0
  34363. */
  34364. this.penumbra = penumbra;
  34365. /**
  34366. * The amount the light dims along the distance of the light. In context of
  34367. * physically-correct rendering the default value should not be changed.
  34368. *
  34369. * @type {number}
  34370. * @default 2
  34371. */
  34372. this.decay = decay;
  34373. /**
  34374. * A texture used to modulate the color of the light. The spot light
  34375. * color is mixed with the RGB value of this texture, with a ratio
  34376. * corresponding to its alpha value. The cookie-like masking effect is
  34377. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  34378. *
  34379. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  34380. *
  34381. * @type {?Texture}
  34382. * @default null
  34383. */
  34384. this.map = null;
  34385. /**
  34386. * This property holds the light's shadow configuration.
  34387. *
  34388. * @type {SpotLightShadow}
  34389. */
  34390. this.shadow = new SpotLightShadow();
  34391. }
  34392. /**
  34393. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34394. * Changing the power will also change the light's intensity.
  34395. *
  34396. * @type {number}
  34397. */
  34398. get power() {
  34399. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34400. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  34401. return this.intensity * Math.PI;
  34402. }
  34403. set power( power ) {
  34404. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34405. this.intensity = power / Math.PI;
  34406. }
  34407. dispose() {
  34408. super.dispose();
  34409. this.shadow.dispose();
  34410. }
  34411. copy( source, recursive ) {
  34412. super.copy( source, recursive );
  34413. this.distance = source.distance;
  34414. this.angle = source.angle;
  34415. this.penumbra = source.penumbra;
  34416. this.decay = source.decay;
  34417. this.target = source.target.clone();
  34418. this.map = source.map;
  34419. this.shadow = source.shadow.clone();
  34420. return this;
  34421. }
  34422. toJSON( meta ) {
  34423. const data = super.toJSON( meta );
  34424. data.object.distance = this.distance;
  34425. data.object.angle = this.angle;
  34426. data.object.decay = this.decay;
  34427. data.object.penumbra = this.penumbra;
  34428. data.object.target = this.target.uuid;
  34429. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  34430. data.object.shadow = this.shadow.toJSON();
  34431. return data;
  34432. }
  34433. }
  34434. /**
  34435. * Represents the shadow configuration of point lights.
  34436. *
  34437. * @augments LightShadow
  34438. */
  34439. class PointLightShadow extends LightShadow {
  34440. /**
  34441. * Constructs a new point light shadow.
  34442. */
  34443. constructor() {
  34444. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  34445. /**
  34446. * This flag can be used for type testing.
  34447. *
  34448. * @type {boolean}
  34449. * @readonly
  34450. * @default true
  34451. */
  34452. this.isPointLightShadow = true;
  34453. }
  34454. }
  34455. /**
  34456. * A light that gets emitted from a single point in all directions. A common
  34457. * use case for this is to replicate the light emitted from a bare
  34458. * lightbulb.
  34459. *
  34460. * This light can cast shadows - see the {@link PointLightShadow} for details.
  34461. *
  34462. * ```js
  34463. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  34464. * light.position.set( 50, 50, 50 );
  34465. * scene.add( light );
  34466. * ```
  34467. *
  34468. * @augments Light
  34469. */
  34470. class PointLight extends Light {
  34471. /**
  34472. * Constructs a new point light.
  34473. *
  34474. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34475. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  34476. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  34477. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  34478. */
  34479. constructor( color, intensity, distance = 0, decay = 2 ) {
  34480. super( color, intensity );
  34481. /**
  34482. * This flag can be used for type testing.
  34483. *
  34484. * @type {boolean}
  34485. * @readonly
  34486. * @default true
  34487. */
  34488. this.isPointLight = true;
  34489. this.type = 'PointLight';
  34490. /**
  34491. * When distance is zero, light will attenuate according to inverse-square
  34492. * law to infinite distance. When distance is non-zero, light will attenuate
  34493. * according to inverse-square law until near the distance cutoff, where it
  34494. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  34495. * physically correct.
  34496. *
  34497. * @type {number}
  34498. * @default 0
  34499. */
  34500. this.distance = distance;
  34501. /**
  34502. * The amount the light dims along the distance of the light. In context of
  34503. * physically-correct rendering the default value should not be changed.
  34504. *
  34505. * @type {number}
  34506. * @default 2
  34507. */
  34508. this.decay = decay;
  34509. /**
  34510. * This property holds the light's shadow configuration.
  34511. *
  34512. * @type {PointLightShadow}
  34513. */
  34514. this.shadow = new PointLightShadow();
  34515. }
  34516. /**
  34517. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34518. * Changing the power will also change the light's intensity.
  34519. *
  34520. * @type {number}
  34521. */
  34522. get power() {
  34523. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34524. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34525. return this.intensity * 4 * Math.PI;
  34526. }
  34527. set power( power ) {
  34528. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34529. this.intensity = power / ( 4 * Math.PI );
  34530. }
  34531. dispose() {
  34532. super.dispose();
  34533. this.shadow.dispose();
  34534. }
  34535. copy( source, recursive ) {
  34536. super.copy( source, recursive );
  34537. this.distance = source.distance;
  34538. this.decay = source.decay;
  34539. this.shadow = source.shadow.clone();
  34540. return this;
  34541. }
  34542. toJSON( meta ) {
  34543. const data = super.toJSON( meta );
  34544. data.object.distance = this.distance;
  34545. data.object.decay = this.decay;
  34546. data.object.shadow = this.shadow.toJSON();
  34547. return data;
  34548. }
  34549. }
  34550. /**
  34551. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34552. *
  34553. * In this projection mode, an object's size in the rendered image stays
  34554. * constant regardless of its distance from the camera. This can be useful
  34555. * for rendering 2D scenes and UI elements, amongst other things.
  34556. *
  34557. * ```js
  34558. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34559. * scene.add( camera );
  34560. * ```
  34561. *
  34562. * @augments Camera
  34563. */
  34564. class OrthographicCamera extends Camera {
  34565. /**
  34566. * Constructs a new orthographic camera.
  34567. *
  34568. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34569. * @param {number} [right=1] - The right plane of the camera's frustum.
  34570. * @param {number} [top=1] - The top plane of the camera's frustum.
  34571. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34572. * @param {number} [near=0.1] - The camera's near plane.
  34573. * @param {number} [far=2000] - The camera's far plane.
  34574. */
  34575. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34576. super();
  34577. /**
  34578. * This flag can be used for type testing.
  34579. *
  34580. * @type {boolean}
  34581. * @readonly
  34582. * @default true
  34583. */
  34584. this.isOrthographicCamera = true;
  34585. this.type = 'OrthographicCamera';
  34586. /**
  34587. * The zoom factor of the camera.
  34588. *
  34589. * @type {number}
  34590. * @default 1
  34591. */
  34592. this.zoom = 1;
  34593. /**
  34594. * Represents the frustum window specification. This property should not be edited
  34595. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34596. *
  34597. * @type {?Object}
  34598. * @default null
  34599. */
  34600. this.view = null;
  34601. /**
  34602. * The left plane of the camera's frustum.
  34603. *
  34604. * @type {number}
  34605. * @default -1
  34606. */
  34607. this.left = left;
  34608. /**
  34609. * The right plane of the camera's frustum.
  34610. *
  34611. * @type {number}
  34612. * @default 1
  34613. */
  34614. this.right = right;
  34615. /**
  34616. * The top plane of the camera's frustum.
  34617. *
  34618. * @type {number}
  34619. * @default 1
  34620. */
  34621. this.top = top;
  34622. /**
  34623. * The bottom plane of the camera's frustum.
  34624. *
  34625. * @type {number}
  34626. * @default -1
  34627. */
  34628. this.bottom = bottom;
  34629. /**
  34630. * The camera's near plane. The valid range is greater than `0`
  34631. * and less than the current value of {@link OrthographicCamera#far}.
  34632. *
  34633. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34634. * valid value for an orthographic camera's near plane.
  34635. *
  34636. * @type {number}
  34637. * @default 0.1
  34638. */
  34639. this.near = near;
  34640. /**
  34641. * The camera's far plane. Must be greater than the
  34642. * current value of {@link OrthographicCamera#near}.
  34643. *
  34644. * @type {number}
  34645. * @default 2000
  34646. */
  34647. this.far = far;
  34648. this.updateProjectionMatrix();
  34649. }
  34650. copy( source, recursive ) {
  34651. super.copy( source, recursive );
  34652. this.left = source.left;
  34653. this.right = source.right;
  34654. this.top = source.top;
  34655. this.bottom = source.bottom;
  34656. this.near = source.near;
  34657. this.far = source.far;
  34658. this.zoom = source.zoom;
  34659. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34660. return this;
  34661. }
  34662. /**
  34663. * Sets an offset in a larger frustum. This is useful for multi-window or
  34664. * multi-monitor/multi-machine setups.
  34665. *
  34666. * @param {number} fullWidth - The full width of multiview setup.
  34667. * @param {number} fullHeight - The full height of multiview setup.
  34668. * @param {number} x - The horizontal offset of the subcamera.
  34669. * @param {number} y - The vertical offset of the subcamera.
  34670. * @param {number} width - The width of subcamera.
  34671. * @param {number} height - The height of subcamera.
  34672. * @see {@link PerspectiveCamera#setViewOffset}
  34673. */
  34674. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34675. if ( this.view === null ) {
  34676. this.view = {
  34677. enabled: true,
  34678. fullWidth: 1,
  34679. fullHeight: 1,
  34680. offsetX: 0,
  34681. offsetY: 0,
  34682. width: 1,
  34683. height: 1
  34684. };
  34685. }
  34686. this.view.enabled = true;
  34687. this.view.fullWidth = fullWidth;
  34688. this.view.fullHeight = fullHeight;
  34689. this.view.offsetX = x;
  34690. this.view.offsetY = y;
  34691. this.view.width = width;
  34692. this.view.height = height;
  34693. this.updateProjectionMatrix();
  34694. }
  34695. /**
  34696. * Removes the view offset from the projection matrix.
  34697. */
  34698. clearViewOffset() {
  34699. if ( this.view !== null ) {
  34700. this.view.enabled = false;
  34701. }
  34702. this.updateProjectionMatrix();
  34703. }
  34704. /**
  34705. * Updates the camera's projection matrix. Must be called after any change of
  34706. * camera properties.
  34707. */
  34708. updateProjectionMatrix() {
  34709. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34710. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34711. const cx = ( this.right + this.left ) / 2;
  34712. const cy = ( this.top + this.bottom ) / 2;
  34713. let left = cx - dx;
  34714. let right = cx + dx;
  34715. let top = cy + dy;
  34716. let bottom = cy - dy;
  34717. if ( this.view !== null && this.view.enabled ) {
  34718. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34719. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34720. left += scaleW * this.view.offsetX;
  34721. right = left + scaleW * this.view.width;
  34722. top -= scaleH * this.view.offsetY;
  34723. bottom = top - scaleH * this.view.height;
  34724. }
  34725. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34726. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34727. }
  34728. toJSON( meta ) {
  34729. const data = super.toJSON( meta );
  34730. data.object.zoom = this.zoom;
  34731. data.object.left = this.left;
  34732. data.object.right = this.right;
  34733. data.object.top = this.top;
  34734. data.object.bottom = this.bottom;
  34735. data.object.near = this.near;
  34736. data.object.far = this.far;
  34737. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34738. return data;
  34739. }
  34740. }
  34741. /**
  34742. * Represents the shadow configuration of directional lights.
  34743. *
  34744. * @augments LightShadow
  34745. */
  34746. class DirectionalLightShadow extends LightShadow {
  34747. /**
  34748. * Constructs a new directional light shadow.
  34749. */
  34750. constructor() {
  34751. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34752. /**
  34753. * This flag can be used for type testing.
  34754. *
  34755. * @type {boolean}
  34756. * @readonly
  34757. * @default true
  34758. */
  34759. this.isDirectionalLightShadow = true;
  34760. }
  34761. }
  34762. /**
  34763. * A light that gets emitted in a specific direction. This light will behave
  34764. * as though it is infinitely far away and the rays produced from it are all
  34765. * parallel. The common use case for this is to simulate daylight; the sun is
  34766. * far enough away that its position can be considered to be infinite, and
  34767. * all light rays coming from it are parallel.
  34768. *
  34769. * A common point of confusion for directional lights is that setting the
  34770. * rotation has no effect. This is because three.js's DirectionalLight is the
  34771. * equivalent to what is often called a 'Target Direct Light' in other
  34772. * applications.
  34773. *
  34774. * This means that its direction is calculated as pointing from the light's
  34775. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34776. * (as opposed to a 'Free Direct Light' that just has a rotation
  34777. * component).
  34778. *
  34779. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34780. *
  34781. * ```js
  34782. * // White directional light at half intensity shining from the top.
  34783. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34784. * scene.add( directionalLight );
  34785. * ```
  34786. *
  34787. * @augments Light
  34788. */
  34789. class DirectionalLight extends Light {
  34790. /**
  34791. * Constructs a new directional light.
  34792. *
  34793. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34794. * @param {number} [intensity=1] - The light's strength/intensity.
  34795. */
  34796. constructor( color, intensity ) {
  34797. super( color, intensity );
  34798. /**
  34799. * This flag can be used for type testing.
  34800. *
  34801. * @type {boolean}
  34802. * @readonly
  34803. * @default true
  34804. */
  34805. this.isDirectionalLight = true;
  34806. this.type = 'DirectionalLight';
  34807. this.position.copy( Object3D.DEFAULT_UP );
  34808. this.updateMatrix();
  34809. /**
  34810. * The directional light points from its position to the
  34811. * target's position.
  34812. *
  34813. * For the target's position to be changed to anything other
  34814. * than the default, it must be added to the scene.
  34815. *
  34816. * It is also possible to set the target to be another 3D object
  34817. * in the scene. The light will now track the target object.
  34818. *
  34819. * @type {Object3D}
  34820. */
  34821. this.target = new Object3D();
  34822. /**
  34823. * This property holds the light's shadow configuration.
  34824. *
  34825. * @type {DirectionalLightShadow}
  34826. */
  34827. this.shadow = new DirectionalLightShadow();
  34828. }
  34829. dispose() {
  34830. super.dispose();
  34831. this.shadow.dispose();
  34832. }
  34833. copy( source ) {
  34834. super.copy( source );
  34835. this.target = source.target.clone();
  34836. this.shadow = source.shadow.clone();
  34837. return this;
  34838. }
  34839. toJSON( meta ) {
  34840. const data = super.toJSON( meta );
  34841. data.object.shadow = this.shadow.toJSON();
  34842. data.object.target = this.target.uuid;
  34843. return data;
  34844. }
  34845. }
  34846. /**
  34847. * This light globally illuminates all objects in the scene equally.
  34848. *
  34849. * It cannot be used to cast shadows as it does not have a direction.
  34850. *
  34851. * ```js
  34852. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34853. * scene.add( light );
  34854. * ```
  34855. *
  34856. * @augments Light
  34857. */
  34858. class AmbientLight extends Light {
  34859. /**
  34860. * Constructs a new ambient light.
  34861. *
  34862. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34863. * @param {number} [intensity=1] - The light's strength/intensity.
  34864. */
  34865. constructor( color, intensity ) {
  34866. super( color, intensity );
  34867. /**
  34868. * This flag can be used for type testing.
  34869. *
  34870. * @type {boolean}
  34871. * @readonly
  34872. * @default true
  34873. */
  34874. this.isAmbientLight = true;
  34875. this.type = 'AmbientLight';
  34876. }
  34877. }
  34878. /**
  34879. * This class emits light uniformly across the face a rectangular plane.
  34880. * This light type can be used to simulate light sources such as bright
  34881. * windows or strip lighting.
  34882. *
  34883. * Important Notes:
  34884. *
  34885. * - There is no shadow support.
  34886. * - Only PBR materials are supported.
  34887. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34888. * into your app and init the uniforms/textures.
  34889. *
  34890. * ```js
  34891. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34892. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34893. *
  34894. * const intensity = 1; const width = 10; const height = 10;
  34895. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34896. * rectLight.position.set( 5, 5, 0 );
  34897. * rectLight.lookAt( 0, 0, 0 );
  34898. * scene.add( rectLight )
  34899. * ```
  34900. *
  34901. * @augments Light
  34902. */
  34903. class RectAreaLight extends Light {
  34904. /**
  34905. * Constructs a new area light.
  34906. *
  34907. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34908. * @param {number} [intensity=1] - The light's strength/intensity.
  34909. * @param {number} [width=10] - The width of the light.
  34910. * @param {number} [height=10] - The height of the light.
  34911. */
  34912. constructor( color, intensity, width = 10, height = 10 ) {
  34913. super( color, intensity );
  34914. /**
  34915. * This flag can be used for type testing.
  34916. *
  34917. * @type {boolean}
  34918. * @readonly
  34919. * @default true
  34920. */
  34921. this.isRectAreaLight = true;
  34922. this.type = 'RectAreaLight';
  34923. /**
  34924. * The width of the light.
  34925. *
  34926. * @type {number}
  34927. * @default 10
  34928. */
  34929. this.width = width;
  34930. /**
  34931. * The height of the light.
  34932. *
  34933. * @type {number}
  34934. * @default 10
  34935. */
  34936. this.height = height;
  34937. }
  34938. /**
  34939. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34940. * Changing the power will also change the light's intensity.
  34941. *
  34942. * @type {number}
  34943. */
  34944. get power() {
  34945. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34946. return this.intensity * this.width * this.height * Math.PI;
  34947. }
  34948. set power( power ) {
  34949. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34950. this.intensity = power / ( this.width * this.height * Math.PI );
  34951. }
  34952. copy( source ) {
  34953. super.copy( source );
  34954. this.width = source.width;
  34955. this.height = source.height;
  34956. return this;
  34957. }
  34958. toJSON( meta ) {
  34959. const data = super.toJSON( meta );
  34960. data.object.width = this.width;
  34961. data.object.height = this.height;
  34962. return data;
  34963. }
  34964. }
  34965. /**
  34966. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34967. * to encode lighting information.
  34968. *
  34969. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34970. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34971. */
  34972. class SphericalHarmonics3 {
  34973. /**
  34974. * Constructs a new spherical harmonics.
  34975. */
  34976. constructor() {
  34977. /**
  34978. * This flag can be used for type testing.
  34979. *
  34980. * @type {boolean}
  34981. * @readonly
  34982. * @default true
  34983. */
  34984. this.isSphericalHarmonics3 = true;
  34985. /**
  34986. * An array holding the (9) SH coefficients.
  34987. *
  34988. * @type {Array<Vector3>}
  34989. */
  34990. this.coefficients = [];
  34991. for ( let i = 0; i < 9; i ++ ) {
  34992. this.coefficients.push( new Vector3() );
  34993. }
  34994. }
  34995. /**
  34996. * Sets the given SH coefficients to this instance by copying
  34997. * the values.
  34998. *
  34999. * @param {Array<Vector3>} coefficients - The SH coefficients.
  35000. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35001. */
  35002. set( coefficients ) {
  35003. for ( let i = 0; i < 9; i ++ ) {
  35004. this.coefficients[ i ].copy( coefficients[ i ] );
  35005. }
  35006. return this;
  35007. }
  35008. /**
  35009. * Sets all SH coefficients to `0`.
  35010. *
  35011. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35012. */
  35013. zero() {
  35014. for ( let i = 0; i < 9; i ++ ) {
  35015. this.coefficients[ i ].set( 0, 0, 0 );
  35016. }
  35017. return this;
  35018. }
  35019. /**
  35020. * Returns the radiance in the direction of the given normal.
  35021. *
  35022. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  35023. * @param {Vector3} target - The target vector that is used to store the method's result.
  35024. * @return {Vector3} The radiance.
  35025. */
  35026. getAt( normal, target ) {
  35027. // normal is assumed to be unit length
  35028. const x = normal.x, y = normal.y, z = normal.z;
  35029. const coeff = this.coefficients;
  35030. // band 0
  35031. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  35032. // band 1
  35033. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  35034. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  35035. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  35036. // band 2
  35037. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  35038. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  35039. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  35040. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  35041. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  35042. return target;
  35043. }
  35044. /**
  35045. * Returns the irradiance (radiance convolved with cosine lobe) in the
  35046. * direction of the given normal.
  35047. *
  35048. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  35049. * @param {Vector3} target - The target vector that is used to store the method's result.
  35050. * @return {Vector3} The irradiance.
  35051. */
  35052. getIrradianceAt( normal, target ) {
  35053. // normal is assumed to be unit length
  35054. const x = normal.x, y = normal.y, z = normal.z;
  35055. const coeff = this.coefficients;
  35056. // band 0
  35057. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  35058. // band 1
  35059. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  35060. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  35061. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  35062. // band 2
  35063. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  35064. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  35065. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  35066. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  35067. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  35068. return target;
  35069. }
  35070. /**
  35071. * Adds the given SH to this instance.
  35072. *
  35073. * @param {SphericalHarmonics3} sh - The SH to add.
  35074. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35075. */
  35076. add( sh ) {
  35077. for ( let i = 0; i < 9; i ++ ) {
  35078. this.coefficients[ i ].add( sh.coefficients[ i ] );
  35079. }
  35080. return this;
  35081. }
  35082. /**
  35083. * A convenience method for performing {@link SphericalHarmonics3#add} and
  35084. * {@link SphericalHarmonics3#scale} at once.
  35085. *
  35086. * @param {SphericalHarmonics3} sh - The SH to add.
  35087. * @param {number} s - The scale factor.
  35088. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35089. */
  35090. addScaledSH( sh, s ) {
  35091. for ( let i = 0; i < 9; i ++ ) {
  35092. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  35093. }
  35094. return this;
  35095. }
  35096. /**
  35097. * Scales this SH by the given scale factor.
  35098. *
  35099. * @param {number} s - The scale factor.
  35100. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35101. */
  35102. scale( s ) {
  35103. for ( let i = 0; i < 9; i ++ ) {
  35104. this.coefficients[ i ].multiplyScalar( s );
  35105. }
  35106. return this;
  35107. }
  35108. /**
  35109. * Linear interpolates between the given SH and this instance by the given
  35110. * alpha factor.
  35111. *
  35112. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  35113. * @param {number} alpha - The alpha factor.
  35114. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35115. */
  35116. lerp( sh, alpha ) {
  35117. for ( let i = 0; i < 9; i ++ ) {
  35118. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  35119. }
  35120. return this;
  35121. }
  35122. /**
  35123. * Returns `true` if this spherical harmonics is equal with the given one.
  35124. *
  35125. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  35126. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  35127. */
  35128. equals( sh ) {
  35129. for ( let i = 0; i < 9; i ++ ) {
  35130. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  35131. return false;
  35132. }
  35133. }
  35134. return true;
  35135. }
  35136. /**
  35137. * Copies the values of the given spherical harmonics to this instance.
  35138. *
  35139. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  35140. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  35141. */
  35142. copy( sh ) {
  35143. return this.set( sh.coefficients );
  35144. }
  35145. /**
  35146. * Returns a new spherical harmonics with copied values from this instance.
  35147. *
  35148. * @return {SphericalHarmonics3} A clone of this instance.
  35149. */
  35150. clone() {
  35151. return new this.constructor().copy( this );
  35152. }
  35153. /**
  35154. * Sets the SH coefficients of this instance from the given array.
  35155. *
  35156. * @param {Array<number>} array - An array holding the SH coefficients.
  35157. * @param {number} [offset=0] - The array offset where to start copying.
  35158. * @return {SphericalHarmonics3} A clone of this instance.
  35159. */
  35160. fromArray( array, offset = 0 ) {
  35161. const coefficients = this.coefficients;
  35162. for ( let i = 0; i < 9; i ++ ) {
  35163. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  35164. }
  35165. return this;
  35166. }
  35167. /**
  35168. * Returns an array with the SH coefficients, or copies them into the provided
  35169. * array. The coefficients are represented as numbers.
  35170. *
  35171. * @param {Array<number>} [array=[]] - The target array.
  35172. * @param {number} [offset=0] - The array offset where to start copying.
  35173. * @return {Array<number>} An array with flat SH coefficients.
  35174. */
  35175. toArray( array = [], offset = 0 ) {
  35176. const coefficients = this.coefficients;
  35177. for ( let i = 0; i < 9; i ++ ) {
  35178. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  35179. }
  35180. return array;
  35181. }
  35182. /**
  35183. * Computes the SH basis for the given normal vector.
  35184. *
  35185. * @param {Vector3} normal - The normal.
  35186. * @param {Array<number>} shBasis - The target array holding the SH basis.
  35187. */
  35188. static getBasisAt( normal, shBasis ) {
  35189. // normal is assumed to be unit length
  35190. const x = normal.x, y = normal.y, z = normal.z;
  35191. // band 0
  35192. shBasis[ 0 ] = 0.282095;
  35193. // band 1
  35194. shBasis[ 1 ] = 0.488603 * y;
  35195. shBasis[ 2 ] = 0.488603 * z;
  35196. shBasis[ 3 ] = 0.488603 * x;
  35197. // band 2
  35198. shBasis[ 4 ] = 1.092548 * x * y;
  35199. shBasis[ 5 ] = 1.092548 * y * z;
  35200. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  35201. shBasis[ 7 ] = 1.092548 * x * z;
  35202. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  35203. }
  35204. }
  35205. /**
  35206. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  35207. * classical light sources (e.g. directional, point or spot lights), light
  35208. * probes do not emit light. Instead they store information about light
  35209. * passing through 3D space. During rendering, the light that hits a 3D
  35210. * object is approximated by using the data from the light probe.
  35211. *
  35212. * Light probes are usually created from (radiance) environment maps. The
  35213. * class {@link LightProbeGenerator} can be used to create light probes from
  35214. * cube textures or render targets. However, light estimation data could also
  35215. * be provided in other forms e.g. by WebXR. This enables the rendering of
  35216. * augmented reality content that reacts to real world lighting.
  35217. *
  35218. * The current probe implementation in three.js supports so-called diffuse
  35219. * light probes. This type of light probe is functionally equivalent to an
  35220. * irradiance environment map.
  35221. *
  35222. * @augments Light
  35223. */
  35224. class LightProbe extends Light {
  35225. /**
  35226. * Constructs a new light probe.
  35227. *
  35228. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  35229. * @param {number} [intensity=1] - The light's strength/intensity.
  35230. */
  35231. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  35232. super( undefined, intensity );
  35233. /**
  35234. * This flag can be used for type testing.
  35235. *
  35236. * @type {boolean}
  35237. * @readonly
  35238. * @default true
  35239. */
  35240. this.isLightProbe = true;
  35241. /**
  35242. * A light probe uses spherical harmonics to encode lighting information.
  35243. *
  35244. * @type {SphericalHarmonics3}
  35245. */
  35246. this.sh = sh;
  35247. }
  35248. copy( source ) {
  35249. super.copy( source );
  35250. this.sh.copy( source.sh );
  35251. return this;
  35252. }
  35253. toJSON( meta ) {
  35254. const data = super.toJSON( meta );
  35255. data.object.sh = this.sh.toArray();
  35256. return data;
  35257. }
  35258. }
  35259. const _customMaterials = {};
  35260. /**
  35261. * Class for loading materials. The files are internally
  35262. * loaded via {@link FileLoader}.
  35263. *
  35264. * ```js
  35265. * const loader = new THREE.MaterialLoader();
  35266. * const material = await loader.loadAsync( 'material.json' );
  35267. * ```
  35268. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  35269. *
  35270. * @augments Loader
  35271. */
  35272. class MaterialLoader extends Loader {
  35273. /**
  35274. * Constructs a new material loader.
  35275. *
  35276. * @param {LoadingManager} [manager] - The loading manager.
  35277. */
  35278. constructor( manager ) {
  35279. super( manager );
  35280. /**
  35281. * A dictionary holding textures used by the material.
  35282. *
  35283. * @type {Object<string,Texture>}
  35284. */
  35285. this.textures = {};
  35286. }
  35287. /**
  35288. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  35289. *
  35290. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35291. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  35292. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35293. * @param {onErrorCallback} onError - Executed when errors occur.
  35294. */
  35295. load( url, onLoad, onProgress, onError ) {
  35296. const scope = this;
  35297. const loader = new FileLoader( scope.manager );
  35298. loader.setPath( scope.path );
  35299. loader.setRequestHeader( scope.requestHeader );
  35300. loader.setWithCredentials( scope.withCredentials );
  35301. loader.load( url, function ( text ) {
  35302. try {
  35303. onLoad( scope.parse( JSON.parse( text ) ) );
  35304. } catch ( e ) {
  35305. if ( onError ) {
  35306. onError( e );
  35307. } else {
  35308. error( e );
  35309. }
  35310. scope.manager.itemError( url );
  35311. }
  35312. }, onProgress, onError );
  35313. }
  35314. /**
  35315. * Parses the given JSON object and returns a material.
  35316. *
  35317. * @param {Object} json - The serialized material.
  35318. * @return {Material} The parsed material.
  35319. */
  35320. parse( json ) {
  35321. const material = this.createMaterialFromType( json.type );
  35322. material.fromJSON( json, this.textures );
  35323. return material;
  35324. }
  35325. /**
  35326. * Textures are not embedded in the material JSON so they have
  35327. * to be injected before the loading process starts.
  35328. *
  35329. * @param {Object} value - A dictionary holding textures for material properties.
  35330. * @return {MaterialLoader} A reference to this material loader.
  35331. */
  35332. setTextures( value ) {
  35333. this.textures = value;
  35334. return this;
  35335. }
  35336. /**
  35337. * Creates a material for the given type.
  35338. *
  35339. * @param {string} type - The material type.
  35340. * @return {Material} The new material.
  35341. */
  35342. createMaterialFromType( type ) {
  35343. return MaterialLoader.createMaterialFromType( type );
  35344. }
  35345. /**
  35346. * Creates a material for the given type.
  35347. *
  35348. * @static
  35349. * @param {string} type - The material type.
  35350. * @return {Material} The new material.
  35351. */
  35352. static createMaterialFromType( type ) {
  35353. const materialLib = {
  35354. ShadowMaterial,
  35355. SpriteMaterial,
  35356. RawShaderMaterial,
  35357. ShaderMaterial,
  35358. PointsMaterial,
  35359. MeshPhysicalMaterial,
  35360. MeshStandardMaterial,
  35361. MeshPhongMaterial,
  35362. MeshToonMaterial,
  35363. MeshNormalMaterial,
  35364. MeshLambertMaterial,
  35365. MeshDepthMaterial,
  35366. MeshDistanceMaterial,
  35367. MeshBasicMaterial,
  35368. MeshMatcapMaterial,
  35369. LineDashedMaterial,
  35370. LineBasicMaterial,
  35371. Material,
  35372. ... _customMaterials
  35373. };
  35374. const MaterialType = materialLib[ type ];
  35375. let materialInstance;
  35376. if ( MaterialType === undefined ) {
  35377. warnOnce( `MaterialLoader: Unknown material type "${ type }". Use .registerMaterial() before starting the deserialization process.` );
  35378. materialInstance = new Material();
  35379. } else {
  35380. materialInstance = new MaterialType();
  35381. }
  35382. return materialInstance;
  35383. }
  35384. /**
  35385. * Registers the given material at the internal
  35386. * material library.
  35387. *
  35388. * @static
  35389. * @param {string} type - The material type.
  35390. * @param {Material.constructor} materialClass - The material class.
  35391. */
  35392. static registerMaterial( type, materialClass ) {
  35393. _customMaterials[ type ] = materialClass;
  35394. }
  35395. }
  35396. /**
  35397. * A class with loader utility functions.
  35398. */
  35399. class LoaderUtils {
  35400. /**
  35401. * Extracts the base URL from the given URL.
  35402. *
  35403. * @param {string} url -The URL to extract the base URL from.
  35404. * @return {string} The extracted base URL.
  35405. */
  35406. static extractUrlBase( url ) {
  35407. const index = url.lastIndexOf( '/' );
  35408. if ( index === -1 ) return './';
  35409. return url.slice( 0, index + 1 );
  35410. }
  35411. /**
  35412. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35413. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35414. * string.
  35415. *
  35416. * @param {string} url -The URL to resolve.
  35417. * @param {string} path - The base path for relative URLs to be resolved against.
  35418. * @return {string} The resolved URL.
  35419. */
  35420. static resolveURL( url, path ) {
  35421. // Invalid URL
  35422. if ( typeof url !== 'string' || url === '' ) return '';
  35423. // Host Relative URL
  35424. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35425. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35426. }
  35427. // Absolute URL http://,https://,//
  35428. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35429. // Data URI
  35430. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35431. // Blob URL
  35432. if ( /^blob:.*$/i.test( url ) ) return url;
  35433. // Relative URL
  35434. return path + url;
  35435. }
  35436. }
  35437. /**
  35438. * An instanced version of a geometry.
  35439. */
  35440. class InstancedBufferGeometry extends BufferGeometry {
  35441. /**
  35442. * Constructs a new instanced buffer geometry.
  35443. */
  35444. constructor() {
  35445. super();
  35446. /**
  35447. * This flag can be used for type testing.
  35448. *
  35449. * @type {boolean}
  35450. * @readonly
  35451. * @default true
  35452. */
  35453. this.isInstancedBufferGeometry = true;
  35454. this.type = 'InstancedBufferGeometry';
  35455. /**
  35456. * The instance count.
  35457. *
  35458. * @type {number}
  35459. * @default Infinity
  35460. */
  35461. this.instanceCount = Infinity;
  35462. }
  35463. copy( source ) {
  35464. super.copy( source );
  35465. this.instanceCount = source.instanceCount;
  35466. return this;
  35467. }
  35468. toJSON() {
  35469. const data = super.toJSON();
  35470. data.instanceCount = this.instanceCount;
  35471. data.isInstancedBufferGeometry = true;
  35472. return data;
  35473. }
  35474. }
  35475. /**
  35476. * Class for loading geometries. The files are internally
  35477. * loaded via {@link FileLoader}.
  35478. *
  35479. * ```js
  35480. * const loader = new THREE.BufferGeometryLoader();
  35481. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35482. *
  35483. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35484. * const object = new THREE.Mesh( geometry, material );
  35485. * scene.add( object );
  35486. * ```
  35487. *
  35488. * @augments Loader
  35489. */
  35490. class BufferGeometryLoader extends Loader {
  35491. /**
  35492. * Constructs a new geometry loader.
  35493. *
  35494. * @param {LoadingManager} [manager] - The loading manager.
  35495. */
  35496. constructor( manager ) {
  35497. super( manager );
  35498. }
  35499. /**
  35500. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35501. *
  35502. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35503. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35504. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35505. * @param {onErrorCallback} onError - Executed when errors occur.
  35506. */
  35507. load( url, onLoad, onProgress, onError ) {
  35508. const scope = this;
  35509. const loader = new FileLoader( scope.manager );
  35510. loader.setPath( scope.path );
  35511. loader.setRequestHeader( scope.requestHeader );
  35512. loader.setWithCredentials( scope.withCredentials );
  35513. loader.load( url, function ( text ) {
  35514. try {
  35515. onLoad( scope.parse( JSON.parse( text ) ) );
  35516. } catch ( e ) {
  35517. if ( onError ) {
  35518. onError( e );
  35519. } else {
  35520. error( e );
  35521. }
  35522. scope.manager.itemError( url );
  35523. }
  35524. }, onProgress, onError );
  35525. }
  35526. /**
  35527. * Parses the given JSON object and returns a geometry.
  35528. *
  35529. * @param {Object} json - The serialized geometry.
  35530. * @return {BufferGeometry} The parsed geometry.
  35531. */
  35532. parse( json ) {
  35533. const interleavedBufferMap = {};
  35534. const arrayBufferMap = {};
  35535. function getInterleavedBuffer( json, uuid ) {
  35536. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35537. const interleavedBuffers = json.interleavedBuffers;
  35538. const interleavedBuffer = interleavedBuffers[ uuid ];
  35539. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35540. const array = getTypedArray( interleavedBuffer.type, buffer );
  35541. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35542. ib.uuid = interleavedBuffer.uuid;
  35543. interleavedBufferMap[ uuid ] = ib;
  35544. return ib;
  35545. }
  35546. function getArrayBuffer( json, uuid ) {
  35547. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35548. const arrayBuffers = json.arrayBuffers;
  35549. const arrayBuffer = arrayBuffers[ uuid ];
  35550. const ab = new Uint32Array( arrayBuffer ).buffer;
  35551. arrayBufferMap[ uuid ] = ab;
  35552. return ab;
  35553. }
  35554. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35555. const index = json.data.index;
  35556. if ( index !== undefined ) {
  35557. const typedArray = getTypedArray( index.type, index.array );
  35558. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35559. }
  35560. const attributes = json.data.attributes;
  35561. for ( const key in attributes ) {
  35562. const attribute = attributes[ key ];
  35563. let bufferAttribute;
  35564. if ( attribute.isInterleavedBufferAttribute ) {
  35565. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35566. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35567. } else {
  35568. const typedArray = getTypedArray( attribute.type, attribute.array );
  35569. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35570. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35571. }
  35572. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35573. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35574. geometry.setAttribute( key, bufferAttribute );
  35575. }
  35576. const morphAttributes = json.data.morphAttributes;
  35577. if ( morphAttributes ) {
  35578. for ( const key in morphAttributes ) {
  35579. const attributeArray = morphAttributes[ key ];
  35580. const array = [];
  35581. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35582. const attribute = attributeArray[ i ];
  35583. let bufferAttribute;
  35584. if ( attribute.isInterleavedBufferAttribute ) {
  35585. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35586. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35587. } else {
  35588. const typedArray = getTypedArray( attribute.type, attribute.array );
  35589. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35590. }
  35591. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35592. array.push( bufferAttribute );
  35593. }
  35594. geometry.morphAttributes[ key ] = array;
  35595. }
  35596. }
  35597. const morphTargetsRelative = json.data.morphTargetsRelative;
  35598. if ( morphTargetsRelative ) {
  35599. geometry.morphTargetsRelative = true;
  35600. }
  35601. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35602. if ( groups !== undefined ) {
  35603. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35604. const group = groups[ i ];
  35605. geometry.addGroup( group.start, group.count, group.materialIndex );
  35606. }
  35607. }
  35608. const boundingSphere = json.data.boundingSphere;
  35609. if ( boundingSphere !== undefined ) {
  35610. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35611. }
  35612. if ( json.name ) geometry.name = json.name;
  35613. if ( json.userData ) geometry.userData = json.userData;
  35614. return geometry;
  35615. }
  35616. }
  35617. const _customGeometries = {};
  35618. /**
  35619. * 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).
  35620. * The files are internally loaded via {@link FileLoader}.
  35621. *
  35622. * ```js
  35623. * const loader = new THREE.ObjectLoader();
  35624. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35625. * scene.add( obj );
  35626. *
  35627. * // Alternatively, to parse a previously loaded JSON structure
  35628. * const object = await loader.parseAsync( a_json_object );
  35629. * scene.add( object );
  35630. * ```
  35631. *
  35632. * @augments Loader
  35633. */
  35634. class ObjectLoader extends Loader {
  35635. /**
  35636. * Constructs a new object loader.
  35637. *
  35638. * @param {LoadingManager} [manager] - The loading manager.
  35639. */
  35640. constructor( manager ) {
  35641. super( manager );
  35642. }
  35643. /**
  35644. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35645. *
  35646. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35647. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35648. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35649. * @param {onErrorCallback} onError - Executed when errors occur.
  35650. */
  35651. load( url, onLoad, onProgress, onError ) {
  35652. const scope = this;
  35653. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35654. this.resourcePath = this.resourcePath || path;
  35655. const loader = new FileLoader( this.manager );
  35656. loader.setPath( this.path );
  35657. loader.setRequestHeader( this.requestHeader );
  35658. loader.setWithCredentials( this.withCredentials );
  35659. loader.load( url, function ( text ) {
  35660. let json = null;
  35661. try {
  35662. json = JSON.parse( text );
  35663. } catch ( e ) {
  35664. if ( onError !== undefined ) onError( e );
  35665. error( 'ObjectLoader: Can\'t parse ' + url + '.', e.message );
  35666. return;
  35667. }
  35668. const metadata = json.metadata;
  35669. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35670. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35671. error( 'ObjectLoader: Can\'t load ' + url );
  35672. return;
  35673. }
  35674. scope.parse( json, onLoad );
  35675. }, onProgress, onError );
  35676. }
  35677. /**
  35678. * Async version of {@link ObjectLoader#load}.
  35679. *
  35680. * @async
  35681. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35682. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35683. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35684. */
  35685. async loadAsync( url, onProgress ) {
  35686. const scope = this;
  35687. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35688. this.resourcePath = this.resourcePath || path;
  35689. const loader = new FileLoader( this.manager );
  35690. loader.setPath( this.path );
  35691. loader.setRequestHeader( this.requestHeader );
  35692. loader.setWithCredentials( this.withCredentials );
  35693. const text = await loader.loadAsync( url, onProgress );
  35694. let json;
  35695. try {
  35696. json = JSON.parse( text );
  35697. } catch ( e ) {
  35698. throw new Error( 'THREE.ObjectLoader: Can\'t parse ' + url + '. ' + e.message );
  35699. }
  35700. const metadata = json.metadata;
  35701. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35702. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35703. }
  35704. return await scope.parseAsync( json );
  35705. }
  35706. /**
  35707. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35708. * but can also be used directly to parse a previously loaded JSON structure.
  35709. *
  35710. * @param {Object} json - The serialized 3D object.
  35711. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35712. * @return {Object3D} The parsed 3D object.
  35713. */
  35714. parse( json, onLoad ) {
  35715. const animations = this.parseAnimations( json.animations );
  35716. const shapes = this.parseShapes( json.shapes );
  35717. const geometries = this.parseGeometries( json.geometries, shapes );
  35718. const images = this.parseImages( json.images, function () {
  35719. if ( onLoad !== undefined ) onLoad( object );
  35720. } );
  35721. const textures = this.parseTextures( json.textures, images );
  35722. const materials = this.parseMaterials( json.materials, textures );
  35723. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35724. const skeletons = this.parseSkeletons( json.skeletons, object );
  35725. this.bindSkeletons( object, skeletons );
  35726. this.bindLightTargets( object );
  35727. //
  35728. if ( onLoad !== undefined ) {
  35729. let hasImages = false;
  35730. for ( const uuid in images ) {
  35731. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35732. hasImages = true;
  35733. break;
  35734. }
  35735. }
  35736. if ( hasImages === false ) onLoad( object );
  35737. }
  35738. return object;
  35739. }
  35740. /**
  35741. * Async version of {@link ObjectLoader#parse}.
  35742. *
  35743. * @param {Object} json - The serialized 3D object.
  35744. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35745. */
  35746. async parseAsync( json ) {
  35747. const animations = this.parseAnimations( json.animations );
  35748. const shapes = this.parseShapes( json.shapes );
  35749. const geometries = this.parseGeometries( json.geometries, shapes );
  35750. const images = await this.parseImagesAsync( json.images );
  35751. const textures = this.parseTextures( json.textures, images );
  35752. const materials = this.parseMaterials( json.materials, textures );
  35753. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35754. const skeletons = this.parseSkeletons( json.skeletons, object );
  35755. this.bindSkeletons( object, skeletons );
  35756. this.bindLightTargets( object );
  35757. return object;
  35758. }
  35759. /**
  35760. * Registers the given geometry at the internal
  35761. * geometry library.
  35762. *
  35763. * @static
  35764. * @param {string} type - The geometry type.
  35765. * @param {BufferGeometry.constructor} geometryClass - The geometry class.
  35766. */
  35767. static registerGeometry( type, geometryClass ) {
  35768. _customGeometries[ type ] = geometryClass;
  35769. }
  35770. // internals
  35771. parseShapes( json ) {
  35772. const shapes = {};
  35773. if ( json !== undefined ) {
  35774. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35775. const shape = new Shape().fromJSON( json[ i ] );
  35776. shapes[ shape.uuid ] = shape;
  35777. }
  35778. }
  35779. return shapes;
  35780. }
  35781. parseSkeletons( json, object ) {
  35782. const skeletons = {};
  35783. const bones = {};
  35784. // generate bone lookup table
  35785. object.traverse( function ( child ) {
  35786. if ( child.isBone ) bones[ child.uuid ] = child;
  35787. } );
  35788. // create skeletons
  35789. if ( json !== undefined ) {
  35790. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35791. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35792. skeletons[ skeleton.uuid ] = skeleton;
  35793. }
  35794. }
  35795. return skeletons;
  35796. }
  35797. parseGeometries( json, shapes ) {
  35798. const geometries = {};
  35799. if ( json !== undefined ) {
  35800. const bufferGeometryLoader = new BufferGeometryLoader();
  35801. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35802. let geometry;
  35803. const data = json[ i ];
  35804. switch ( data.type ) {
  35805. case 'BufferGeometry':
  35806. case 'InstancedBufferGeometry':
  35807. geometry = bufferGeometryLoader.parse( data );
  35808. break;
  35809. default:
  35810. if ( data.type in Geometries ) {
  35811. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35812. } else if ( data.type in _customGeometries ) {
  35813. geometry = _customGeometries[ data.type ].fromJSON( data, shapes );
  35814. } else {
  35815. warn( `ObjectLoader: Unknown geometry type "${ data.type }". Use .registerGeometry() before starting the deserialization process.` );
  35816. }
  35817. }
  35818. geometry.uuid = data.uuid;
  35819. if ( data.name !== undefined ) geometry.name = data.name;
  35820. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35821. geometries[ data.uuid ] = geometry;
  35822. }
  35823. }
  35824. return geometries;
  35825. }
  35826. parseMaterials( json, textures ) {
  35827. const cache = {}; // MultiMaterial
  35828. const materials = {};
  35829. if ( json !== undefined ) {
  35830. const loader = new MaterialLoader();
  35831. loader.setTextures( textures );
  35832. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35833. const data = json[ i ];
  35834. if ( cache[ data.uuid ] === undefined ) {
  35835. cache[ data.uuid ] = loader.parse( data );
  35836. }
  35837. materials[ data.uuid ] = cache[ data.uuid ];
  35838. }
  35839. }
  35840. return materials;
  35841. }
  35842. parseAnimations( json ) {
  35843. const animations = {};
  35844. if ( json !== undefined ) {
  35845. for ( let i = 0; i < json.length; i ++ ) {
  35846. const data = json[ i ];
  35847. const clip = AnimationClip.parse( data );
  35848. animations[ clip.uuid ] = clip;
  35849. }
  35850. }
  35851. return animations;
  35852. }
  35853. parseImages( json, onLoad ) {
  35854. const scope = this;
  35855. const images = {};
  35856. let loader;
  35857. function loadImage( url ) {
  35858. url = scope.manager.resolveURL( url );
  35859. scope.manager.itemStart( url );
  35860. return loader.load( url, function () {
  35861. scope.manager.itemEnd( url );
  35862. }, undefined, function () {
  35863. scope.manager.itemError( url );
  35864. scope.manager.itemEnd( url );
  35865. } );
  35866. }
  35867. function deserializeImage( image ) {
  35868. if ( typeof image === 'string' ) {
  35869. const url = image;
  35870. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35871. return loadImage( path );
  35872. } else {
  35873. if ( image.data ) {
  35874. return {
  35875. data: getTypedArray( image.type, image.data ),
  35876. width: image.width,
  35877. height: image.height
  35878. };
  35879. } else {
  35880. return null;
  35881. }
  35882. }
  35883. }
  35884. if ( json !== undefined && json.length > 0 ) {
  35885. const manager = new LoadingManager( onLoad );
  35886. loader = new ImageLoader( manager );
  35887. loader.setCrossOrigin( this.crossOrigin );
  35888. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35889. const image = json[ i ];
  35890. const url = image.url;
  35891. if ( Array.isArray( url ) ) {
  35892. // load array of images e.g CubeTexture
  35893. const imageArray = [];
  35894. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35895. const currentUrl = url[ j ];
  35896. const deserializedImage = deserializeImage( currentUrl );
  35897. if ( deserializedImage !== null ) {
  35898. if ( deserializedImage instanceof HTMLImageElement ) {
  35899. imageArray.push( deserializedImage );
  35900. } else {
  35901. // special case: handle array of data textures for cube textures
  35902. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35903. }
  35904. }
  35905. }
  35906. images[ image.uuid ] = new Source( imageArray );
  35907. } else {
  35908. // load single image
  35909. const deserializedImage = deserializeImage( image.url );
  35910. images[ image.uuid ] = new Source( deserializedImage );
  35911. }
  35912. }
  35913. }
  35914. return images;
  35915. }
  35916. async parseImagesAsync( json ) {
  35917. const scope = this;
  35918. const images = {};
  35919. let loader;
  35920. async function deserializeImage( image ) {
  35921. if ( typeof image === 'string' ) {
  35922. const url = image;
  35923. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35924. return await loader.loadAsync( path );
  35925. } else {
  35926. if ( image.data ) {
  35927. return {
  35928. data: getTypedArray( image.type, image.data ),
  35929. width: image.width,
  35930. height: image.height
  35931. };
  35932. } else {
  35933. return null;
  35934. }
  35935. }
  35936. }
  35937. if ( json !== undefined && json.length > 0 ) {
  35938. loader = new ImageLoader( this.manager );
  35939. loader.setCrossOrigin( this.crossOrigin );
  35940. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35941. const image = json[ i ];
  35942. const url = image.url;
  35943. if ( Array.isArray( url ) ) {
  35944. // load array of images e.g CubeTexture
  35945. const imageArray = [];
  35946. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35947. const currentUrl = url[ j ];
  35948. const deserializedImage = await deserializeImage( currentUrl );
  35949. if ( deserializedImage !== null ) {
  35950. if ( deserializedImage instanceof HTMLImageElement ) {
  35951. imageArray.push( deserializedImage );
  35952. } else {
  35953. // special case: handle array of data textures for cube textures
  35954. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35955. }
  35956. }
  35957. }
  35958. images[ image.uuid ] = new Source( imageArray );
  35959. } else {
  35960. // load single image
  35961. const deserializedImage = await deserializeImage( image.url );
  35962. images[ image.uuid ] = new Source( deserializedImage );
  35963. }
  35964. }
  35965. }
  35966. return images;
  35967. }
  35968. parseTextures( json, images ) {
  35969. function parseConstant( value, type ) {
  35970. if ( typeof value === 'number' ) return value;
  35971. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35972. return type[ value ];
  35973. }
  35974. const textures = {};
  35975. if ( json !== undefined ) {
  35976. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35977. const data = json[ i ];
  35978. if ( data.image === undefined ) {
  35979. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35980. }
  35981. if ( images[ data.image ] === undefined ) {
  35982. warn( 'ObjectLoader: Undefined image', data.image );
  35983. }
  35984. const source = images[ data.image ];
  35985. const image = source.data;
  35986. let texture;
  35987. if ( Array.isArray( image ) ) {
  35988. texture = new CubeTexture();
  35989. if ( image.length === 6 ) texture.needsUpdate = true;
  35990. } else {
  35991. if ( image && image.data ) {
  35992. texture = new DataTexture();
  35993. } else {
  35994. texture = new Texture();
  35995. }
  35996. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35997. }
  35998. texture.source = source;
  35999. texture.uuid = data.uuid;
  36000. if ( data.name !== undefined ) texture.name = data.name;
  36001. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  36002. if ( data.channel !== undefined ) texture.channel = data.channel;
  36003. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  36004. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  36005. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  36006. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  36007. if ( data.wrap !== undefined ) {
  36008. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  36009. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  36010. }
  36011. if ( data.format !== undefined ) texture.format = data.format;
  36012. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  36013. if ( data.type !== undefined ) texture.type = data.type;
  36014. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  36015. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  36016. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  36017. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  36018. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  36019. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  36020. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  36021. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  36022. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  36023. if ( data.normalized !== undefined ) texture.normalized = data.normalized;
  36024. if ( data.userData !== undefined ) texture.userData = data.userData;
  36025. textures[ data.uuid ] = texture;
  36026. }
  36027. }
  36028. return textures;
  36029. }
  36030. parseObject( data, geometries, materials, textures, animations ) {
  36031. let object;
  36032. function getGeometry( name ) {
  36033. if ( geometries[ name ] === undefined ) {
  36034. warn( 'ObjectLoader: Undefined geometry', name );
  36035. }
  36036. return geometries[ name ];
  36037. }
  36038. function getMaterial( name ) {
  36039. if ( name === undefined ) return undefined;
  36040. if ( Array.isArray( name ) ) {
  36041. const array = [];
  36042. for ( let i = 0, l = name.length; i < l; i ++ ) {
  36043. const uuid = name[ i ];
  36044. if ( materials[ uuid ] === undefined ) {
  36045. warn( 'ObjectLoader: Undefined material', uuid );
  36046. }
  36047. array.push( materials[ uuid ] );
  36048. }
  36049. return array;
  36050. }
  36051. if ( materials[ name ] === undefined ) {
  36052. warn( 'ObjectLoader: Undefined material', name );
  36053. }
  36054. return materials[ name ];
  36055. }
  36056. function getTexture( uuid ) {
  36057. if ( textures[ uuid ] === undefined ) {
  36058. warn( 'ObjectLoader: Undefined texture', uuid );
  36059. }
  36060. return textures[ uuid ];
  36061. }
  36062. let geometry, material;
  36063. switch ( data.type ) {
  36064. case 'Scene':
  36065. object = new Scene();
  36066. if ( data.background !== undefined ) {
  36067. if ( Number.isInteger( data.background ) ) {
  36068. object.background = new Color( data.background );
  36069. } else {
  36070. object.background = getTexture( data.background );
  36071. }
  36072. }
  36073. if ( data.environment !== undefined ) {
  36074. object.environment = getTexture( data.environment );
  36075. }
  36076. if ( data.fog !== undefined ) {
  36077. if ( data.fog.type === 'Fog' ) {
  36078. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  36079. } else if ( data.fog.type === 'FogExp2' ) {
  36080. object.fog = new FogExp2( data.fog.color, data.fog.density );
  36081. }
  36082. if ( data.fog.name !== '' ) {
  36083. object.fog.name = data.fog.name;
  36084. }
  36085. }
  36086. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  36087. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  36088. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  36089. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  36090. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  36091. break;
  36092. case 'PerspectiveCamera':
  36093. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  36094. if ( data.focus !== undefined ) object.focus = data.focus;
  36095. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  36096. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  36097. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  36098. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  36099. break;
  36100. case 'OrthographicCamera':
  36101. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  36102. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  36103. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  36104. break;
  36105. case 'AmbientLight':
  36106. object = new AmbientLight( data.color, data.intensity );
  36107. break;
  36108. case 'DirectionalLight':
  36109. object = new DirectionalLight( data.color, data.intensity );
  36110. object.target = data.target || '';
  36111. break;
  36112. case 'PointLight':
  36113. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  36114. break;
  36115. case 'RectAreaLight':
  36116. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  36117. break;
  36118. case 'SpotLight':
  36119. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  36120. object.target = data.target || '';
  36121. break;
  36122. case 'HemisphereLight':
  36123. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  36124. break;
  36125. case 'LightProbe':
  36126. const sh = new SphericalHarmonics3().fromArray( data.sh );
  36127. object = new LightProbe( sh, data.intensity );
  36128. break;
  36129. case 'SkinnedMesh':
  36130. geometry = getGeometry( data.geometry );
  36131. material = getMaterial( data.material );
  36132. object = new SkinnedMesh( geometry, material );
  36133. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  36134. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  36135. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  36136. break;
  36137. case 'Mesh':
  36138. geometry = getGeometry( data.geometry );
  36139. material = getMaterial( data.material );
  36140. object = new Mesh( geometry, material );
  36141. break;
  36142. case 'InstancedMesh':
  36143. geometry = getGeometry( data.geometry );
  36144. material = getMaterial( data.material );
  36145. const count = data.count;
  36146. const instanceMatrix = data.instanceMatrix;
  36147. const instanceColor = data.instanceColor;
  36148. object = new InstancedMesh( geometry, material, count );
  36149. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  36150. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  36151. break;
  36152. case 'BatchedMesh':
  36153. geometry = getGeometry( data.geometry );
  36154. material = getMaterial( data.material );
  36155. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  36156. object.geometry = geometry;
  36157. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  36158. object.sortObjects = data.sortObjects;
  36159. object._drawRanges = data.drawRanges;
  36160. object._reservedRanges = data.reservedRanges;
  36161. object._geometryInfo = data.geometryInfo.map( info => {
  36162. let box = null;
  36163. let sphere = null;
  36164. if ( info.boundingBox !== undefined ) {
  36165. box = new Box3().fromJSON( info.boundingBox );
  36166. }
  36167. if ( info.boundingSphere !== undefined ) {
  36168. sphere = new Sphere().fromJSON( info.boundingSphere );
  36169. }
  36170. return {
  36171. ...info,
  36172. boundingBox: box,
  36173. boundingSphere: sphere
  36174. };
  36175. } );
  36176. object._instanceInfo = data.instanceInfo;
  36177. object._availableInstanceIds = data._availableInstanceIds;
  36178. object._availableGeometryIds = data._availableGeometryIds;
  36179. object._nextIndexStart = data.nextIndexStart;
  36180. object._nextVertexStart = data.nextVertexStart;
  36181. object._geometryCount = data.geometryCount;
  36182. object._maxInstanceCount = data.maxInstanceCount;
  36183. object._maxVertexCount = data.maxVertexCount;
  36184. object._maxIndexCount = data.maxIndexCount;
  36185. object._geometryInitialized = data.geometryInitialized;
  36186. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  36187. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  36188. if ( data.colorsTexture !== undefined ) {
  36189. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  36190. }
  36191. if ( data.boundingSphere !== undefined ) {
  36192. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  36193. }
  36194. if ( data.boundingBox !== undefined ) {
  36195. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  36196. }
  36197. break;
  36198. case 'LOD':
  36199. object = new LOD();
  36200. break;
  36201. case 'Line':
  36202. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  36203. break;
  36204. case 'LineLoop':
  36205. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  36206. break;
  36207. case 'LineSegments':
  36208. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  36209. break;
  36210. case 'PointCloud':
  36211. case 'Points':
  36212. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  36213. break;
  36214. case 'Sprite':
  36215. object = new Sprite( getMaterial( data.material ) );
  36216. break;
  36217. case 'Group':
  36218. object = new Group();
  36219. break;
  36220. case 'Bone':
  36221. object = new Bone();
  36222. break;
  36223. default:
  36224. object = new Object3D();
  36225. }
  36226. object.uuid = data.uuid;
  36227. if ( data.name !== undefined ) object.name = data.name;
  36228. if ( data.matrix !== undefined ) {
  36229. object.matrix.fromArray( data.matrix );
  36230. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  36231. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  36232. } else {
  36233. if ( data.position !== undefined ) object.position.fromArray( data.position );
  36234. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  36235. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  36236. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  36237. }
  36238. if ( data.up !== undefined ) object.up.fromArray( data.up );
  36239. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  36240. if ( data.morphTargetDictionary !== undefined ) object.morphTargetDictionary = Object.assign( {}, data.morphTargetDictionary );
  36241. if ( data.morphTargetInfluences !== undefined ) object.morphTargetInfluences = data.morphTargetInfluences.slice();
  36242. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  36243. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  36244. if ( data.shadow ) {
  36245. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  36246. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  36247. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  36248. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  36249. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  36250. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  36251. }
  36252. if ( data.visible !== undefined ) object.visible = data.visible;
  36253. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  36254. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  36255. if ( data.static !== undefined ) object.static = data.static;
  36256. if ( data.userData !== undefined ) object.userData = data.userData;
  36257. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  36258. if ( data.children !== undefined ) {
  36259. const children = data.children;
  36260. for ( let i = 0; i < children.length; i ++ ) {
  36261. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  36262. }
  36263. }
  36264. if ( data.animations !== undefined ) {
  36265. const objectAnimations = data.animations;
  36266. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  36267. const uuid = objectAnimations[ i ];
  36268. object.animations.push( animations[ uuid ] );
  36269. }
  36270. }
  36271. if ( data.type === 'LOD' ) {
  36272. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  36273. const levels = data.levels;
  36274. for ( let l = 0; l < levels.length; l ++ ) {
  36275. const level = levels[ l ];
  36276. const child = object.getObjectByProperty( 'uuid', level.object );
  36277. if ( child !== undefined ) {
  36278. object.addLevel( child, level.distance, level.hysteresis );
  36279. }
  36280. }
  36281. }
  36282. return object;
  36283. }
  36284. bindSkeletons( object, skeletons ) {
  36285. if ( Object.keys( skeletons ).length === 0 ) return;
  36286. object.traverse( function ( child ) {
  36287. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  36288. const skeleton = skeletons[ child.skeleton ];
  36289. if ( skeleton === undefined ) {
  36290. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  36291. } else {
  36292. child.bind( skeleton, child.bindMatrix );
  36293. }
  36294. }
  36295. } );
  36296. }
  36297. bindLightTargets( object ) {
  36298. object.traverse( function ( child ) {
  36299. if ( child.isDirectionalLight || child.isSpotLight ) {
  36300. const uuid = child.target;
  36301. const target = object.getObjectByProperty( 'uuid', uuid );
  36302. if ( target !== undefined ) {
  36303. child.target = target;
  36304. } else {
  36305. child.target = new Object3D();
  36306. }
  36307. }
  36308. } );
  36309. }
  36310. }
  36311. const TEXTURE_MAPPING = {
  36312. UVMapping: UVMapping,
  36313. CubeReflectionMapping: CubeReflectionMapping,
  36314. CubeRefractionMapping: CubeRefractionMapping,
  36315. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  36316. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  36317. CubeUVReflectionMapping: CubeUVReflectionMapping
  36318. };
  36319. const TEXTURE_WRAPPING = {
  36320. RepeatWrapping: RepeatWrapping,
  36321. ClampToEdgeWrapping: ClampToEdgeWrapping,
  36322. MirroredRepeatWrapping: MirroredRepeatWrapping
  36323. };
  36324. const TEXTURE_FILTER = {
  36325. NearestFilter: NearestFilter,
  36326. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  36327. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  36328. LinearFilter: LinearFilter,
  36329. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  36330. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  36331. };
  36332. const _errorMap = new WeakMap();
  36333. /**
  36334. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  36335. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  36336. * textures for rendering.
  36337. *
  36338. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  36339. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  36340. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  36341. *
  36342. * To match the default behaviour of {@link Texture}, the following options are needed:
  36343. *
  36344. * ```js
  36345. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  36346. * ```
  36347. *
  36348. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  36349. *
  36350. * ```js
  36351. * const loader = new THREE.ImageBitmapLoader();
  36352. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  36353. * const imageBitmap = await loader.loadAsync( 'image.png' );
  36354. *
  36355. * const texture = new THREE.Texture( imageBitmap );
  36356. * texture.needsUpdate = true;
  36357. * ```
  36358. *
  36359. * @augments Loader
  36360. */
  36361. class ImageBitmapLoader extends Loader {
  36362. /**
  36363. * Constructs a new image bitmap loader.
  36364. *
  36365. * @param {LoadingManager} [manager] - The loading manager.
  36366. */
  36367. constructor( manager ) {
  36368. super( manager );
  36369. /**
  36370. * This flag can be used for type testing.
  36371. *
  36372. * @type {boolean}
  36373. * @readonly
  36374. * @default true
  36375. */
  36376. this.isImageBitmapLoader = true;
  36377. if ( typeof createImageBitmap === 'undefined' ) {
  36378. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  36379. }
  36380. if ( typeof fetch === 'undefined' ) {
  36381. warn( 'ImageBitmapLoader: fetch() not supported.' );
  36382. }
  36383. /**
  36384. * Represents the loader options.
  36385. *
  36386. * @type {Object}
  36387. * @default {premultiplyAlpha:'none'}
  36388. */
  36389. this.options = { premultiplyAlpha: 'none' };
  36390. /**
  36391. * Used for aborting requests.
  36392. *
  36393. * @private
  36394. * @type {AbortController}
  36395. */
  36396. this._abortController = new AbortController();
  36397. }
  36398. /**
  36399. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36400. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36401. *
  36402. * Note: When caching is enabled, the cache key is based on the URL only. Loading the same URL with
  36403. * different options will return the cached result of the first request.
  36404. *
  36405. * @param {Object} options - The loader options to set.
  36406. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36407. */
  36408. setOptions( options ) {
  36409. this.options = options;
  36410. return this;
  36411. }
  36412. /**
  36413. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36414. *
  36415. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36416. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36417. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36418. * @param {onErrorCallback} onError - Executed when errors occur.
  36419. */
  36420. load( url, onLoad, onProgress, onError ) {
  36421. if ( url === undefined ) url = '';
  36422. if ( this.path !== undefined ) url = this.path + url;
  36423. url = this.manager.resolveURL( url );
  36424. const scope = this;
  36425. const cached = Cache.get( `image-bitmap:${url}` );
  36426. if ( cached !== undefined ) {
  36427. scope.manager.itemStart( url );
  36428. // If cached is a promise, wait for it to resolve
  36429. if ( cached.then ) {
  36430. cached.then( imageBitmap => {
  36431. // check if there is an error for the cached promise
  36432. if ( _errorMap.has( cached ) === true ) {
  36433. if ( onError ) onError( _errorMap.get( cached ) );
  36434. scope.manager.itemError( url );
  36435. scope.manager.itemEnd( url );
  36436. } else {
  36437. if ( onLoad ) onLoad( imageBitmap );
  36438. scope.manager.itemEnd( url );
  36439. }
  36440. } );
  36441. return;
  36442. }
  36443. // If cached is not a promise (i.e., it's already an imageBitmap)
  36444. setTimeout( function () {
  36445. if ( onLoad ) onLoad( cached );
  36446. scope.manager.itemEnd( url );
  36447. }, 0 );
  36448. return;
  36449. }
  36450. const fetchOptions = {};
  36451. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36452. fetchOptions.headers = this.requestHeader;
  36453. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36454. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36455. return res.blob();
  36456. } ).then( function ( blob ) {
  36457. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36458. } ).then( function ( imageBitmap ) {
  36459. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36460. if ( onLoad ) onLoad( imageBitmap );
  36461. scope.manager.itemEnd( url );
  36462. } ).catch( function ( e ) {
  36463. if ( onError ) onError( e );
  36464. _errorMap.set( promise, e );
  36465. Cache.remove( `image-bitmap:${url}` );
  36466. scope.manager.itemError( url );
  36467. scope.manager.itemEnd( url );
  36468. } );
  36469. Cache.add( `image-bitmap:${url}`, promise );
  36470. scope.manager.itemStart( url );
  36471. }
  36472. /**
  36473. * Aborts ongoing fetch requests.
  36474. *
  36475. * @return {ImageBitmapLoader} A reference to this instance.
  36476. */
  36477. abort() {
  36478. this._abortController.abort();
  36479. this._abortController = new AbortController();
  36480. return this;
  36481. }
  36482. }
  36483. let _context;
  36484. /**
  36485. * Manages the global audio context in the engine.
  36486. *
  36487. * @hideconstructor
  36488. */
  36489. class AudioContext {
  36490. /**
  36491. * Returns the global native audio context.
  36492. *
  36493. * @return {Window.AudioContext} The native audio context.
  36494. */
  36495. static getContext() {
  36496. if ( _context === undefined ) {
  36497. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36498. }
  36499. return _context;
  36500. }
  36501. /**
  36502. * Allows to set the global native audio context from outside.
  36503. *
  36504. * @param {Window.AudioContext} value - The native context to set.
  36505. */
  36506. static setContext( value ) {
  36507. _context = value;
  36508. }
  36509. }
  36510. /**
  36511. * Class for loading audio buffers. Audios are internally
  36512. * loaded via {@link FileLoader}.
  36513. *
  36514. * ```js
  36515. * const audioListener = new THREE.AudioListener();
  36516. * const ambientSound = new THREE.Audio( audioListener );
  36517. *
  36518. * const loader = new THREE.AudioLoader();
  36519. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36520. *
  36521. * ambientSound.setBuffer( audioBuffer );
  36522. * ambientSound.play();
  36523. * ```
  36524. *
  36525. * @augments Loader
  36526. */
  36527. class AudioLoader extends Loader {
  36528. /**
  36529. * Constructs a new audio loader.
  36530. *
  36531. * @param {LoadingManager} [manager] - The loading manager.
  36532. */
  36533. constructor( manager ) {
  36534. super( manager );
  36535. }
  36536. /**
  36537. * Starts loading from the given URL and passes the loaded audio buffer
  36538. * to the `onLoad()` callback.
  36539. *
  36540. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36541. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36542. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36543. * @param {onErrorCallback} onError - Executed when errors occur.
  36544. */
  36545. load( url, onLoad, onProgress, onError ) {
  36546. const scope = this;
  36547. const loader = new FileLoader( this.manager );
  36548. loader.setResponseType( 'arraybuffer' );
  36549. loader.setPath( this.path );
  36550. loader.setRequestHeader( this.requestHeader );
  36551. loader.setWithCredentials( this.withCredentials );
  36552. loader.load( url, function ( buffer ) {
  36553. try {
  36554. // Create a copy of the buffer. The `decodeAudioData` method
  36555. // detaches the buffer when complete, preventing reuse.
  36556. const bufferCopy = buffer.slice( 0 );
  36557. const context = AudioContext.getContext();
  36558. const decodeUrl = url + '#decode';
  36559. scope.manager.itemStart( decodeUrl ); // prevent loading manager from completing too early, see #33378
  36560. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36561. onLoad( audioBuffer );
  36562. scope.manager.itemEnd( decodeUrl );
  36563. } ).catch( function ( e ) {
  36564. handleError( e );
  36565. scope.manager.itemEnd( decodeUrl );
  36566. } );
  36567. } catch ( e ) {
  36568. handleError( e );
  36569. }
  36570. }, onProgress, onError );
  36571. function handleError( e ) {
  36572. if ( onError ) {
  36573. onError( e );
  36574. } else {
  36575. error( e );
  36576. }
  36577. scope.manager.itemError( url );
  36578. }
  36579. }
  36580. }
  36581. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36582. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36583. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36584. /**
  36585. * A special type of camera that uses two perspective cameras with
  36586. * stereoscopic projection. Can be used for rendering stereo effects
  36587. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36588. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36589. */
  36590. class StereoCamera {
  36591. /**
  36592. * Constructs a new stereo camera.
  36593. */
  36594. constructor() {
  36595. /**
  36596. * The type property is used for detecting the object type
  36597. * in context of serialization/deserialization.
  36598. *
  36599. * @type {string}
  36600. * @readonly
  36601. */
  36602. this.type = 'StereoCamera';
  36603. /**
  36604. * The aspect.
  36605. *
  36606. * @type {number}
  36607. * @default 1
  36608. */
  36609. this.aspect = 1;
  36610. /**
  36611. * The eye separation which represents the distance
  36612. * between the left and right camera.
  36613. *
  36614. * @type {number}
  36615. * @default 0.064
  36616. */
  36617. this.eyeSep = 0.064;
  36618. /**
  36619. * The camera representing the left eye. This is added to layer `1` so objects to be
  36620. * rendered by the left camera must also be added to this layer.
  36621. *
  36622. * @type {PerspectiveCamera}
  36623. */
  36624. this.cameraL = new PerspectiveCamera();
  36625. this.cameraL.layers.enable( 1 );
  36626. this.cameraL.matrixAutoUpdate = false;
  36627. /**
  36628. * The camera representing the right eye. This is added to layer `2` so objects to be
  36629. * rendered by the right camera must also be added to this layer.
  36630. *
  36631. * @type {PerspectiveCamera}
  36632. */
  36633. this.cameraR = new PerspectiveCamera();
  36634. this.cameraR.layers.enable( 2 );
  36635. this.cameraR.matrixAutoUpdate = false;
  36636. this._cache = {
  36637. focus: null,
  36638. fov: null,
  36639. aspect: null,
  36640. near: null,
  36641. far: null,
  36642. zoom: null,
  36643. eyeSep: null
  36644. };
  36645. }
  36646. /**
  36647. * Updates the stereo camera based on the given perspective camera.
  36648. *
  36649. * @param {PerspectiveCamera} camera - The perspective camera.
  36650. */
  36651. update( camera ) {
  36652. const cache = this._cache;
  36653. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36654. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36655. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36656. if ( needsUpdate ) {
  36657. cache.focus = camera.focus;
  36658. cache.fov = camera.fov;
  36659. cache.aspect = camera.aspect * this.aspect;
  36660. cache.near = camera.near;
  36661. cache.far = camera.far;
  36662. cache.zoom = camera.zoom;
  36663. cache.eyeSep = this.eyeSep;
  36664. // Off-axis stereoscopic effect based on
  36665. // http://paulbourke.net/stereographics/stereorender/
  36666. _projectionMatrix.copy( camera.projectionMatrix );
  36667. const eyeSepHalf = cache.eyeSep / 2;
  36668. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36669. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36670. let xmin, xmax;
  36671. // translate xOffset
  36672. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36673. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36674. // for left eye
  36675. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36676. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36677. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36678. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36679. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36680. // for right eye
  36681. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36682. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36683. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36684. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36685. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36686. }
  36687. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36688. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36689. }
  36690. }
  36691. const fov = -90; // negative fov is not an error
  36692. const aspect = 1;
  36693. /**
  36694. * A special type of camera that is positioned in 3D space to render its surroundings into a
  36695. * cube render target. The render target can then be used as an environment map for rendering
  36696. * realtime reflections in your scene.
  36697. *
  36698. * ```js
  36699. * // Create cube render target
  36700. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  36701. *
  36702. * // Create cube camera
  36703. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  36704. * scene.add( cubeCamera );
  36705. *
  36706. * // Create car
  36707. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  36708. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  36709. * scene.add( car );
  36710. *
  36711. * // Update the render target cube
  36712. * car.visible = false;
  36713. * cubeCamera.position.copy( car.position );
  36714. * cubeCamera.update( renderer, scene );
  36715. *
  36716. * // Render the scene
  36717. * car.visible = true;
  36718. * renderer.render( scene, camera );
  36719. * ```
  36720. *
  36721. * @augments Object3D
  36722. */
  36723. class CubeCamera extends Object3D {
  36724. /**
  36725. * Constructs a new cube camera.
  36726. *
  36727. * @param {number} near - The camera's near plane.
  36728. * @param {number} far - The camera's far plane.
  36729. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  36730. */
  36731. constructor( near, far, renderTarget ) {
  36732. super();
  36733. this.type = 'CubeCamera';
  36734. /**
  36735. * A reference to the cube render target.
  36736. *
  36737. * @type {WebGLCubeRenderTarget}
  36738. */
  36739. this.renderTarget = renderTarget;
  36740. /**
  36741. * The current active coordinate system.
  36742. *
  36743. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  36744. * @default null
  36745. */
  36746. this.coordinateSystem = null;
  36747. /**
  36748. * The current active mipmap level
  36749. *
  36750. * @type {number}
  36751. * @default 0
  36752. */
  36753. this.activeMipmapLevel = 0;
  36754. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  36755. cameraPX.layers = this.layers;
  36756. this.add( cameraPX );
  36757. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  36758. cameraNX.layers = this.layers;
  36759. this.add( cameraNX );
  36760. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  36761. cameraPY.layers = this.layers;
  36762. this.add( cameraPY );
  36763. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  36764. cameraNY.layers = this.layers;
  36765. this.add( cameraNY );
  36766. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  36767. cameraPZ.layers = this.layers;
  36768. this.add( cameraPZ );
  36769. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  36770. cameraNZ.layers = this.layers;
  36771. this.add( cameraNZ );
  36772. }
  36773. /**
  36774. * Must be called when the coordinate system of the cube camera is changed.
  36775. */
  36776. updateCoordinateSystem() {
  36777. const coordinateSystem = this.coordinateSystem;
  36778. const cameras = this.children.concat();
  36779. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  36780. for ( const camera of cameras ) this.remove( camera );
  36781. if ( coordinateSystem === WebGLCoordinateSystem ) {
  36782. cameraPX.up.set( 0, 1, 0 );
  36783. cameraPX.lookAt( 1, 0, 0 );
  36784. cameraNX.up.set( 0, 1, 0 );
  36785. cameraNX.lookAt( -1, 0, 0 );
  36786. cameraPY.up.set( 0, 0, -1 );
  36787. cameraPY.lookAt( 0, 1, 0 );
  36788. cameraNY.up.set( 0, 0, 1 );
  36789. cameraNY.lookAt( 0, -1, 0 );
  36790. cameraPZ.up.set( 0, 1, 0 );
  36791. cameraPZ.lookAt( 0, 0, 1 );
  36792. cameraNZ.up.set( 0, 1, 0 );
  36793. cameraNZ.lookAt( 0, 0, -1 );
  36794. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  36795. cameraPX.up.set( 0, -1, 0 );
  36796. cameraPX.lookAt( -1, 0, 0 );
  36797. cameraNX.up.set( 0, -1, 0 );
  36798. cameraNX.lookAt( 1, 0, 0 );
  36799. cameraPY.up.set( 0, 0, 1 );
  36800. cameraPY.lookAt( 0, 1, 0 );
  36801. cameraNY.up.set( 0, 0, -1 );
  36802. cameraNY.lookAt( 0, -1, 0 );
  36803. cameraPZ.up.set( 0, -1, 0 );
  36804. cameraPZ.lookAt( 0, 0, 1 );
  36805. cameraNZ.up.set( 0, -1, 0 );
  36806. cameraNZ.lookAt( 0, 0, -1 );
  36807. } else {
  36808. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  36809. }
  36810. for ( const camera of cameras ) {
  36811. this.add( camera );
  36812. camera.updateMatrixWorld();
  36813. }
  36814. }
  36815. /**
  36816. * Calling this method will render the given scene with the given renderer
  36817. * into the cube render target of the camera.
  36818. *
  36819. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  36820. * @param {Scene} scene - The scene to render.
  36821. */
  36822. update( renderer, scene ) {
  36823. if ( this.parent === null ) this.updateMatrixWorld();
  36824. const { renderTarget, activeMipmapLevel } = this;
  36825. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  36826. this.coordinateSystem = renderer.coordinateSystem;
  36827. this.updateCoordinateSystem();
  36828. }
  36829. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  36830. const currentRenderTarget = renderer.getRenderTarget();
  36831. const currentActiveCubeFace = renderer.getActiveCubeFace();
  36832. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  36833. const currentXrEnabled = renderer.xr.enabled;
  36834. renderer.xr.enabled = false;
  36835. const generateMipmaps = renderTarget.texture.generateMipmaps;
  36836. renderTarget.texture.generateMipmaps = false;
  36837. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  36838. let reversedDepthBuffer = false;
  36839. if ( renderer.isWebGLRenderer === true ) {
  36840. reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  36841. } else {
  36842. reversedDepthBuffer = renderer.reversedDepthBuffer;
  36843. }
  36844. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  36845. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36846. renderer.render( scene, cameraPX );
  36847. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  36848. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36849. renderer.render( scene, cameraNX );
  36850. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  36851. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36852. renderer.render( scene, cameraPY );
  36853. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  36854. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36855. renderer.render( scene, cameraNY );
  36856. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  36857. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36858. renderer.render( scene, cameraPZ );
  36859. // mipmaps are generated during the last call of render()
  36860. // at this point, all sides of the cube render target are defined
  36861. renderTarget.texture.generateMipmaps = generateMipmaps;
  36862. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  36863. if ( reversedDepthBuffer && renderer.autoClear === false ) renderer.clearDepth();
  36864. renderer.render( scene, cameraNZ );
  36865. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  36866. renderer.xr.enabled = currentXrEnabled;
  36867. renderTarget.texture.needsPMREMUpdate = true;
  36868. }
  36869. }
  36870. /**
  36871. * This type of camera can be used in order to efficiently render a scene with a
  36872. * predefined set of cameras. This is an important performance aspect for
  36873. * rendering VR scenes.
  36874. *
  36875. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36876. * to define for each sub camera the `viewport` property which determines the
  36877. * part of the viewport that is rendered with this camera.
  36878. *
  36879. * @augments PerspectiveCamera
  36880. */
  36881. class ArrayCamera extends PerspectiveCamera {
  36882. /**
  36883. * Constructs a new array camera.
  36884. *
  36885. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36886. */
  36887. constructor( array = [] ) {
  36888. super();
  36889. /**
  36890. * This flag can be used for type testing.
  36891. *
  36892. * @type {boolean}
  36893. * @readonly
  36894. * @default true
  36895. */
  36896. this.isArrayCamera = true;
  36897. /**
  36898. * Whether this camera is used with multiview rendering or not.
  36899. *
  36900. * @type {boolean}
  36901. * @readonly
  36902. * @default false
  36903. */
  36904. this.isMultiViewCamera = false;
  36905. /**
  36906. * An array of perspective sub cameras.
  36907. *
  36908. * @type {Array<PerspectiveCamera>}
  36909. */
  36910. this.cameras = array;
  36911. }
  36912. }
  36913. /**
  36914. * This class is an alternative to {@link Clock} with a different API design and behavior.
  36915. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  36916. *
  36917. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  36918. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  36919. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  36920. * is inactive (e.g. tab switched or browser hidden).
  36921. *
  36922. * ```js
  36923. * const timer = new Timer();
  36924. * timer.connect( document ); // use Page Visibility API
  36925. * ```
  36926. */
  36927. class Timer {
  36928. /**
  36929. * Constructs a new timer.
  36930. */
  36931. constructor() {
  36932. this._previousTime = 0;
  36933. this._currentTime = 0;
  36934. this._startTime = performance.now();
  36935. this._delta = 0;
  36936. this._elapsed = 0;
  36937. this._timescale = 1;
  36938. this._document = null;
  36939. this._pageVisibilityHandler = null;
  36940. }
  36941. /**
  36942. * Connect the timer to the given document.Calling this method is not mandatory to
  36943. * use the timer but enables the usage of the Page Visibility API to avoid large time
  36944. * delta values.
  36945. *
  36946. * @param {Document} document - The document.
  36947. */
  36948. connect( document ) {
  36949. this._document = document;
  36950. // use Page Visibility API to avoid large time delta values
  36951. if ( document.hidden !== undefined ) {
  36952. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  36953. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  36954. }
  36955. }
  36956. /**
  36957. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  36958. */
  36959. disconnect() {
  36960. if ( this._pageVisibilityHandler !== null ) {
  36961. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  36962. this._pageVisibilityHandler = null;
  36963. }
  36964. this._document = null;
  36965. }
  36966. /**
  36967. * Returns the time delta in seconds.
  36968. *
  36969. * @return {number} The time delta in second.
  36970. */
  36971. getDelta() {
  36972. return this._delta / 1000;
  36973. }
  36974. /**
  36975. * Returns the elapsed time in seconds.
  36976. *
  36977. * @return {number} The elapsed time in second.
  36978. */
  36979. getElapsed() {
  36980. return this._elapsed / 1000;
  36981. }
  36982. /**
  36983. * Returns the timescale.
  36984. *
  36985. * @return {number} The timescale.
  36986. */
  36987. getTimescale() {
  36988. return this._timescale;
  36989. }
  36990. /**
  36991. * Sets the given timescale which scale the time delta computation
  36992. * in `update()`.
  36993. *
  36994. * @param {number} timescale - The timescale to set.
  36995. * @return {Timer} A reference to this timer.
  36996. */
  36997. setTimescale( timescale ) {
  36998. this._timescale = timescale;
  36999. return this;
  37000. }
  37001. /**
  37002. * Resets the time computation for the current simulation step.
  37003. *
  37004. * @return {Timer} A reference to this timer.
  37005. */
  37006. reset() {
  37007. this._currentTime = performance.now() - this._startTime;
  37008. return this;
  37009. }
  37010. /**
  37011. * Can be used to free all internal resources. Usually called when
  37012. * the timer instance isn't required anymore.
  37013. */
  37014. dispose() {
  37015. this.disconnect();
  37016. }
  37017. /**
  37018. * Updates the internal state of the timer. This method should be called
  37019. * once per simulation step and before you perform queries against the timer
  37020. * (e.g. via `getDelta()`).
  37021. *
  37022. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  37023. * from the `requestAnimationFrame` callback argument. If not provided, the current
  37024. * time will be determined with `performance.now`.
  37025. * @return {Timer} A reference to this timer.
  37026. */
  37027. update( timestamp ) {
  37028. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  37029. this._delta = 0;
  37030. } else {
  37031. this._previousTime = this._currentTime;
  37032. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  37033. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  37034. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  37035. }
  37036. return this;
  37037. }
  37038. }
  37039. function handleVisibilityChange() {
  37040. if ( this._document.hidden === false ) this.reset();
  37041. }
  37042. const _position$1 = /*@__PURE__*/ new Vector3();
  37043. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  37044. const _scale$1 = /*@__PURE__*/ new Vector3();
  37045. const _forward = /*@__PURE__*/ new Vector3();
  37046. const _up = /*@__PURE__*/ new Vector3();
  37047. /**
  37048. * The class represents a virtual listener of the all positional and non-positional audio effects
  37049. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  37050. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  37051. *
  37052. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  37053. * camera represents the 3D transformation of the listener.
  37054. *
  37055. * @augments Object3D
  37056. */
  37057. class AudioListener extends Object3D {
  37058. /**
  37059. * Constructs a new audio listener.
  37060. */
  37061. constructor() {
  37062. super();
  37063. this.type = 'AudioListener';
  37064. /**
  37065. * The native audio context.
  37066. *
  37067. * @type {AudioContext}
  37068. * @readonly
  37069. */
  37070. this.context = AudioContext.getContext();
  37071. /**
  37072. * The gain node used for volume control.
  37073. *
  37074. * @type {GainNode}
  37075. * @readonly
  37076. */
  37077. this.gain = this.context.createGain();
  37078. this.gain.connect( this.context.destination );
  37079. /**
  37080. * An optional filter.
  37081. *
  37082. * Defined via {@link AudioListener#setFilter}.
  37083. *
  37084. * @type {?AudioNode}
  37085. * @default null
  37086. * @readonly
  37087. */
  37088. this.filter = null;
  37089. /**
  37090. * Time delta values required for `linearRampToValueAtTime()` usage.
  37091. *
  37092. * @type {number}
  37093. * @default 0
  37094. * @readonly
  37095. */
  37096. this.timeDelta = 0;
  37097. // private
  37098. this._timer = new Timer();
  37099. }
  37100. /**
  37101. * Returns the listener's input node.
  37102. *
  37103. * This method is used by other audio nodes to connect to this listener.
  37104. *
  37105. * @return {GainNode} The input node.
  37106. */
  37107. getInput() {
  37108. return this.gain;
  37109. }
  37110. /**
  37111. * Removes the current filter from this listener.
  37112. *
  37113. * @return {AudioListener} A reference to this listener.
  37114. */
  37115. removeFilter() {
  37116. if ( this.filter !== null ) {
  37117. this.gain.disconnect( this.filter );
  37118. this.filter.disconnect( this.context.destination );
  37119. this.gain.connect( this.context.destination );
  37120. this.filter = null;
  37121. }
  37122. return this;
  37123. }
  37124. /**
  37125. * Returns the current set filter.
  37126. *
  37127. * @return {?AudioNode} The filter.
  37128. */
  37129. getFilter() {
  37130. return this.filter;
  37131. }
  37132. /**
  37133. * Sets the given filter to this listener.
  37134. *
  37135. * @param {AudioNode} value - The filter to set.
  37136. * @return {AudioListener} A reference to this listener.
  37137. */
  37138. setFilter( value ) {
  37139. if ( this.filter !== null ) {
  37140. this.gain.disconnect( this.filter );
  37141. this.filter.disconnect( this.context.destination );
  37142. } else {
  37143. this.gain.disconnect( this.context.destination );
  37144. }
  37145. this.filter = value;
  37146. this.gain.connect( this.filter );
  37147. this.filter.connect( this.context.destination );
  37148. return this;
  37149. }
  37150. /**
  37151. * Returns the applications master volume.
  37152. *
  37153. * @return {number} The master volume.
  37154. */
  37155. getMasterVolume() {
  37156. return this.gain.gain.value;
  37157. }
  37158. /**
  37159. * Sets the applications master volume. This volume setting affects
  37160. * all audio nodes in the scene.
  37161. *
  37162. * @param {number} value - The master volume to set.
  37163. * @return {AudioListener} A reference to this listener.
  37164. */
  37165. setMasterVolume( value ) {
  37166. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37167. return this;
  37168. }
  37169. updateMatrixWorld( force ) {
  37170. super.updateMatrixWorld( force );
  37171. this._timer.update();
  37172. const listener = this.context.listener;
  37173. this.timeDelta = this._timer.getDelta();
  37174. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  37175. // the initial forward and up directions must be orthogonal
  37176. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  37177. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  37178. if ( listener.positionX ) {
  37179. // code path for Chrome (see #14393)
  37180. const endTime = this.context.currentTime + this.timeDelta;
  37181. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  37182. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  37183. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  37184. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  37185. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  37186. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  37187. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  37188. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  37189. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  37190. } else {
  37191. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  37192. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  37193. }
  37194. }
  37195. }
  37196. /**
  37197. * Represents a non-positional ( global ) audio object.
  37198. *
  37199. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  37200. *
  37201. * ```js
  37202. * // create an AudioListener and add it to the camera
  37203. * const listener = new THREE.AudioListener();
  37204. * camera.add( listener );
  37205. *
  37206. * // create a global audio source
  37207. * const sound = new THREE.Audio( listener );
  37208. *
  37209. * // load a sound and set it as the Audio object's buffer
  37210. * const audioLoader = new THREE.AudioLoader();
  37211. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37212. * sound.setBuffer( buffer );
  37213. * sound.setLoop( true );
  37214. * sound.setVolume( 0.5 );
  37215. * sound.play();
  37216. * });
  37217. * ```
  37218. *
  37219. * @augments Object3D
  37220. */
  37221. class Audio extends Object3D {
  37222. /**
  37223. * Constructs a new audio.
  37224. *
  37225. * @param {AudioListener} listener - The global audio listener.
  37226. */
  37227. constructor( listener ) {
  37228. super();
  37229. this.type = 'Audio';
  37230. /**
  37231. * The global audio listener.
  37232. *
  37233. * @type {AudioListener}
  37234. * @readonly
  37235. */
  37236. this.listener = listener;
  37237. /**
  37238. * The audio context.
  37239. *
  37240. * @type {AudioContext}
  37241. * @readonly
  37242. */
  37243. this.context = listener.context;
  37244. /**
  37245. * The gain node used for volume control.
  37246. *
  37247. * @type {GainNode}
  37248. * @readonly
  37249. */
  37250. this.gain = this.context.createGain();
  37251. this.gain.connect( listener.getInput() );
  37252. /**
  37253. * Whether to start playback automatically or not.
  37254. *
  37255. * @type {boolean}
  37256. * @default false
  37257. */
  37258. this.autoplay = false;
  37259. /**
  37260. * A reference to an audio buffer.
  37261. *
  37262. * Defined via {@link Audio#setBuffer}.
  37263. *
  37264. * @type {?AudioBuffer}
  37265. * @default null
  37266. * @readonly
  37267. */
  37268. this.buffer = null;
  37269. /**
  37270. * Modify pitch, measured in cents. +/- 100 is a semitone.
  37271. * +/- 1200 is an octave.
  37272. *
  37273. * Defined via {@link Audio#setDetune}.
  37274. *
  37275. * @type {number}
  37276. * @default 0
  37277. * @readonly
  37278. */
  37279. this.detune = 0;
  37280. /**
  37281. * Whether the audio should loop or not.
  37282. *
  37283. * Defined via {@link Audio#setLoop}.
  37284. *
  37285. * @type {boolean}
  37286. * @default false
  37287. * @readonly
  37288. */
  37289. this.loop = false;
  37290. /**
  37291. * Defines where in the audio buffer the replay should
  37292. * start, in seconds.
  37293. *
  37294. * @type {number}
  37295. * @default 0
  37296. */
  37297. this.loopStart = 0;
  37298. /**
  37299. * Defines where in the audio buffer the replay should
  37300. * stop, in seconds.
  37301. *
  37302. * @type {number}
  37303. * @default 0
  37304. */
  37305. this.loopEnd = 0;
  37306. /**
  37307. * An offset to the time within the audio buffer the playback
  37308. * should begin, in seconds.
  37309. *
  37310. * @type {number}
  37311. * @default 0
  37312. */
  37313. this.offset = 0;
  37314. /**
  37315. * Overrides the default duration of the audio.
  37316. *
  37317. * @type {undefined|number}
  37318. * @default undefined
  37319. */
  37320. this.duration = undefined;
  37321. /**
  37322. * The playback speed.
  37323. *
  37324. * Defined via {@link Audio#setPlaybackRate}.
  37325. *
  37326. * @type {number}
  37327. * @readonly
  37328. * @default 1
  37329. */
  37330. this.playbackRate = 1;
  37331. /**
  37332. * Indicates whether the audio is playing or not.
  37333. *
  37334. * This flag will be automatically set when using {@link Audio#play},
  37335. * {@link Audio#pause}, {@link Audio#stop}.
  37336. *
  37337. * @type {boolean}
  37338. * @readonly
  37339. * @default false
  37340. */
  37341. this.isPlaying = false;
  37342. /**
  37343. * Indicates whether the audio playback can be controlled
  37344. * with method like {@link Audio#play} or {@link Audio#pause}.
  37345. *
  37346. * This flag will be automatically set when audio sources are
  37347. * defined.
  37348. *
  37349. * @type {boolean}
  37350. * @readonly
  37351. * @default true
  37352. */
  37353. this.hasPlaybackControl = true;
  37354. /**
  37355. * Holds a reference to the current audio source.
  37356. *
  37357. * The property is automatically by one of the `set*()` methods.
  37358. *
  37359. * @type {?AudioNode}
  37360. * @readonly
  37361. * @default null
  37362. */
  37363. this.source = null;
  37364. /**
  37365. * Defines the source type.
  37366. *
  37367. * The property is automatically set by one of the `set*()` methods.
  37368. *
  37369. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  37370. * @readonly
  37371. * @default 'empty'
  37372. */
  37373. this.sourceType = 'empty';
  37374. this._startedAt = 0;
  37375. this._progress = 0;
  37376. this._connected = false;
  37377. /**
  37378. * Can be used to apply a variety of low-order filters to create
  37379. * more complex sound effects e.g. via `BiquadFilterNode`.
  37380. *
  37381. * The property is automatically set by {@link Audio#setFilters}.
  37382. *
  37383. * @type {Array<AudioNode>}
  37384. * @readonly
  37385. */
  37386. this.filters = [];
  37387. }
  37388. /**
  37389. * Returns the output audio node.
  37390. *
  37391. * @return {GainNode} The output node.
  37392. */
  37393. getOutput() {
  37394. return this.gain;
  37395. }
  37396. /**
  37397. * Sets the given audio node as the source of this instance.
  37398. *
  37399. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  37400. *
  37401. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  37402. * @return {Audio} A reference to this instance.
  37403. */
  37404. setNodeSource( audioNode ) {
  37405. this.hasPlaybackControl = false;
  37406. this.sourceType = 'audioNode';
  37407. this.source = audioNode;
  37408. this.connect();
  37409. return this;
  37410. }
  37411. /**
  37412. * Sets the given media element as the source of this instance.
  37413. *
  37414. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  37415. *
  37416. * @param {HTMLMediaElement} mediaElement - The media element.
  37417. * @return {Audio} A reference to this instance.
  37418. */
  37419. setMediaElementSource( mediaElement ) {
  37420. this.hasPlaybackControl = false;
  37421. this.sourceType = 'mediaNode';
  37422. this.source = this.context.createMediaElementSource( mediaElement );
  37423. this.connect();
  37424. return this;
  37425. }
  37426. /**
  37427. * Sets the given media stream as the source of this instance.
  37428. *
  37429. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  37430. *
  37431. * @param {MediaStream} mediaStream - The media stream.
  37432. * @return {Audio} A reference to this instance.
  37433. */
  37434. setMediaStreamSource( mediaStream ) {
  37435. this.hasPlaybackControl = false;
  37436. this.sourceType = 'mediaStreamNode';
  37437. this.source = this.context.createMediaStreamSource( mediaStream );
  37438. this.connect();
  37439. return this;
  37440. }
  37441. /**
  37442. * Sets the given audio buffer as the source of this instance.
  37443. *
  37444. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  37445. *
  37446. * @param {AudioBuffer} audioBuffer - The audio buffer.
  37447. * @return {Audio} A reference to this instance.
  37448. */
  37449. setBuffer( audioBuffer ) {
  37450. this.buffer = audioBuffer;
  37451. this.sourceType = 'buffer';
  37452. if ( this.autoplay ) this.play();
  37453. return this;
  37454. }
  37455. /**
  37456. * Starts the playback of the audio.
  37457. *
  37458. * Can only be used with compatible audio sources that allow playback control.
  37459. *
  37460. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  37461. * @return {Audio|undefined} A reference to this instance.
  37462. */
  37463. play( delay = 0 ) {
  37464. if ( this.isPlaying === true ) {
  37465. warn( 'Audio: Audio is already playing.' );
  37466. return;
  37467. }
  37468. if ( this.hasPlaybackControl === false ) {
  37469. warn( 'Audio: this Audio has no playback control.' );
  37470. return;
  37471. }
  37472. this._startedAt = this.context.currentTime + delay;
  37473. const source = this.context.createBufferSource();
  37474. source.buffer = this.buffer;
  37475. source.loop = this.loop;
  37476. source.loopStart = this.loopStart;
  37477. source.loopEnd = this.loopEnd;
  37478. source.onended = this.onEnded.bind( this );
  37479. source.start( this._startedAt, this._progress + this.offset, this.duration );
  37480. this.isPlaying = true;
  37481. this.source = source;
  37482. this.setDetune( this.detune );
  37483. this.setPlaybackRate( this.playbackRate );
  37484. return this.connect();
  37485. }
  37486. /**
  37487. * Pauses the playback of the audio.
  37488. *
  37489. * Can only be used with compatible audio sources that allow playback control.
  37490. *
  37491. * @return {Audio|undefined} A reference to this instance.
  37492. */
  37493. pause() {
  37494. if ( this.hasPlaybackControl === false ) {
  37495. warn( 'Audio: this Audio has no playback control.' );
  37496. return;
  37497. }
  37498. if ( this.isPlaying === true ) {
  37499. // update current progress
  37500. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  37501. if ( this.loop === true ) {
  37502. // ensure _progress does not exceed duration with looped audios
  37503. this._progress = this._progress % ( this.duration || this.buffer.duration );
  37504. }
  37505. this.source.stop();
  37506. this.source.onended = null;
  37507. this.isPlaying = false;
  37508. }
  37509. return this;
  37510. }
  37511. /**
  37512. * Stops the playback of the audio.
  37513. *
  37514. * Can only be used with compatible audio sources that allow playback control.
  37515. *
  37516. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  37517. * @return {Audio|undefined} A reference to this instance.
  37518. */
  37519. stop( delay = 0 ) {
  37520. if ( this.hasPlaybackControl === false ) {
  37521. warn( 'Audio: this Audio has no playback control.' );
  37522. return;
  37523. }
  37524. this._progress = 0;
  37525. if ( this.source !== null ) {
  37526. this.source.stop( this.context.currentTime + delay );
  37527. this.source.onended = null;
  37528. }
  37529. this.isPlaying = false;
  37530. return this;
  37531. }
  37532. /**
  37533. * Connects to the audio source. This is used internally on
  37534. * initialisation and when setting / removing filters.
  37535. *
  37536. * @return {Audio} A reference to this instance.
  37537. */
  37538. connect() {
  37539. if ( this.filters.length > 0 ) {
  37540. this.source.connect( this.filters[ 0 ] );
  37541. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37542. this.filters[ i - 1 ].connect( this.filters[ i ] );
  37543. }
  37544. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  37545. } else {
  37546. this.source.connect( this.getOutput() );
  37547. }
  37548. this._connected = true;
  37549. return this;
  37550. }
  37551. /**
  37552. * Disconnects to the audio source. This is used internally on
  37553. * initialisation and when setting / removing filters.
  37554. *
  37555. * @return {Audio|undefined} A reference to this instance.
  37556. */
  37557. disconnect() {
  37558. if ( this._connected === false ) {
  37559. return;
  37560. }
  37561. if ( this.filters.length > 0 ) {
  37562. this.source.disconnect( this.filters[ 0 ] );
  37563. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  37564. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  37565. }
  37566. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  37567. } else {
  37568. this.source.disconnect( this.getOutput() );
  37569. }
  37570. this._connected = false;
  37571. return this;
  37572. }
  37573. /**
  37574. * Returns the current set filters.
  37575. *
  37576. * @return {Array<AudioNode>} The list of filters.
  37577. */
  37578. getFilters() {
  37579. return this.filters;
  37580. }
  37581. /**
  37582. * Sets an array of filters and connects them with the audio source.
  37583. *
  37584. * @param {Array<AudioNode>} [value] - A list of filters.
  37585. * @return {Audio} A reference to this instance.
  37586. */
  37587. setFilters( value ) {
  37588. if ( ! value ) value = [];
  37589. if ( this._connected === true ) {
  37590. this.disconnect();
  37591. this.filters = value.slice();
  37592. this.connect();
  37593. } else {
  37594. this.filters = value.slice();
  37595. }
  37596. return this;
  37597. }
  37598. /**
  37599. * Defines the detuning of oscillation in cents.
  37600. *
  37601. * @param {number} value - The detuning of oscillation in cents.
  37602. * @return {Audio} A reference to this instance.
  37603. */
  37604. setDetune( value ) {
  37605. this.detune = value;
  37606. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37607. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37608. }
  37609. return this;
  37610. }
  37611. /**
  37612. * Returns the detuning of oscillation in cents.
  37613. *
  37614. * @return {number} The detuning of oscillation in cents.
  37615. */
  37616. getDetune() {
  37617. return this.detune;
  37618. }
  37619. /**
  37620. * Returns the first filter in the list of filters.
  37621. *
  37622. * @return {AudioNode|undefined} The first filter in the list of filters.
  37623. */
  37624. getFilter() {
  37625. return this.getFilters()[ 0 ];
  37626. }
  37627. /**
  37628. * Applies a single filter node to the audio.
  37629. *
  37630. * @param {AudioNode} [filter] - The filter to set.
  37631. * @return {Audio} A reference to this instance.
  37632. */
  37633. setFilter( filter ) {
  37634. return this.setFilters( filter ? [ filter ] : [] );
  37635. }
  37636. /**
  37637. * Sets the playback rate.
  37638. *
  37639. * Can only be used with compatible audio sources that allow playback control.
  37640. *
  37641. * @param {number} [value] - The playback rate to set.
  37642. * @return {Audio|undefined} A reference to this instance.
  37643. */
  37644. setPlaybackRate( value ) {
  37645. if ( this.hasPlaybackControl === false ) {
  37646. warn( 'Audio: this Audio has no playback control.' );
  37647. return;
  37648. }
  37649. this.playbackRate = value;
  37650. if ( this.isPlaying === true ) {
  37651. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37652. }
  37653. return this;
  37654. }
  37655. /**
  37656. * Returns the current playback rate.
  37657. * @return {number} The playback rate.
  37658. */
  37659. getPlaybackRate() {
  37660. return this.playbackRate;
  37661. }
  37662. /**
  37663. * Automatically called when playback finished.
  37664. */
  37665. onEnded() {
  37666. this.isPlaying = false;
  37667. this._progress = 0;
  37668. }
  37669. /**
  37670. * Returns the loop flag.
  37671. *
  37672. * Can only be used with compatible audio sources that allow playback control.
  37673. *
  37674. * @return {boolean} Whether the audio should loop or not.
  37675. */
  37676. getLoop() {
  37677. if ( this.hasPlaybackControl === false ) {
  37678. warn( 'Audio: this Audio has no playback control.' );
  37679. return false;
  37680. }
  37681. return this.loop;
  37682. }
  37683. /**
  37684. * Sets the loop flag.
  37685. *
  37686. * Can only be used with compatible audio sources that allow playback control.
  37687. *
  37688. * @param {boolean} value - Whether the audio should loop or not.
  37689. * @return {Audio|undefined} A reference to this instance.
  37690. */
  37691. setLoop( value ) {
  37692. if ( this.hasPlaybackControl === false ) {
  37693. warn( 'Audio: this Audio has no playback control.' );
  37694. return;
  37695. }
  37696. this.loop = value;
  37697. if ( this.isPlaying === true ) {
  37698. this.source.loop = this.loop;
  37699. }
  37700. return this;
  37701. }
  37702. /**
  37703. * Sets the loop start value which defines where in the audio buffer the replay should
  37704. * start, in seconds.
  37705. *
  37706. * @param {number} value - The loop start value.
  37707. * @return {Audio} A reference to this instance.
  37708. */
  37709. setLoopStart( value ) {
  37710. this.loopStart = value;
  37711. return this;
  37712. }
  37713. /**
  37714. * Sets the loop end value which defines where in the audio buffer the replay should
  37715. * stop, in seconds.
  37716. *
  37717. * @param {number} value - The loop end value.
  37718. * @return {Audio} A reference to this instance.
  37719. */
  37720. setLoopEnd( value ) {
  37721. this.loopEnd = value;
  37722. return this;
  37723. }
  37724. /**
  37725. * Returns the volume.
  37726. *
  37727. * @return {number} The volume.
  37728. */
  37729. getVolume() {
  37730. return this.gain.gain.value;
  37731. }
  37732. /**
  37733. * Sets the volume.
  37734. *
  37735. * @param {number} value - The volume to set.
  37736. * @return {Audio} A reference to this instance.
  37737. */
  37738. setVolume( value ) {
  37739. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37740. return this;
  37741. }
  37742. copy( source, recursive ) {
  37743. super.copy( source, recursive );
  37744. if ( source.sourceType !== 'buffer' ) {
  37745. warn( 'Audio: Audio source type cannot be copied.' );
  37746. return this;
  37747. }
  37748. this.autoplay = source.autoplay;
  37749. this.buffer = source.buffer;
  37750. this.detune = source.detune;
  37751. this.loop = source.loop;
  37752. this.loopStart = source.loopStart;
  37753. this.loopEnd = source.loopEnd;
  37754. this.offset = source.offset;
  37755. this.duration = source.duration;
  37756. this.playbackRate = source.playbackRate;
  37757. this.hasPlaybackControl = source.hasPlaybackControl;
  37758. this.sourceType = source.sourceType;
  37759. this.filters = source.filters.slice();
  37760. return this;
  37761. }
  37762. clone( recursive ) {
  37763. return new this.constructor( this.listener ).copy( this, recursive );
  37764. }
  37765. }
  37766. const _position = /*@__PURE__*/ new Vector3();
  37767. const _quaternion = /*@__PURE__*/ new Quaternion();
  37768. const _scale = /*@__PURE__*/ new Vector3();
  37769. const _orientation = /*@__PURE__*/ new Vector3();
  37770. /**
  37771. * Represents a positional audio object.
  37772. *
  37773. * ```js
  37774. * // create an AudioListener and add it to the camera
  37775. * const listener = new THREE.AudioListener();
  37776. * camera.add( listener );
  37777. *
  37778. * // create the PositionalAudio object (passing in the listener)
  37779. * const sound = new THREE.PositionalAudio( listener );
  37780. *
  37781. * // load a sound and set it as the PositionalAudio object's buffer
  37782. * const audioLoader = new THREE.AudioLoader();
  37783. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37784. * sound.setBuffer( buffer );
  37785. * sound.setRefDistance( 20 );
  37786. * sound.play();
  37787. * });
  37788. *
  37789. * // create an object for the sound to play from
  37790. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37791. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37792. * const mesh = new THREE.Mesh( sphere, material );
  37793. * scene.add( mesh );
  37794. *
  37795. * // finally add the sound to the mesh
  37796. * mesh.add( sound );
  37797. *
  37798. * @augments Audio
  37799. */
  37800. class PositionalAudio extends Audio {
  37801. /**
  37802. * Constructs a positional audio.
  37803. *
  37804. * @param {AudioListener} listener - The global audio listener.
  37805. */
  37806. constructor( listener ) {
  37807. super( listener );
  37808. /**
  37809. * The panner node represents the location, direction, and behavior of an audio
  37810. * source in 3D space.
  37811. *
  37812. * @type {PannerNode}
  37813. * @readonly
  37814. */
  37815. this.panner = this.context.createPanner();
  37816. this.panner.panningModel = 'HRTF';
  37817. this.panner.connect( this.gain );
  37818. }
  37819. connect() {
  37820. super.connect();
  37821. this.panner.connect( this.gain );
  37822. return this;
  37823. }
  37824. disconnect() {
  37825. super.disconnect();
  37826. this.panner.disconnect( this.gain );
  37827. return this;
  37828. }
  37829. getOutput() {
  37830. return this.panner;
  37831. }
  37832. /**
  37833. * Returns the current reference distance.
  37834. *
  37835. * @return {number} The reference distance.
  37836. */
  37837. getRefDistance() {
  37838. return this.panner.refDistance;
  37839. }
  37840. /**
  37841. * Defines the reference distance for reducing volume as the audio source moves
  37842. * further from the listener – i.e. the distance at which the volume reduction
  37843. * starts taking effect.
  37844. *
  37845. * @param {number} value - The reference distance to set.
  37846. * @return {PositionalAudio} A reference to this instance.
  37847. */
  37848. setRefDistance( value ) {
  37849. this.panner.refDistance = value;
  37850. return this;
  37851. }
  37852. /**
  37853. * Returns the current rolloff factor.
  37854. *
  37855. * @return {number} The rolloff factor.
  37856. */
  37857. getRolloffFactor() {
  37858. return this.panner.rolloffFactor;
  37859. }
  37860. /**
  37861. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37862. *
  37863. * @param {number} value - The rolloff factor.
  37864. * @return {PositionalAudio} A reference to this instance.
  37865. */
  37866. setRolloffFactor( value ) {
  37867. this.panner.rolloffFactor = value;
  37868. return this;
  37869. }
  37870. /**
  37871. * Returns the current distance model.
  37872. *
  37873. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37874. */
  37875. getDistanceModel() {
  37876. return this.panner.distanceModel;
  37877. }
  37878. /**
  37879. * Defines which algorithm to use to reduce the volume of the audio source
  37880. * as it moves away from the listener.
  37881. *
  37882. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37883. * for more details.
  37884. *
  37885. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37886. * @return {PositionalAudio} A reference to this instance.
  37887. */
  37888. setDistanceModel( value ) {
  37889. this.panner.distanceModel = value;
  37890. return this;
  37891. }
  37892. /**
  37893. * Returns the current max distance.
  37894. *
  37895. * @return {number} The max distance.
  37896. */
  37897. getMaxDistance() {
  37898. return this.panner.maxDistance;
  37899. }
  37900. /**
  37901. * Defines the maximum distance between the audio source and the listener,
  37902. * after which the volume is not reduced any further.
  37903. *
  37904. * This value is used only by the `linear` distance model.
  37905. *
  37906. * @param {number} value - The max distance.
  37907. * @return {PositionalAudio} A reference to this instance.
  37908. */
  37909. setMaxDistance( value ) {
  37910. this.panner.maxDistance = value;
  37911. return this;
  37912. }
  37913. /**
  37914. * Sets the directional cone in which the audio can be listened.
  37915. *
  37916. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37917. * @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.
  37918. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37919. * @return {PositionalAudio} A reference to this instance.
  37920. */
  37921. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37922. this.panner.coneInnerAngle = coneInnerAngle;
  37923. this.panner.coneOuterAngle = coneOuterAngle;
  37924. this.panner.coneOuterGain = coneOuterGain;
  37925. return this;
  37926. }
  37927. updateMatrixWorld( force ) {
  37928. super.updateMatrixWorld( force );
  37929. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37930. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37931. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37932. const panner = this.panner;
  37933. if ( panner.positionX ) {
  37934. // code path for Chrome and Firefox (see #14393)
  37935. const endTime = this.context.currentTime + this.listener.timeDelta;
  37936. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37937. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37938. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37939. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37940. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37941. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37942. } else {
  37943. panner.setPosition( _position.x, _position.y, _position.z );
  37944. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37945. }
  37946. }
  37947. }
  37948. /**
  37949. * This class can be used to analyse audio data.
  37950. *
  37951. * ```js
  37952. * // create an AudioListener and add it to the camera
  37953. * const listener = new THREE.AudioListener();
  37954. * camera.add( listener );
  37955. *
  37956. * // create an Audio source
  37957. * const sound = new THREE.Audio( listener );
  37958. *
  37959. * // load a sound and set it as the Audio object's buffer
  37960. * const audioLoader = new THREE.AudioLoader();
  37961. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37962. * sound.setBuffer( buffer );
  37963. * sound.setLoop(true);
  37964. * sound.setVolume(0.5);
  37965. * sound.play();
  37966. * });
  37967. *
  37968. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37969. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37970. *
  37971. * // get the average frequency of the sound
  37972. * const data = analyser.getAverageFrequency();
  37973. * ```
  37974. */
  37975. class AudioAnalyser {
  37976. /**
  37977. * Constructs a new audio analyzer.
  37978. *
  37979. * @param {Audio} audio - The audio to analyze.
  37980. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37981. */
  37982. constructor( audio, fftSize = 2048 ) {
  37983. /**
  37984. * The global audio listener.
  37985. *
  37986. * @type {AnalyserNode}
  37987. */
  37988. this.analyser = audio.context.createAnalyser();
  37989. this.analyser.fftSize = fftSize;
  37990. /**
  37991. * Holds the analyzed data.
  37992. *
  37993. * @type {Uint8Array}
  37994. */
  37995. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37996. audio.getOutput().connect( this.analyser );
  37997. }
  37998. /**
  37999. * Returns an array with frequency data of the audio.
  38000. *
  38001. * Each item in the array represents the decibel value for a specific frequency.
  38002. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  38003. * For example, for 48000 sample rate, the last item of the array will represent
  38004. * the decibel value for 24000 Hz.
  38005. *
  38006. * @return {Uint8Array} The frequency data.
  38007. */
  38008. getFrequencyData() {
  38009. this.analyser.getByteFrequencyData( this.data );
  38010. return this.data;
  38011. }
  38012. /**
  38013. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  38014. *
  38015. * @return {number} The average frequency.
  38016. */
  38017. getAverageFrequency() {
  38018. let value = 0;
  38019. const data = this.getFrequencyData();
  38020. for ( let i = 0; i < data.length; i ++ ) {
  38021. value += data[ i ];
  38022. }
  38023. return value / data.length;
  38024. }
  38025. }
  38026. /**
  38027. * Buffered scene graph property that allows weighted accumulation; used internally.
  38028. */
  38029. class PropertyMixer {
  38030. /**
  38031. * Constructs a new property mixer.
  38032. *
  38033. * @param {PropertyBinding} binding - The property binding.
  38034. * @param {string} typeName - The keyframe track type name.
  38035. * @param {number} valueSize - The keyframe track value size.
  38036. */
  38037. constructor( binding, typeName, valueSize ) {
  38038. /**
  38039. * The property binding.
  38040. *
  38041. * @type {PropertyBinding}
  38042. */
  38043. this.binding = binding;
  38044. /**
  38045. * The keyframe track value size.
  38046. *
  38047. * @type {number}
  38048. */
  38049. this.valueSize = valueSize;
  38050. let mixFunction,
  38051. mixFunctionAdditive,
  38052. setIdentity;
  38053. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  38054. //
  38055. // interpolators can use .buffer as their .result
  38056. // the data then goes to 'incoming'
  38057. //
  38058. // 'accu0' and 'accu1' are used frame-interleaved for
  38059. // the cumulative result and are compared to detect
  38060. // changes
  38061. //
  38062. // 'orig' stores the original state of the property
  38063. //
  38064. // 'add' is used for additive cumulative results
  38065. //
  38066. // 'work' is optional and is only present for quaternion types. It is used
  38067. // to store intermediate quaternion multiplication results
  38068. switch ( typeName ) {
  38069. case 'quaternion':
  38070. mixFunction = this._slerp;
  38071. mixFunctionAdditive = this._slerpAdditive;
  38072. setIdentity = this._setAdditiveIdentityQuaternion;
  38073. this.buffer = new Float64Array( valueSize * 6 );
  38074. this._workIndex = 5;
  38075. break;
  38076. case 'string':
  38077. case 'bool':
  38078. mixFunction = this._select;
  38079. // Use the regular mix function and for additive on these types,
  38080. // additive is not relevant for non-numeric types
  38081. mixFunctionAdditive = this._select;
  38082. setIdentity = this._setAdditiveIdentityOther;
  38083. this.buffer = new Array( valueSize * 5 );
  38084. break;
  38085. default:
  38086. mixFunction = this._lerp;
  38087. mixFunctionAdditive = this._lerpAdditive;
  38088. setIdentity = this._setAdditiveIdentityNumeric;
  38089. this.buffer = new Float64Array( valueSize * 5 );
  38090. }
  38091. this._mixBufferRegion = mixFunction;
  38092. this._mixBufferRegionAdditive = mixFunctionAdditive;
  38093. this._setIdentity = setIdentity;
  38094. this._origIndex = 3;
  38095. this._addIndex = 4;
  38096. /**
  38097. * Accumulated weight of the property binding.
  38098. *
  38099. * @type {number}
  38100. * @default 0
  38101. */
  38102. this.cumulativeWeight = 0;
  38103. /**
  38104. * Accumulated additive weight of the property binding.
  38105. *
  38106. * @type {number}
  38107. * @default 0
  38108. */
  38109. this.cumulativeWeightAdditive = 0;
  38110. /**
  38111. * Number of active keyframe tracks currently using this property binding.
  38112. *
  38113. * @type {number}
  38114. * @default 0
  38115. */
  38116. this.useCount = 0;
  38117. /**
  38118. * Number of keyframe tracks referencing this property binding.
  38119. *
  38120. * @type {number}
  38121. * @default 0
  38122. */
  38123. this.referenceCount = 0;
  38124. }
  38125. /**
  38126. * Accumulates data in the `incoming` region into `accu<i>`.
  38127. *
  38128. * @param {number} accuIndex - The accumulation index.
  38129. * @param {number} weight - The weight.
  38130. */
  38131. accumulate( accuIndex, weight ) {
  38132. // note: happily accumulating nothing when weight = 0, the caller knows
  38133. // the weight and shouldn't have made the call in the first place
  38134. const buffer = this.buffer,
  38135. stride = this.valueSize,
  38136. offset = accuIndex * stride + stride;
  38137. let currentWeight = this.cumulativeWeight;
  38138. if ( currentWeight === 0 ) {
  38139. // accuN := incoming * weight
  38140. for ( let i = 0; i !== stride; ++ i ) {
  38141. buffer[ offset + i ] = buffer[ i ];
  38142. }
  38143. currentWeight = weight;
  38144. } else {
  38145. // accuN := accuN + incoming * weight
  38146. currentWeight += weight;
  38147. const mix = weight / currentWeight;
  38148. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  38149. }
  38150. this.cumulativeWeight = currentWeight;
  38151. }
  38152. /**
  38153. * Accumulates data in the `incoming` region into `add`.
  38154. *
  38155. * @param {number} weight - The weight.
  38156. */
  38157. accumulateAdditive( weight ) {
  38158. const buffer = this.buffer,
  38159. stride = this.valueSize,
  38160. offset = stride * this._addIndex;
  38161. if ( this.cumulativeWeightAdditive === 0 ) {
  38162. // add = identity
  38163. this._setIdentity();
  38164. }
  38165. // add := add + incoming * weight
  38166. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  38167. this.cumulativeWeightAdditive += weight;
  38168. }
  38169. /**
  38170. * Applies the state of `accu<i>` to the binding when accus differ.
  38171. *
  38172. * @param {number} accuIndex - The accumulation index.
  38173. */
  38174. apply( accuIndex ) {
  38175. const stride = this.valueSize,
  38176. buffer = this.buffer,
  38177. offset = accuIndex * stride + stride,
  38178. weight = this.cumulativeWeight,
  38179. weightAdditive = this.cumulativeWeightAdditive,
  38180. binding = this.binding;
  38181. this.cumulativeWeight = 0;
  38182. this.cumulativeWeightAdditive = 0;
  38183. if ( weight < 1 ) {
  38184. // accuN := accuN + original * ( 1 - cumulativeWeight )
  38185. const originalValueOffset = stride * this._origIndex;
  38186. this._mixBufferRegion(
  38187. buffer, offset, originalValueOffset, 1 - weight, stride );
  38188. }
  38189. if ( weightAdditive > 0 ) {
  38190. // accuN := accuN + additive accuN
  38191. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  38192. }
  38193. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  38194. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  38195. // value has changed -> update scene graph
  38196. binding.setValue( buffer, offset );
  38197. break;
  38198. }
  38199. }
  38200. }
  38201. /**
  38202. * Remembers the state of the bound property and copy it to both accus.
  38203. */
  38204. saveOriginalState() {
  38205. const binding = this.binding;
  38206. const buffer = this.buffer,
  38207. stride = this.valueSize,
  38208. originalValueOffset = stride * this._origIndex;
  38209. binding.getValue( buffer, originalValueOffset );
  38210. // accu[0..1] := orig -- initially detect changes against the original
  38211. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  38212. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  38213. }
  38214. // Add to identity for additive
  38215. this._setIdentity();
  38216. this.cumulativeWeight = 0;
  38217. this.cumulativeWeightAdditive = 0;
  38218. }
  38219. /**
  38220. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  38221. */
  38222. restoreOriginalState() {
  38223. const originalValueOffset = this.valueSize * 3;
  38224. this.binding.setValue( this.buffer, originalValueOffset );
  38225. }
  38226. // internals
  38227. _setAdditiveIdentityNumeric() {
  38228. const startIndex = this._addIndex * this.valueSize;
  38229. const endIndex = startIndex + this.valueSize;
  38230. for ( let i = startIndex; i < endIndex; i ++ ) {
  38231. this.buffer[ i ] = 0;
  38232. }
  38233. }
  38234. _setAdditiveIdentityQuaternion() {
  38235. this._setAdditiveIdentityNumeric();
  38236. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  38237. }
  38238. _setAdditiveIdentityOther() {
  38239. const startIndex = this._origIndex * this.valueSize;
  38240. const targetIndex = this._addIndex * this.valueSize;
  38241. for ( let i = 0; i < this.valueSize; i ++ ) {
  38242. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  38243. }
  38244. }
  38245. // mix functions
  38246. _select( buffer, dstOffset, srcOffset, t, stride ) {
  38247. if ( t >= 0.5 ) {
  38248. for ( let i = 0; i !== stride; ++ i ) {
  38249. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  38250. }
  38251. }
  38252. }
  38253. _slerp( buffer, dstOffset, srcOffset, t ) {
  38254. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  38255. }
  38256. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  38257. const workOffset = this._workIndex * stride;
  38258. // Store result in intermediate buffer offset
  38259. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  38260. // Slerp to the intermediate result
  38261. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  38262. }
  38263. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  38264. const s = 1 - t;
  38265. for ( let i = 0; i !== stride; ++ i ) {
  38266. const j = dstOffset + i;
  38267. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  38268. }
  38269. }
  38270. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  38271. for ( let i = 0; i !== stride; ++ i ) {
  38272. const j = dstOffset + i;
  38273. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  38274. }
  38275. }
  38276. }
  38277. // Characters [].:/ are reserved for track binding syntax.
  38278. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  38279. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  38280. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  38281. // only latin characters, and the unicode \p{L} is not yet supported. So
  38282. // instead, we exclude reserved characters and match everything else.
  38283. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  38284. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  38285. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  38286. // be matched to parse the rest of the track name.
  38287. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  38288. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  38289. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  38290. // Object on target node, and accessor. May not contain reserved
  38291. // characters. Accessor may contain any character except closing bracket.
  38292. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  38293. // Property and accessor. May not contain reserved characters. Accessor may
  38294. // contain any non-bracket characters.
  38295. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  38296. const _trackRe = new RegExp( ''
  38297. + '^'
  38298. + _directoryRe
  38299. + _nodeRe
  38300. + _objectRe
  38301. + _propertyRe
  38302. + '$'
  38303. );
  38304. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  38305. class Composite {
  38306. constructor( targetGroup, path, optionalParsedPath ) {
  38307. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  38308. this._targetGroup = targetGroup;
  38309. this._bindings = targetGroup.subscribe_( path, parsedPath );
  38310. }
  38311. getValue( array, offset ) {
  38312. this.bind(); // bind all binding
  38313. const firstValidIndex = this._targetGroup.nCachedObjects_,
  38314. binding = this._bindings[ firstValidIndex ];
  38315. // and only call .getValue on the first
  38316. if ( binding !== undefined ) binding.getValue( array, offset );
  38317. }
  38318. setValue( array, offset ) {
  38319. const bindings = this._bindings;
  38320. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38321. bindings[ i ].setValue( array, offset );
  38322. }
  38323. }
  38324. bind() {
  38325. const bindings = this._bindings;
  38326. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38327. bindings[ i ].bind();
  38328. }
  38329. }
  38330. unbind() {
  38331. const bindings = this._bindings;
  38332. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  38333. bindings[ i ].unbind();
  38334. }
  38335. }
  38336. }
  38337. // Note: This class uses a State pattern on a per-method basis:
  38338. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  38339. // prototype version of these methods with one that represents
  38340. // the bound state. When the property is not found, the methods
  38341. // become no-ops.
  38342. /**
  38343. * This holds a reference to a real property in the scene graph; used internally.
  38344. */
  38345. class PropertyBinding {
  38346. /**
  38347. * Constructs a new property binding.
  38348. *
  38349. * @param {Object} rootNode - The root node.
  38350. * @param {string} path - The path.
  38351. * @param {?Object} [parsedPath] - The parsed path.
  38352. */
  38353. constructor( rootNode, path, parsedPath ) {
  38354. /**
  38355. * The object path to the animated property.
  38356. *
  38357. * @type {string}
  38358. */
  38359. this.path = path;
  38360. /**
  38361. * An object holding information about the path.
  38362. *
  38363. * @type {Object}
  38364. */
  38365. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  38366. /**
  38367. * The object owns the animated property.
  38368. *
  38369. * @type {?Object}
  38370. */
  38371. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  38372. /**
  38373. * The root node.
  38374. *
  38375. * @type {Object3D|Skeleton}
  38376. */
  38377. this.rootNode = rootNode;
  38378. // initial state of these methods that calls 'bind'
  38379. this.getValue = this._getValue_unbound;
  38380. this.setValue = this._setValue_unbound;
  38381. }
  38382. /**
  38383. * Factory method for creating a property binding from the given parameters.
  38384. *
  38385. * @static
  38386. * @param {Object} root - The root node.
  38387. * @param {string} path - The path.
  38388. * @param {?Object} [parsedPath] - The parsed path.
  38389. * @return {PropertyBinding|Composite} The created property binding or composite.
  38390. */
  38391. static create( root, path, parsedPath ) {
  38392. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  38393. return new PropertyBinding( root, path, parsedPath );
  38394. } else {
  38395. return new PropertyBinding.Composite( root, path, parsedPath );
  38396. }
  38397. }
  38398. /**
  38399. * Replaces spaces with underscores and removes unsupported characters from
  38400. * node names, to ensure compatibility with parseTrackName().
  38401. *
  38402. * @param {string} name - Node name to be sanitized.
  38403. * @return {string} The sanitized node name.
  38404. */
  38405. static sanitizeNodeName( name ) {
  38406. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  38407. }
  38408. /**
  38409. * Parses the given track name (an object path to an animated property) and
  38410. * returns an object with information about the path. Matches strings in the following forms:
  38411. *
  38412. * - nodeName.property
  38413. * - nodeName.property[accessor]
  38414. * - nodeName.material.property[accessor]
  38415. * - uuid.property[accessor]
  38416. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  38417. * - parentName/nodeName.property
  38418. * - parentName/parentName/nodeName.property[index]
  38419. * - .bone[Armature.DEF_cog].position
  38420. * - scene:helium_balloon_model:helium_balloon_model.position
  38421. *
  38422. * @static
  38423. * @param {string} trackName - The track name to parse.
  38424. * @return {Object} The parsed track name as an object.
  38425. */
  38426. static parseTrackName( trackName ) {
  38427. const matches = _trackRe.exec( trackName );
  38428. if ( matches === null ) {
  38429. throw new Error( 'THREE.PropertyBinding: Cannot parse trackName: ' + trackName );
  38430. }
  38431. const results = {
  38432. // directoryName: matches[ 1 ], // (tschw) currently unused
  38433. nodeName: matches[ 2 ],
  38434. objectName: matches[ 3 ],
  38435. objectIndex: matches[ 4 ],
  38436. propertyName: matches[ 5 ], // required
  38437. propertyIndex: matches[ 6 ]
  38438. };
  38439. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  38440. if ( lastDot !== undefined && lastDot !== -1 ) {
  38441. const objectName = results.nodeName.substring( lastDot + 1 );
  38442. // Object names must be checked against an allowlist. Otherwise, there
  38443. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  38444. // 'bar' could be the objectName, or part of a nodeName (which can
  38445. // include '.' characters).
  38446. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  38447. results.nodeName = results.nodeName.substring( 0, lastDot );
  38448. results.objectName = objectName;
  38449. }
  38450. }
  38451. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  38452. throw new Error( 'THREE.PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  38453. }
  38454. return results;
  38455. }
  38456. /**
  38457. * Searches for a node in the hierarchy of the given root object by the given
  38458. * node name.
  38459. *
  38460. * @static
  38461. * @param {Object} root - The root object.
  38462. * @param {string|number} nodeName - The name of the node.
  38463. * @return {?Object} The found node. Returns `null` if no object was found.
  38464. */
  38465. static findNode( root, nodeName ) {
  38466. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  38467. return root;
  38468. }
  38469. // search into skeleton bones.
  38470. if ( root.skeleton ) {
  38471. const bone = root.skeleton.getBoneByName( nodeName );
  38472. if ( bone !== undefined ) {
  38473. return bone;
  38474. }
  38475. }
  38476. // search into node subtree.
  38477. if ( root.children ) {
  38478. const searchNodeSubtree = function ( children ) {
  38479. for ( let i = 0; i < children.length; i ++ ) {
  38480. const childNode = children[ i ];
  38481. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  38482. return childNode;
  38483. }
  38484. const result = searchNodeSubtree( childNode.children );
  38485. if ( result ) return result;
  38486. }
  38487. return null;
  38488. };
  38489. const subTreeNode = searchNodeSubtree( root.children );
  38490. if ( subTreeNode ) {
  38491. return subTreeNode;
  38492. }
  38493. }
  38494. return null;
  38495. }
  38496. // these are used to "bind" a nonexistent property
  38497. _getValue_unavailable() {}
  38498. _setValue_unavailable() {}
  38499. // Getters
  38500. _getValue_direct( buffer, offset ) {
  38501. buffer[ offset ] = this.targetObject[ this.propertyName ];
  38502. }
  38503. _getValue_array( buffer, offset ) {
  38504. const source = this.resolvedProperty;
  38505. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  38506. buffer[ offset ++ ] = source[ i ];
  38507. }
  38508. }
  38509. _getValue_arrayElement( buffer, offset ) {
  38510. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  38511. }
  38512. _getValue_toArray( buffer, offset ) {
  38513. this.resolvedProperty.toArray( buffer, offset );
  38514. }
  38515. // Direct
  38516. _setValue_direct( buffer, offset ) {
  38517. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38518. }
  38519. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  38520. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38521. this.targetObject.needsUpdate = true;
  38522. }
  38523. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38524. this.targetObject[ this.propertyName ] = buffer[ offset ];
  38525. this.targetObject.matrixWorldNeedsUpdate = true;
  38526. }
  38527. // EntireArray
  38528. _setValue_array( buffer, offset ) {
  38529. const dest = this.resolvedProperty;
  38530. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38531. dest[ i ] = buffer[ offset ++ ];
  38532. }
  38533. }
  38534. _setValue_array_setNeedsUpdate( buffer, offset ) {
  38535. const dest = this.resolvedProperty;
  38536. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38537. dest[ i ] = buffer[ offset ++ ];
  38538. }
  38539. this.targetObject.needsUpdate = true;
  38540. }
  38541. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38542. const dest = this.resolvedProperty;
  38543. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  38544. dest[ i ] = buffer[ offset ++ ];
  38545. }
  38546. this.targetObject.matrixWorldNeedsUpdate = true;
  38547. }
  38548. // ArrayElement
  38549. _setValue_arrayElement( buffer, offset ) {
  38550. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38551. }
  38552. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  38553. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38554. this.targetObject.needsUpdate = true;
  38555. }
  38556. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38557. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  38558. this.targetObject.matrixWorldNeedsUpdate = true;
  38559. }
  38560. // HasToFromArray
  38561. _setValue_fromArray( buffer, offset ) {
  38562. this.resolvedProperty.fromArray( buffer, offset );
  38563. }
  38564. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  38565. this.resolvedProperty.fromArray( buffer, offset );
  38566. this.targetObject.needsUpdate = true;
  38567. }
  38568. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  38569. this.resolvedProperty.fromArray( buffer, offset );
  38570. this.targetObject.matrixWorldNeedsUpdate = true;
  38571. }
  38572. _getValue_unbound( targetArray, offset ) {
  38573. this.bind();
  38574. this.getValue( targetArray, offset );
  38575. }
  38576. _setValue_unbound( sourceArray, offset ) {
  38577. this.bind();
  38578. this.setValue( sourceArray, offset );
  38579. }
  38580. /**
  38581. * Creates a getter / setter pair for the property tracked by this binding.
  38582. */
  38583. bind() {
  38584. let targetObject = this.node;
  38585. const parsedPath = this.parsedPath;
  38586. const objectName = parsedPath.objectName;
  38587. const propertyName = parsedPath.propertyName;
  38588. let propertyIndex = parsedPath.propertyIndex;
  38589. if ( ! targetObject ) {
  38590. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  38591. this.node = targetObject;
  38592. }
  38593. // set fail state so we can just 'return' on error
  38594. this.getValue = this._getValue_unavailable;
  38595. this.setValue = this._setValue_unavailable;
  38596. // ensure there is a value node
  38597. if ( ! targetObject ) {
  38598. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  38599. return;
  38600. }
  38601. if ( objectName ) {
  38602. let objectIndex = parsedPath.objectIndex;
  38603. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  38604. switch ( objectName ) {
  38605. case 'materials':
  38606. if ( ! targetObject.material ) {
  38607. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38608. return;
  38609. }
  38610. if ( ! targetObject.material.materials ) {
  38611. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38612. return;
  38613. }
  38614. targetObject = targetObject.material.materials;
  38615. break;
  38616. case 'bones':
  38617. if ( ! targetObject.skeleton ) {
  38618. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38619. return;
  38620. }
  38621. // potential future optimization: skip this if propertyIndex is already an integer
  38622. // and convert the integer string to a true integer.
  38623. targetObject = targetObject.skeleton.bones;
  38624. // support resolving morphTarget names into indices.
  38625. for ( let i = 0; i < targetObject.length; i ++ ) {
  38626. if ( targetObject[ i ].name === objectIndex ) {
  38627. objectIndex = i;
  38628. break;
  38629. }
  38630. }
  38631. break;
  38632. case 'map':
  38633. if ( 'map' in targetObject ) {
  38634. targetObject = targetObject.map;
  38635. break;
  38636. }
  38637. if ( ! targetObject.material ) {
  38638. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38639. return;
  38640. }
  38641. if ( ! targetObject.material.map ) {
  38642. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38643. return;
  38644. }
  38645. targetObject = targetObject.material.map;
  38646. break;
  38647. default:
  38648. if ( targetObject[ objectName ] === undefined ) {
  38649. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38650. return;
  38651. }
  38652. targetObject = targetObject[ objectName ];
  38653. }
  38654. if ( objectIndex !== undefined ) {
  38655. if ( targetObject[ objectIndex ] === undefined ) {
  38656. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38657. return;
  38658. }
  38659. targetObject = targetObject[ objectIndex ];
  38660. }
  38661. }
  38662. // resolve property
  38663. const nodeProperty = targetObject[ propertyName ];
  38664. if ( nodeProperty === undefined ) {
  38665. const nodeName = parsedPath.nodeName;
  38666. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38667. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38668. return;
  38669. }
  38670. // determine versioning scheme
  38671. let versioning = this.Versioning.None;
  38672. this.targetObject = targetObject;
  38673. if ( targetObject.isMaterial === true ) {
  38674. versioning = this.Versioning.NeedsUpdate;
  38675. } else if ( targetObject.isObject3D === true ) {
  38676. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38677. }
  38678. // determine how the property gets bound
  38679. let bindingType = this.BindingType.Direct;
  38680. if ( propertyIndex !== undefined ) {
  38681. // access a sub element of the property array (only primitives are supported right now)
  38682. if ( propertyName === 'morphTargetInfluences' ) {
  38683. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38684. // support resolving morphTarget names into indices.
  38685. if ( ! targetObject.geometry ) {
  38686. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38687. return;
  38688. }
  38689. if ( ! targetObject.geometry.morphAttributes ) {
  38690. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38691. return;
  38692. }
  38693. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38694. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38695. }
  38696. }
  38697. bindingType = this.BindingType.ArrayElement;
  38698. this.resolvedProperty = nodeProperty;
  38699. this.propertyIndex = propertyIndex;
  38700. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38701. // must use copy for Object3D.Euler/Quaternion
  38702. bindingType = this.BindingType.HasFromToArray;
  38703. this.resolvedProperty = nodeProperty;
  38704. } else if ( Array.isArray( nodeProperty ) ) {
  38705. bindingType = this.BindingType.EntireArray;
  38706. this.resolvedProperty = nodeProperty;
  38707. } else {
  38708. this.propertyName = propertyName;
  38709. }
  38710. // select getter / setter
  38711. this.getValue = this.GetterByBindingType[ bindingType ];
  38712. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38713. }
  38714. /**
  38715. * Unbinds the property.
  38716. */
  38717. unbind() {
  38718. this.node = null;
  38719. // back to the prototype version of getValue / setValue
  38720. // note: avoiding to mutate the shape of 'this' via 'delete'
  38721. this.getValue = this._getValue_unbound;
  38722. this.setValue = this._setValue_unbound;
  38723. }
  38724. }
  38725. PropertyBinding.Composite = Composite;
  38726. PropertyBinding.prototype.BindingType = {
  38727. Direct: 0,
  38728. EntireArray: 1,
  38729. ArrayElement: 2,
  38730. HasFromToArray: 3
  38731. };
  38732. PropertyBinding.prototype.Versioning = {
  38733. None: 0,
  38734. NeedsUpdate: 1,
  38735. MatrixWorldNeedsUpdate: 2
  38736. };
  38737. PropertyBinding.prototype.GetterByBindingType = [
  38738. PropertyBinding.prototype._getValue_direct,
  38739. PropertyBinding.prototype._getValue_array,
  38740. PropertyBinding.prototype._getValue_arrayElement,
  38741. PropertyBinding.prototype._getValue_toArray,
  38742. ];
  38743. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38744. [
  38745. // Direct
  38746. PropertyBinding.prototype._setValue_direct,
  38747. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38748. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38749. ], [
  38750. // EntireArray
  38751. PropertyBinding.prototype._setValue_array,
  38752. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38753. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38754. ], [
  38755. // ArrayElement
  38756. PropertyBinding.prototype._setValue_arrayElement,
  38757. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38758. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38759. ], [
  38760. // HasToFromArray
  38761. PropertyBinding.prototype._setValue_fromArray,
  38762. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38763. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38764. ]
  38765. ];
  38766. /**
  38767. * A group of objects that receives a shared animation state.
  38768. *
  38769. * Usage:
  38770. *
  38771. * - Add objects you would otherwise pass as 'root' to the
  38772. * constructor or the .clipAction method of AnimationMixer.
  38773. * - Instead pass this object as 'root'.
  38774. * - You can also add and remove objects later when the mixer is running.
  38775. *
  38776. * Note:
  38777. *
  38778. * - Objects of this class appear as one object to the mixer,
  38779. * so cache control of the individual objects must be done on the group.
  38780. *
  38781. * Limitation:
  38782. *
  38783. * - The animated properties must be compatible among the all objects in the group.
  38784. * - A single property can either be controlled through a target group or directly, but not both.
  38785. */
  38786. class AnimationObjectGroup {
  38787. /**
  38788. * Constructs a new animation group.
  38789. *
  38790. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38791. */
  38792. constructor() {
  38793. /**
  38794. * This flag can be used for type testing.
  38795. *
  38796. * @type {boolean}
  38797. * @readonly
  38798. * @default true
  38799. */
  38800. this.isAnimationObjectGroup = true;
  38801. /**
  38802. * The UUID of the 3D object.
  38803. *
  38804. * @type {string}
  38805. * @readonly
  38806. */
  38807. this.uuid = generateUUID();
  38808. // cached objects followed by the active ones
  38809. this._objects = Array.prototype.slice.call( arguments );
  38810. this.nCachedObjects_ = 0; // threshold
  38811. // note: read by PropertyBinding.Composite
  38812. const indices = {};
  38813. this._indicesByUUID = indices; // for bookkeeping
  38814. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38815. indices[ arguments[ i ].uuid ] = i;
  38816. }
  38817. this._paths = []; // inside: string
  38818. this._parsedPaths = []; // inside: { we don't care, here }
  38819. this._bindings = []; // inside: Array< PropertyBinding >
  38820. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38821. const scope = this;
  38822. this.stats = {
  38823. objects: {
  38824. get total() {
  38825. return scope._objects.length;
  38826. },
  38827. get inUse() {
  38828. return this.total - scope.nCachedObjects_;
  38829. }
  38830. },
  38831. get bindingsPerObject() {
  38832. return scope._bindings.length;
  38833. }
  38834. };
  38835. }
  38836. /**
  38837. * Adds an arbitrary number of objects to this animation group.
  38838. *
  38839. * @param {...Object3D} arguments - The 3D objects to add.
  38840. */
  38841. add() {
  38842. const objects = this._objects,
  38843. indicesByUUID = this._indicesByUUID,
  38844. paths = this._paths,
  38845. parsedPaths = this._parsedPaths,
  38846. bindings = this._bindings,
  38847. nBindings = bindings.length;
  38848. let knownObject = undefined,
  38849. nObjects = objects.length,
  38850. nCachedObjects = this.nCachedObjects_;
  38851. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38852. const object = arguments[ i ],
  38853. uuid = object.uuid;
  38854. let index = indicesByUUID[ uuid ];
  38855. if ( index === undefined ) {
  38856. // unknown object -> add it to the ACTIVE region
  38857. index = nObjects ++;
  38858. indicesByUUID[ uuid ] = index;
  38859. objects.push( object );
  38860. // accounting is done, now do the same for all bindings
  38861. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38862. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38863. }
  38864. } else if ( index < nCachedObjects ) {
  38865. knownObject = objects[ index ];
  38866. // move existing object to the ACTIVE region
  38867. const firstActiveIndex = -- nCachedObjects,
  38868. lastCachedObject = objects[ firstActiveIndex ];
  38869. indicesByUUID[ lastCachedObject.uuid ] = index;
  38870. objects[ index ] = lastCachedObject;
  38871. indicesByUUID[ uuid ] = firstActiveIndex;
  38872. objects[ firstActiveIndex ] = object;
  38873. // accounting is done, now do the same for all bindings
  38874. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38875. const bindingsForPath = bindings[ j ],
  38876. lastCached = bindingsForPath[ firstActiveIndex ];
  38877. let binding = bindingsForPath[ index ];
  38878. bindingsForPath[ index ] = lastCached;
  38879. if ( binding === undefined ) {
  38880. // since we do not bother to create new bindings
  38881. // for objects that are cached, the binding may
  38882. // or may not exist
  38883. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38884. }
  38885. bindingsForPath[ firstActiveIndex ] = binding;
  38886. }
  38887. } else if ( objects[ index ] !== knownObject ) {
  38888. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38889. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38890. } // else the object is already where we want it to be
  38891. } // for arguments
  38892. this.nCachedObjects_ = nCachedObjects;
  38893. }
  38894. /**
  38895. * Removes an arbitrary number of objects to this animation group
  38896. *
  38897. * @param {...Object3D} arguments - The 3D objects to remove.
  38898. */
  38899. remove() {
  38900. const objects = this._objects,
  38901. indicesByUUID = this._indicesByUUID,
  38902. bindings = this._bindings,
  38903. nBindings = bindings.length;
  38904. let nCachedObjects = this.nCachedObjects_;
  38905. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38906. const object = arguments[ i ],
  38907. uuid = object.uuid,
  38908. index = indicesByUUID[ uuid ];
  38909. if ( index !== undefined && index >= nCachedObjects ) {
  38910. // move existing object into the CACHED region
  38911. const lastCachedIndex = nCachedObjects ++,
  38912. firstActiveObject = objects[ lastCachedIndex ];
  38913. indicesByUUID[ firstActiveObject.uuid ] = index;
  38914. objects[ index ] = firstActiveObject;
  38915. indicesByUUID[ uuid ] = lastCachedIndex;
  38916. objects[ lastCachedIndex ] = object;
  38917. // accounting is done, now do the same for all bindings
  38918. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38919. const bindingsForPath = bindings[ j ],
  38920. firstActive = bindingsForPath[ lastCachedIndex ],
  38921. binding = bindingsForPath[ index ];
  38922. bindingsForPath[ index ] = firstActive;
  38923. bindingsForPath[ lastCachedIndex ] = binding;
  38924. }
  38925. }
  38926. } // for arguments
  38927. this.nCachedObjects_ = nCachedObjects;
  38928. }
  38929. /**
  38930. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38931. *
  38932. * @param {...Object3D} arguments - The 3D objects to uncache.
  38933. */
  38934. uncache() {
  38935. const objects = this._objects,
  38936. indicesByUUID = this._indicesByUUID,
  38937. bindings = this._bindings,
  38938. nBindings = bindings.length;
  38939. let nCachedObjects = this.nCachedObjects_,
  38940. nObjects = objects.length;
  38941. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38942. const object = arguments[ i ],
  38943. uuid = object.uuid,
  38944. index = indicesByUUID[ uuid ];
  38945. if ( index !== undefined ) {
  38946. delete indicesByUUID[ uuid ];
  38947. if ( index < nCachedObjects ) {
  38948. // object is cached, shrink the CACHED region
  38949. const firstActiveIndex = -- nCachedObjects,
  38950. lastCachedObject = objects[ firstActiveIndex ],
  38951. lastIndex = -- nObjects,
  38952. lastObject = objects[ lastIndex ];
  38953. // last cached object takes this object's place
  38954. indicesByUUID[ lastCachedObject.uuid ] = index;
  38955. objects[ index ] = lastCachedObject;
  38956. // last object goes to the activated slot and pop
  38957. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38958. objects[ firstActiveIndex ] = lastObject;
  38959. objects.pop();
  38960. // accounting is done, now do the same for all bindings
  38961. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38962. const bindingsForPath = bindings[ j ],
  38963. lastCached = bindingsForPath[ firstActiveIndex ],
  38964. last = bindingsForPath[ lastIndex ];
  38965. bindingsForPath[ index ] = lastCached;
  38966. bindingsForPath[ firstActiveIndex ] = last;
  38967. bindingsForPath.pop();
  38968. }
  38969. } else {
  38970. // object is active, just swap with the last and pop
  38971. const lastIndex = -- nObjects,
  38972. lastObject = objects[ lastIndex ];
  38973. if ( lastIndex > 0 ) {
  38974. indicesByUUID[ lastObject.uuid ] = index;
  38975. }
  38976. objects[ index ] = lastObject;
  38977. objects.pop();
  38978. // accounting is done, now do the same for all bindings
  38979. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38980. const bindingsForPath = bindings[ j ];
  38981. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38982. bindingsForPath.pop();
  38983. }
  38984. } // cached or active
  38985. } // if object is known
  38986. } // for arguments
  38987. this.nCachedObjects_ = nCachedObjects;
  38988. }
  38989. // Internal interface used by befriended PropertyBinding.Composite:
  38990. subscribe_( path, parsedPath ) {
  38991. // returns an array of bindings for the given path that is changed
  38992. // according to the contained objects in the group
  38993. const indicesByPath = this._bindingsIndicesByPath;
  38994. let index = indicesByPath[ path ];
  38995. const bindings = this._bindings;
  38996. if ( index !== undefined ) return bindings[ index ];
  38997. const paths = this._paths,
  38998. parsedPaths = this._parsedPaths,
  38999. objects = this._objects,
  39000. nObjects = objects.length,
  39001. nCachedObjects = this.nCachedObjects_,
  39002. bindingsForPath = new Array( nObjects );
  39003. index = bindings.length;
  39004. indicesByPath[ path ] = index;
  39005. paths.push( path );
  39006. parsedPaths.push( parsedPath );
  39007. bindings.push( bindingsForPath );
  39008. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  39009. const object = objects[ i ];
  39010. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  39011. }
  39012. return bindingsForPath;
  39013. }
  39014. unsubscribe_( path ) {
  39015. // tells the group to forget about a property path and no longer
  39016. // update the array previously obtained with 'subscribe_'
  39017. const indicesByPath = this._bindingsIndicesByPath,
  39018. index = indicesByPath[ path ];
  39019. if ( index !== undefined ) {
  39020. const paths = this._paths,
  39021. parsedPaths = this._parsedPaths,
  39022. bindings = this._bindings,
  39023. lastBindingsIndex = bindings.length - 1,
  39024. lastBindings = bindings[ lastBindingsIndex ],
  39025. lastBindingsPath = path[ lastBindingsIndex ];
  39026. indicesByPath[ lastBindingsPath ] = index;
  39027. bindings[ index ] = lastBindings;
  39028. bindings.pop();
  39029. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  39030. parsedPaths.pop();
  39031. paths[ index ] = paths[ lastBindingsIndex ];
  39032. paths.pop();
  39033. }
  39034. }
  39035. }
  39036. /**
  39037. * An instance of `AnimationAction` schedules the playback of an animation which is
  39038. * stored in {@link AnimationClip}.
  39039. */
  39040. class AnimationAction {
  39041. /**
  39042. * Constructs a new animation action.
  39043. *
  39044. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  39045. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  39046. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  39047. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39048. */
  39049. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  39050. this._mixer = mixer;
  39051. this._clip = clip;
  39052. this._localRoot = localRoot;
  39053. /**
  39054. * Defines how the animation is blended/combined when two or more animations
  39055. * are simultaneously played.
  39056. *
  39057. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  39058. */
  39059. this.blendMode = blendMode;
  39060. const tracks = clip.tracks,
  39061. nTracks = tracks.length,
  39062. interpolants = new Array( nTracks );
  39063. const interpolantSettings = {
  39064. endingStart: ZeroCurvatureEnding,
  39065. endingEnd: ZeroCurvatureEnding
  39066. };
  39067. for ( let i = 0; i !== nTracks; ++ i ) {
  39068. const interpolant = tracks[ i ].createInterpolant( null );
  39069. interpolants[ i ] = interpolant;
  39070. interpolant.settings = interpolantSettings;
  39071. }
  39072. this._interpolantSettings = interpolantSettings;
  39073. this._interpolants = interpolants; // bound by the mixer
  39074. // inside: PropertyMixer (managed by the mixer)
  39075. this._propertyBindings = new Array( nTracks );
  39076. this._cacheIndex = null; // for the memory manager
  39077. this._byClipCacheIndex = null; // for the memory manager
  39078. this._timeScaleInterpolant = null;
  39079. this._restoreTimeScale = null;
  39080. this._weightInterpolant = null;
  39081. /**
  39082. * The loop mode, set via {@link AnimationAction#setLoop}.
  39083. *
  39084. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  39085. * @default LoopRepeat
  39086. */
  39087. this.loop = LoopRepeat;
  39088. this._loopCount = -1;
  39089. // global mixer time when the action is to be started
  39090. // it's set back to 'null' upon start of the action
  39091. this._startTime = null;
  39092. /**
  39093. * The local time of this action (in seconds, starting with `0`).
  39094. *
  39095. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  39096. * loop state).
  39097. *
  39098. * @type {number}
  39099. * @default Infinity
  39100. */
  39101. this.time = 0;
  39102. /**
  39103. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  39104. * animation to pause. Negative values cause the animation to play backwards.
  39105. *
  39106. * @type {number}
  39107. * @default 1
  39108. */
  39109. this.timeScale = 1;
  39110. this._effectiveTimeScale = 1;
  39111. /**
  39112. * The degree of influence of this action (in the interval `[0, 1]`). Values
  39113. * between `0` (no impact) and `1` (full impact) can be used to blend between
  39114. * several actions.
  39115. *
  39116. * @type {number}
  39117. * @default 1
  39118. */
  39119. this.weight = 1;
  39120. this._effectiveWeight = 1;
  39121. /**
  39122. * The number of repetitions of the performed clip over the course of this action.
  39123. * Can be set via {@link AnimationAction#setLoop}.
  39124. *
  39125. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  39126. * `THREE:LoopOnce`.
  39127. *
  39128. * @type {number}
  39129. * @default Infinity
  39130. */
  39131. this.repetitions = Infinity;
  39132. /**
  39133. * If set to `true`, the playback of the action is paused.
  39134. *
  39135. * @type {boolean}
  39136. * @default false
  39137. */
  39138. this.paused = false;
  39139. /**
  39140. * If set to `false`, the action is disabled so it has no impact.
  39141. *
  39142. * When the action is re-enabled, the animation continues from its current
  39143. * time (setting `enabled` to `false` doesn't reset the action).
  39144. *
  39145. * @type {boolean}
  39146. * @default true
  39147. */
  39148. this.enabled = true;
  39149. /**
  39150. * If set to true the animation will automatically be paused on its last frame.
  39151. *
  39152. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  39153. * to `false` when the last loop of the action has finished, so that this action has
  39154. * no further impact.
  39155. *
  39156. * Note: This member has no impact if the action is interrupted (it
  39157. * has only an effect if its last loop has really finished).
  39158. *
  39159. * @type {boolean}
  39160. * @default false
  39161. */
  39162. this.clampWhenFinished = false;
  39163. /**
  39164. * Enables smooth interpolation without separate clips for start, loop and end.
  39165. *
  39166. * @type {boolean}
  39167. * @default true
  39168. */
  39169. this.zeroSlopeAtStart = true;
  39170. /**
  39171. * Enables smooth interpolation without separate clips for start, loop and end.
  39172. *
  39173. * @type {boolean}
  39174. * @default true
  39175. */
  39176. this.zeroSlopeAtEnd = true;
  39177. }
  39178. /**
  39179. * Starts the playback of the animation.
  39180. *
  39181. * @return {AnimationAction} A reference to this animation action.
  39182. */
  39183. play() {
  39184. this._mixer._activateAction( this );
  39185. return this;
  39186. }
  39187. /**
  39188. * Stops the playback of the animation.
  39189. *
  39190. * @return {AnimationAction} A reference to this animation action.
  39191. */
  39192. stop() {
  39193. this._mixer._deactivateAction( this );
  39194. return this.reset();
  39195. }
  39196. /**
  39197. * Resets the playback of the animation.
  39198. *
  39199. * @return {AnimationAction} A reference to this animation action.
  39200. */
  39201. reset() {
  39202. this.paused = false;
  39203. this.enabled = true;
  39204. this.time = 0; // restart clip
  39205. this._loopCount = -1;// forget previous loops
  39206. this._startTime = null;// forget scheduling
  39207. return this.stopFading().stopWarping();
  39208. }
  39209. /**
  39210. * Returns `true` if the animation is running.
  39211. *
  39212. * @return {boolean} Whether the animation is running or not.
  39213. */
  39214. isRunning() {
  39215. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  39216. this._startTime === null && this._mixer._isActiveAction( this );
  39217. }
  39218. /**
  39219. * Returns `true` when {@link AnimationAction#play} has been called.
  39220. *
  39221. * @return {boolean} Whether the animation is scheduled or not.
  39222. */
  39223. isScheduled() {
  39224. return this._mixer._isActiveAction( this );
  39225. }
  39226. /**
  39227. * Defines the time when the animation should start.
  39228. *
  39229. * @param {number} time - The start time in seconds.
  39230. * @return {AnimationAction} A reference to this animation action.
  39231. */
  39232. startAt( time ) {
  39233. this._startTime = time;
  39234. return this;
  39235. }
  39236. /**
  39237. * Configures the loop settings for this action.
  39238. *
  39239. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  39240. * @param {number} repetitions - The number of repetitions.
  39241. * @return {AnimationAction} A reference to this animation action.
  39242. */
  39243. setLoop( mode, repetitions ) {
  39244. this.loop = mode;
  39245. this.repetitions = repetitions;
  39246. return this;
  39247. }
  39248. /**
  39249. * Sets the effective weight of this action.
  39250. *
  39251. * An action has no effect and thus an effective weight of zero when the
  39252. * action is disabled.
  39253. *
  39254. * @param {number} weight - The weight to set.
  39255. * @return {AnimationAction} A reference to this animation action.
  39256. */
  39257. setEffectiveWeight( weight ) {
  39258. this.weight = weight;
  39259. // note: same logic as when updated at runtime
  39260. this._effectiveWeight = this.enabled ? weight : 0;
  39261. return this.stopFading();
  39262. }
  39263. /**
  39264. * Returns the effective weight of this action.
  39265. *
  39266. * @return {number} The effective weight.
  39267. */
  39268. getEffectiveWeight() {
  39269. return this._effectiveWeight;
  39270. }
  39271. /**
  39272. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  39273. * within the passed time interval.
  39274. *
  39275. * @param {number} duration - The duration of the fade.
  39276. * @return {AnimationAction} A reference to this animation action.
  39277. */
  39278. fadeIn( duration ) {
  39279. return this._scheduleFading( duration, 0, 1 );
  39280. }
  39281. /**
  39282. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  39283. * within the passed time interval.
  39284. *
  39285. * @param {number} duration - The duration of the fade.
  39286. * @return {AnimationAction} A reference to this animation action.
  39287. */
  39288. fadeOut( duration ) {
  39289. return this._scheduleFading( duration, 1, 0 );
  39290. }
  39291. /**
  39292. * Causes this action to fade in and the given action to fade out,
  39293. * within the passed time interval.
  39294. *
  39295. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  39296. * @param {number} duration - The duration of the fade.
  39297. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39298. * @return {AnimationAction} A reference to this animation action.
  39299. */
  39300. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  39301. fadeOutAction.fadeOut( duration );
  39302. this.fadeIn( duration );
  39303. if ( warp === true ) {
  39304. const fadeInDuration = this._clip.duration,
  39305. fadeOutDuration = fadeOutAction._clip.duration,
  39306. startEndRatio = fadeOutDuration / fadeInDuration,
  39307. endStartRatio = fadeInDuration / fadeOutDuration;
  39308. fadeOutAction._restoreTimeScale = fadeOutAction.timeScale;
  39309. this._restoreTimeScale = this.timeScale;
  39310. fadeOutAction.warp( 1.0, startEndRatio, duration );
  39311. this.warp( endStartRatio, 1.0, duration );
  39312. }
  39313. return this;
  39314. }
  39315. /**
  39316. * Causes this action to fade out and the given action to fade in,
  39317. * within the passed time interval.
  39318. *
  39319. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  39320. * @param {number} duration - The duration of the fade.
  39321. * @param {boolean} [warp=false] - Whether warping should be used or not.
  39322. * @return {AnimationAction} A reference to this animation action.
  39323. */
  39324. crossFadeTo( fadeInAction, duration, warp = false ) {
  39325. return fadeInAction.crossFadeFrom( this, duration, warp );
  39326. }
  39327. /**
  39328. * Stops any fading which is applied to this action.
  39329. *
  39330. * @return {AnimationAction} A reference to this animation action.
  39331. */
  39332. stopFading() {
  39333. const weightInterpolant = this._weightInterpolant;
  39334. if ( weightInterpolant !== null ) {
  39335. this._weightInterpolant = null;
  39336. this._mixer._takeBackControlInterpolant( weightInterpolant );
  39337. }
  39338. return this;
  39339. }
  39340. /**
  39341. * Sets the effective time scale of this action.
  39342. *
  39343. * An action has no effect and thus an effective time scale of zero when the
  39344. * action is paused.
  39345. *
  39346. * @param {number} timeScale - The time scale to set.
  39347. * @return {AnimationAction} A reference to this animation action.
  39348. */
  39349. setEffectiveTimeScale( timeScale ) {
  39350. this.timeScale = timeScale;
  39351. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  39352. return this.stopWarping();
  39353. }
  39354. /**
  39355. * Returns the effective time scale of this action.
  39356. *
  39357. * @return {number} The effective time scale.
  39358. */
  39359. getEffectiveTimeScale() {
  39360. return this._effectiveTimeScale;
  39361. }
  39362. /**
  39363. * Sets the duration for a single loop of this action.
  39364. *
  39365. * @param {number} duration - The duration to set.
  39366. * @return {AnimationAction} A reference to this animation action.
  39367. */
  39368. setDuration( duration ) {
  39369. this.timeScale = this._clip.duration / duration;
  39370. return this.stopWarping();
  39371. }
  39372. /**
  39373. * Synchronizes this action with the passed other action.
  39374. *
  39375. * @param {AnimationAction} action - The action to sync with.
  39376. * @return {AnimationAction} A reference to this animation action.
  39377. */
  39378. syncWith( action ) {
  39379. this.time = action.time;
  39380. this.timeScale = action.timeScale;
  39381. return this.stopWarping();
  39382. }
  39383. /**
  39384. * Decelerates this animation's speed to `0` within the passed time interval.
  39385. *
  39386. * @param {number} duration - The duration.
  39387. * @return {AnimationAction} A reference to this animation action.
  39388. */
  39389. halt( duration ) {
  39390. return this.warp( this._effectiveTimeScale, 0, duration );
  39391. }
  39392. /**
  39393. * Changes the playback speed, within the passed time interval, by modifying
  39394. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  39395. * `endTimeScale`.
  39396. *
  39397. * @param {number} startTimeScale - The start time scale.
  39398. * @param {number} endTimeScale - The end time scale.
  39399. * @param {number} duration - The duration.
  39400. * @return {AnimationAction} A reference to this animation action.
  39401. */
  39402. warp( startTimeScale, endTimeScale, duration ) {
  39403. const mixer = this._mixer,
  39404. now = mixer.time,
  39405. timeScale = this.timeScale;
  39406. let interpolant = this._timeScaleInterpolant;
  39407. if ( interpolant === null ) {
  39408. interpolant = mixer._lendControlInterpolant();
  39409. this._timeScaleInterpolant = interpolant;
  39410. }
  39411. const times = interpolant.parameterPositions,
  39412. values = interpolant.sampleValues;
  39413. times[ 0 ] = now;
  39414. times[ 1 ] = now + duration;
  39415. values[ 0 ] = startTimeScale / timeScale;
  39416. values[ 1 ] = endTimeScale / timeScale;
  39417. return this;
  39418. }
  39419. /**
  39420. * Stops any scheduled warping which is applied to this action.
  39421. *
  39422. * @return {AnimationAction} A reference to this animation action.
  39423. */
  39424. stopWarping() {
  39425. const timeScaleInterpolant = this._timeScaleInterpolant;
  39426. if ( timeScaleInterpolant !== null ) {
  39427. this._timeScaleInterpolant = null;
  39428. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  39429. }
  39430. this._restoreTimeScale = null;
  39431. return this;
  39432. }
  39433. /**
  39434. * Returns the animation mixer of this animation action.
  39435. *
  39436. * @return {AnimationMixer} The animation mixer.
  39437. */
  39438. getMixer() {
  39439. return this._mixer;
  39440. }
  39441. /**
  39442. * Returns the animation clip of this animation action.
  39443. *
  39444. * @return {AnimationClip} The animation clip.
  39445. */
  39446. getClip() {
  39447. return this._clip;
  39448. }
  39449. /**
  39450. * Returns the root object of this animation action.
  39451. *
  39452. * @return {Object3D} The root object.
  39453. */
  39454. getRoot() {
  39455. return this._localRoot || this._mixer._root;
  39456. }
  39457. // Internal
  39458. _update( time, deltaTime, timeDirection, accuIndex ) {
  39459. // called by the mixer
  39460. if ( ! this.enabled ) {
  39461. // call ._updateWeight() to update ._effectiveWeight
  39462. this._updateWeight( time );
  39463. return;
  39464. }
  39465. const startTime = this._startTime;
  39466. if ( startTime !== null ) {
  39467. // check for scheduled start of action
  39468. const timeRunning = ( time - startTime ) * timeDirection;
  39469. if ( timeRunning < 0 || timeDirection === 0 ) {
  39470. deltaTime = 0;
  39471. } else {
  39472. this._startTime = null; // unschedule
  39473. deltaTime = timeDirection * timeRunning;
  39474. }
  39475. }
  39476. // apply time scale and advance time
  39477. deltaTime *= this._updateTimeScale( time );
  39478. const clipTime = this._updateTime( deltaTime );
  39479. // note: _updateTime may disable the action resulting in
  39480. // an effective weight of 0
  39481. const weight = this._updateWeight( time );
  39482. if ( weight > 0 ) {
  39483. const interpolants = this._interpolants;
  39484. const propertyMixers = this._propertyBindings;
  39485. switch ( this.blendMode ) {
  39486. case AdditiveAnimationBlendMode:
  39487. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39488. interpolants[ j ].evaluate( clipTime );
  39489. propertyMixers[ j ].accumulateAdditive( weight );
  39490. }
  39491. break;
  39492. case NormalAnimationBlendMode:
  39493. default:
  39494. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  39495. interpolants[ j ].evaluate( clipTime );
  39496. propertyMixers[ j ].accumulate( accuIndex, weight );
  39497. }
  39498. }
  39499. }
  39500. }
  39501. _updateWeight( time ) {
  39502. let weight = 0;
  39503. if ( this.enabled ) {
  39504. weight = this.weight;
  39505. const interpolant = this._weightInterpolant;
  39506. if ( interpolant !== null ) {
  39507. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39508. weight *= interpolantValue;
  39509. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39510. this.stopFading();
  39511. if ( interpolantValue === 0 ) {
  39512. // faded out, disable
  39513. this.enabled = false;
  39514. }
  39515. }
  39516. }
  39517. }
  39518. this._effectiveWeight = weight;
  39519. return weight;
  39520. }
  39521. _updateTimeScale( time ) {
  39522. let timeScale = 0;
  39523. if ( ! this.paused ) {
  39524. timeScale = this.timeScale;
  39525. const interpolant = this._timeScaleInterpolant;
  39526. if ( interpolant !== null ) {
  39527. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  39528. timeScale *= interpolantValue;
  39529. if ( time > interpolant.parameterPositions[ 1 ] ) {
  39530. if ( timeScale === 0 ) {
  39531. // motion has halted, pause
  39532. this.paused = true;
  39533. } else {
  39534. if ( this._restoreTimeScale !== null ) {
  39535. timeScale = this._restoreTimeScale;
  39536. }
  39537. // warp done - apply final time scale
  39538. this.timeScale = timeScale;
  39539. }
  39540. this.stopWarping();
  39541. }
  39542. }
  39543. }
  39544. this._effectiveTimeScale = timeScale;
  39545. return timeScale;
  39546. }
  39547. _updateTime( deltaTime ) {
  39548. const duration = this._clip.duration;
  39549. const loop = this.loop;
  39550. let time = this.time + deltaTime;
  39551. let loopCount = this._loopCount;
  39552. const pingPong = ( loop === LoopPingPong );
  39553. if ( deltaTime === 0 ) {
  39554. if ( loopCount === -1 ) return time;
  39555. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  39556. }
  39557. if ( loop === LoopOnce ) {
  39558. if ( loopCount === -1 ) {
  39559. // just started
  39560. this._loopCount = 0;
  39561. this._setEndings( true, true, false );
  39562. }
  39563. handle_stop: {
  39564. if ( time >= duration ) {
  39565. time = duration;
  39566. } else if ( time < 0 ) {
  39567. time = 0;
  39568. } else {
  39569. this.time = time;
  39570. break handle_stop;
  39571. }
  39572. if ( this.clampWhenFinished ) this.paused = true;
  39573. else this.enabled = false;
  39574. this.time = time;
  39575. this._mixer.dispatchEvent( {
  39576. type: 'finished', action: this,
  39577. direction: deltaTime < 0 ? -1 : 1
  39578. } );
  39579. }
  39580. } else { // repetitive Repeat or PingPong
  39581. if ( loopCount === -1 ) {
  39582. // just started
  39583. if ( deltaTime >= 0 ) {
  39584. loopCount = 0;
  39585. this._setEndings( true, this.repetitions === 0, pingPong );
  39586. } else {
  39587. // when looping in reverse direction, the initial
  39588. // transition through zero counts as a repetition,
  39589. // so leave loopCount at -1
  39590. this._setEndings( this.repetitions === 0, true, pingPong );
  39591. }
  39592. }
  39593. if ( time >= duration || time < 0 ) {
  39594. // wrap around
  39595. const loopDelta = Math.floor( time / duration ); // signed
  39596. time -= duration * loopDelta;
  39597. loopCount += Math.abs( loopDelta );
  39598. const pending = this.repetitions - loopCount;
  39599. if ( pending <= 0 ) {
  39600. // have to stop (switch state, clamp time, fire event)
  39601. if ( this.clampWhenFinished ) this.paused = true;
  39602. else this.enabled = false;
  39603. time = deltaTime > 0 ? duration : 0;
  39604. this.time = time;
  39605. this._mixer.dispatchEvent( {
  39606. type: 'finished', action: this,
  39607. direction: deltaTime > 0 ? 1 : -1
  39608. } );
  39609. } else {
  39610. // keep running
  39611. if ( pending === 1 ) {
  39612. // entering the last round
  39613. const atStart = deltaTime < 0;
  39614. this._setEndings( atStart, ! atStart, pingPong );
  39615. } else {
  39616. this._setEndings( false, false, pingPong );
  39617. }
  39618. this._loopCount = loopCount;
  39619. this.time = time;
  39620. this._mixer.dispatchEvent( {
  39621. type: 'loop', action: this, loopDelta: loopDelta
  39622. } );
  39623. }
  39624. } else {
  39625. this._loopCount = loopCount;
  39626. this.time = time;
  39627. }
  39628. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39629. // invert time for the "pong round"
  39630. return duration - time;
  39631. }
  39632. }
  39633. return time;
  39634. }
  39635. _setEndings( atStart, atEnd, pingPong ) {
  39636. const settings = this._interpolantSettings;
  39637. if ( pingPong ) {
  39638. settings.endingStart = ZeroSlopeEnding;
  39639. settings.endingEnd = ZeroSlopeEnding;
  39640. } else {
  39641. // assuming for LoopOnce atStart == atEnd == true
  39642. if ( atStart ) {
  39643. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39644. } else {
  39645. settings.endingStart = WrapAroundEnding;
  39646. }
  39647. if ( atEnd ) {
  39648. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39649. } else {
  39650. settings.endingEnd = WrapAroundEnding;
  39651. }
  39652. }
  39653. }
  39654. _scheduleFading( duration, weightNow, weightThen ) {
  39655. const mixer = this._mixer, now = mixer.time;
  39656. let interpolant = this._weightInterpolant;
  39657. if ( interpolant === null ) {
  39658. interpolant = mixer._lendControlInterpolant();
  39659. this._weightInterpolant = interpolant;
  39660. }
  39661. const times = interpolant.parameterPositions,
  39662. values = interpolant.sampleValues;
  39663. times[ 0 ] = now;
  39664. values[ 0 ] = weightNow;
  39665. times[ 1 ] = now + duration;
  39666. values[ 1 ] = weightThen;
  39667. return this;
  39668. }
  39669. }
  39670. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39671. /**
  39672. * `AnimationMixer` is a player for animations on a particular object in
  39673. * the scene. When multiple objects in the scene are animated independently,
  39674. * one `AnimationMixer` may be used for each object.
  39675. */
  39676. class AnimationMixer extends EventDispatcher {
  39677. /**
  39678. * Constructs a new animation mixer.
  39679. *
  39680. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39681. */
  39682. constructor( root ) {
  39683. super();
  39684. this._root = root;
  39685. this._initMemoryManager();
  39686. this._accuIndex = 0;
  39687. /**
  39688. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39689. *
  39690. * @type {number}
  39691. * @default 0
  39692. */
  39693. this.time = 0;
  39694. /**
  39695. * A scaling factor for the global time.
  39696. *
  39697. * Note: Setting this member to `0` and later back to `1` is a
  39698. * possibility to pause/unpause all actions that are controlled by this
  39699. * mixer.
  39700. *
  39701. * @type {number}
  39702. * @default 1
  39703. */
  39704. this.timeScale = 1.0;
  39705. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39706. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39707. }
  39708. }
  39709. _bindAction( action, prototypeAction ) {
  39710. const root = action._localRoot || this._root,
  39711. tracks = action._clip.tracks,
  39712. nTracks = tracks.length,
  39713. bindings = action._propertyBindings,
  39714. interpolants = action._interpolants,
  39715. rootUuid = root.uuid,
  39716. bindingsByRoot = this._bindingsByRootAndName;
  39717. let bindingsByName = bindingsByRoot[ rootUuid ];
  39718. if ( bindingsByName === undefined ) {
  39719. bindingsByName = {};
  39720. bindingsByRoot[ rootUuid ] = bindingsByName;
  39721. }
  39722. for ( let i = 0; i !== nTracks; ++ i ) {
  39723. const track = tracks[ i ],
  39724. trackName = track.name;
  39725. let binding = bindingsByName[ trackName ];
  39726. if ( binding !== undefined ) {
  39727. ++ binding.referenceCount;
  39728. bindings[ i ] = binding;
  39729. } else {
  39730. binding = bindings[ i ];
  39731. if ( binding !== undefined ) {
  39732. // existing binding, make sure the cache knows
  39733. if ( binding._cacheIndex === null ) {
  39734. ++ binding.referenceCount;
  39735. this._addInactiveBinding( binding, rootUuid, trackName );
  39736. }
  39737. continue;
  39738. }
  39739. const path = prototypeAction && prototypeAction.
  39740. _propertyBindings[ i ].binding.parsedPath;
  39741. binding = new PropertyMixer(
  39742. PropertyBinding.create( root, trackName, path ),
  39743. track.ValueTypeName, track.getValueSize() );
  39744. ++ binding.referenceCount;
  39745. this._addInactiveBinding( binding, rootUuid, trackName );
  39746. bindings[ i ] = binding;
  39747. }
  39748. interpolants[ i ].resultBuffer = binding.buffer;
  39749. }
  39750. }
  39751. _activateAction( action ) {
  39752. if ( ! this._isActiveAction( action ) ) {
  39753. if ( action._cacheIndex === null ) {
  39754. // this action has been forgotten by the cache, but the user
  39755. // appears to be still using it -> rebind
  39756. const rootUuid = ( action._localRoot || this._root ).uuid,
  39757. clipUuid = action._clip.uuid,
  39758. actionsForClip = this._actionsByClip[ clipUuid ];
  39759. this._bindAction( action,
  39760. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39761. this._addInactiveAction( action, clipUuid, rootUuid );
  39762. }
  39763. const bindings = action._propertyBindings;
  39764. // increment reference counts / sort out state
  39765. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39766. const binding = bindings[ i ];
  39767. if ( binding.useCount ++ === 0 ) {
  39768. this._lendBinding( binding );
  39769. binding.saveOriginalState();
  39770. }
  39771. }
  39772. this._lendAction( action );
  39773. }
  39774. }
  39775. _deactivateAction( action ) {
  39776. if ( this._isActiveAction( action ) ) {
  39777. const bindings = action._propertyBindings;
  39778. // decrement reference counts / sort out state
  39779. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39780. const binding = bindings[ i ];
  39781. if ( -- binding.useCount === 0 ) {
  39782. binding.restoreOriginalState();
  39783. this._takeBackBinding( binding );
  39784. }
  39785. }
  39786. this._takeBackAction( action );
  39787. }
  39788. }
  39789. // Memory manager
  39790. _initMemoryManager() {
  39791. this._actions = []; // 'nActiveActions' followed by inactive ones
  39792. this._nActiveActions = 0;
  39793. this._actionsByClip = {};
  39794. // inside:
  39795. // {
  39796. // knownActions: Array< AnimationAction > - used as prototypes
  39797. // actionByRoot: AnimationAction - lookup
  39798. // }
  39799. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39800. this._nActiveBindings = 0;
  39801. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39802. this._controlInterpolants = []; // same game as above
  39803. this._nActiveControlInterpolants = 0;
  39804. const scope = this;
  39805. this.stats = {
  39806. actions: {
  39807. get total() {
  39808. return scope._actions.length;
  39809. },
  39810. get inUse() {
  39811. return scope._nActiveActions;
  39812. }
  39813. },
  39814. bindings: {
  39815. get total() {
  39816. return scope._bindings.length;
  39817. },
  39818. get inUse() {
  39819. return scope._nActiveBindings;
  39820. }
  39821. },
  39822. controlInterpolants: {
  39823. get total() {
  39824. return scope._controlInterpolants.length;
  39825. },
  39826. get inUse() {
  39827. return scope._nActiveControlInterpolants;
  39828. }
  39829. }
  39830. };
  39831. }
  39832. // Memory management for AnimationAction objects
  39833. _isActiveAction( action ) {
  39834. const index = action._cacheIndex;
  39835. return index !== null && index < this._nActiveActions;
  39836. }
  39837. _addInactiveAction( action, clipUuid, rootUuid ) {
  39838. const actions = this._actions,
  39839. actionsByClip = this._actionsByClip;
  39840. let actionsForClip = actionsByClip[ clipUuid ];
  39841. if ( actionsForClip === undefined ) {
  39842. actionsForClip = {
  39843. knownActions: [ action ],
  39844. actionByRoot: {}
  39845. };
  39846. action._byClipCacheIndex = 0;
  39847. actionsByClip[ clipUuid ] = actionsForClip;
  39848. } else {
  39849. const knownActions = actionsForClip.knownActions;
  39850. action._byClipCacheIndex = knownActions.length;
  39851. knownActions.push( action );
  39852. }
  39853. action._cacheIndex = actions.length;
  39854. actions.push( action );
  39855. actionsForClip.actionByRoot[ rootUuid ] = action;
  39856. }
  39857. _removeInactiveAction( action ) {
  39858. const actions = this._actions,
  39859. lastInactiveAction = actions[ actions.length - 1 ],
  39860. cacheIndex = action._cacheIndex;
  39861. lastInactiveAction._cacheIndex = cacheIndex;
  39862. actions[ cacheIndex ] = lastInactiveAction;
  39863. actions.pop();
  39864. action._cacheIndex = null;
  39865. const clipUuid = action._clip.uuid,
  39866. actionsByClip = this._actionsByClip,
  39867. actionsForClip = actionsByClip[ clipUuid ],
  39868. knownActionsForClip = actionsForClip.knownActions,
  39869. lastKnownAction =
  39870. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39871. byClipCacheIndex = action._byClipCacheIndex;
  39872. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39873. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39874. knownActionsForClip.pop();
  39875. action._byClipCacheIndex = null;
  39876. const actionByRoot = actionsForClip.actionByRoot,
  39877. rootUuid = ( action._localRoot || this._root ).uuid;
  39878. delete actionByRoot[ rootUuid ];
  39879. if ( knownActionsForClip.length === 0 ) {
  39880. delete actionsByClip[ clipUuid ];
  39881. }
  39882. this._removeInactiveBindingsForAction( action );
  39883. }
  39884. _removeInactiveBindingsForAction( action ) {
  39885. const bindings = action._propertyBindings;
  39886. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39887. const binding = bindings[ i ];
  39888. if ( -- binding.referenceCount === 0 ) {
  39889. this._removeInactiveBinding( binding );
  39890. }
  39891. }
  39892. }
  39893. _lendAction( action ) {
  39894. // [ active actions | inactive actions ]
  39895. // [ active actions >| inactive actions ]
  39896. // s a
  39897. // <-swap->
  39898. // a s
  39899. const actions = this._actions,
  39900. prevIndex = action._cacheIndex,
  39901. lastActiveIndex = this._nActiveActions ++,
  39902. firstInactiveAction = actions[ lastActiveIndex ];
  39903. action._cacheIndex = lastActiveIndex;
  39904. actions[ lastActiveIndex ] = action;
  39905. firstInactiveAction._cacheIndex = prevIndex;
  39906. actions[ prevIndex ] = firstInactiveAction;
  39907. }
  39908. _takeBackAction( action ) {
  39909. // [ active actions | inactive actions ]
  39910. // [ active actions |< inactive actions ]
  39911. // a s
  39912. // <-swap->
  39913. // s a
  39914. const actions = this._actions,
  39915. prevIndex = action._cacheIndex,
  39916. firstInactiveIndex = -- this._nActiveActions,
  39917. lastActiveAction = actions[ firstInactiveIndex ];
  39918. action._cacheIndex = firstInactiveIndex;
  39919. actions[ firstInactiveIndex ] = action;
  39920. lastActiveAction._cacheIndex = prevIndex;
  39921. actions[ prevIndex ] = lastActiveAction;
  39922. }
  39923. // Memory management for PropertyMixer objects
  39924. _addInactiveBinding( binding, rootUuid, trackName ) {
  39925. const bindingsByRoot = this._bindingsByRootAndName,
  39926. bindings = this._bindings;
  39927. let bindingByName = bindingsByRoot[ rootUuid ];
  39928. if ( bindingByName === undefined ) {
  39929. bindingByName = {};
  39930. bindingsByRoot[ rootUuid ] = bindingByName;
  39931. }
  39932. bindingByName[ trackName ] = binding;
  39933. binding._cacheIndex = bindings.length;
  39934. bindings.push( binding );
  39935. }
  39936. _removeInactiveBinding( binding ) {
  39937. const bindings = this._bindings,
  39938. propBinding = binding.binding,
  39939. rootUuid = propBinding.rootNode.uuid,
  39940. trackName = propBinding.path,
  39941. bindingsByRoot = this._bindingsByRootAndName,
  39942. bindingByName = bindingsByRoot[ rootUuid ],
  39943. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39944. cacheIndex = binding._cacheIndex;
  39945. lastInactiveBinding._cacheIndex = cacheIndex;
  39946. bindings[ cacheIndex ] = lastInactiveBinding;
  39947. bindings.pop();
  39948. delete bindingByName[ trackName ];
  39949. if ( Object.keys( bindingByName ).length === 0 ) {
  39950. delete bindingsByRoot[ rootUuid ];
  39951. }
  39952. }
  39953. _lendBinding( binding ) {
  39954. const bindings = this._bindings,
  39955. prevIndex = binding._cacheIndex,
  39956. lastActiveIndex = this._nActiveBindings ++,
  39957. firstInactiveBinding = bindings[ lastActiveIndex ];
  39958. binding._cacheIndex = lastActiveIndex;
  39959. bindings[ lastActiveIndex ] = binding;
  39960. firstInactiveBinding._cacheIndex = prevIndex;
  39961. bindings[ prevIndex ] = firstInactiveBinding;
  39962. }
  39963. _takeBackBinding( binding ) {
  39964. const bindings = this._bindings,
  39965. prevIndex = binding._cacheIndex,
  39966. firstInactiveIndex = -- this._nActiveBindings,
  39967. lastActiveBinding = bindings[ firstInactiveIndex ];
  39968. binding._cacheIndex = firstInactiveIndex;
  39969. bindings[ firstInactiveIndex ] = binding;
  39970. lastActiveBinding._cacheIndex = prevIndex;
  39971. bindings[ prevIndex ] = lastActiveBinding;
  39972. }
  39973. // Memory management of Interpolants for weight and time scale
  39974. _lendControlInterpolant() {
  39975. const interpolants = this._controlInterpolants,
  39976. lastActiveIndex = this._nActiveControlInterpolants ++;
  39977. let interpolant = interpolants[ lastActiveIndex ];
  39978. if ( interpolant === undefined ) {
  39979. interpolant = new LinearInterpolant(
  39980. new Float32Array( 2 ), new Float32Array( 2 ),
  39981. 1, _controlInterpolantsResultBuffer );
  39982. interpolant.__cacheIndex = lastActiveIndex;
  39983. interpolants[ lastActiveIndex ] = interpolant;
  39984. }
  39985. return interpolant;
  39986. }
  39987. _takeBackControlInterpolant( interpolant ) {
  39988. const interpolants = this._controlInterpolants,
  39989. prevIndex = interpolant.__cacheIndex,
  39990. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39991. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39992. interpolant.__cacheIndex = firstInactiveIndex;
  39993. interpolants[ firstInactiveIndex ] = interpolant;
  39994. lastActiveInterpolant.__cacheIndex = prevIndex;
  39995. interpolants[ prevIndex ] = lastActiveInterpolant;
  39996. }
  39997. /**
  39998. * Returns an instance of {@link AnimationAction} for the passed clip.
  39999. *
  40000. * If an action fitting the clip and root parameters doesn't yet exist, it
  40001. * will be created by this method. Calling this method several times with the
  40002. * same clip and root parameters always returns the same action.
  40003. *
  40004. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40005. * @param {Object3D} [optionalRoot] - An alternative root object.
  40006. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  40007. * @return {?AnimationAction} The animation action.
  40008. */
  40009. clipAction( clip, optionalRoot, blendMode ) {
  40010. const root = optionalRoot || this._root,
  40011. rootUuid = root.uuid;
  40012. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  40013. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  40014. const actionsForClip = this._actionsByClip[ clipUuid ];
  40015. let prototypeAction = null;
  40016. if ( blendMode === undefined ) {
  40017. if ( clipObject !== null ) {
  40018. blendMode = clipObject.blendMode;
  40019. } else {
  40020. blendMode = NormalAnimationBlendMode;
  40021. }
  40022. }
  40023. if ( actionsForClip !== undefined ) {
  40024. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  40025. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  40026. return existingAction;
  40027. }
  40028. // we know the clip, so we don't have to parse all
  40029. // the bindings again but can just copy
  40030. prototypeAction = actionsForClip.knownActions[ 0 ];
  40031. // also, take the clip from the prototype action
  40032. if ( clipObject === null )
  40033. clipObject = prototypeAction._clip;
  40034. }
  40035. // clip must be known when specified via string
  40036. if ( clipObject === null ) return null;
  40037. // allocate all resources required to run it
  40038. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  40039. this._bindAction( newAction, prototypeAction );
  40040. // and make the action known to the memory manager
  40041. this._addInactiveAction( newAction, clipUuid, rootUuid );
  40042. return newAction;
  40043. }
  40044. /**
  40045. * Returns an existing animation action for the passed clip.
  40046. *
  40047. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40048. * @param {Object3D} [optionalRoot] - An alternative root object.
  40049. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  40050. */
  40051. existingAction( clip, optionalRoot ) {
  40052. const root = optionalRoot || this._root,
  40053. rootUuid = root.uuid,
  40054. clipObject = typeof clip === 'string' ?
  40055. AnimationClip.findByName( root, clip ) : clip,
  40056. clipUuid = clipObject ? clipObject.uuid : clip,
  40057. actionsForClip = this._actionsByClip[ clipUuid ];
  40058. if ( actionsForClip !== undefined ) {
  40059. return actionsForClip.actionByRoot[ rootUuid ] || null;
  40060. }
  40061. return null;
  40062. }
  40063. /**
  40064. * Deactivates all previously scheduled actions on this mixer.
  40065. *
  40066. * @return {AnimationMixer} A reference to this animation mixer.
  40067. */
  40068. stopAllAction() {
  40069. const actions = this._actions,
  40070. nActions = this._nActiveActions;
  40071. for ( let i = nActions - 1; i >= 0; -- i ) {
  40072. actions[ i ].stop();
  40073. }
  40074. return this;
  40075. }
  40076. /**
  40077. * Advances the global mixer time and updates the animation.
  40078. *
  40079. * This is usually done in the render loop by passing the delta
  40080. * time from {@link Clock} or {@link Timer}.
  40081. *
  40082. * @param {number} deltaTime - The delta time in seconds.
  40083. * @return {AnimationMixer} A reference to this animation mixer.
  40084. */
  40085. update( deltaTime ) {
  40086. deltaTime *= this.timeScale;
  40087. const actions = this._actions,
  40088. nActions = this._nActiveActions,
  40089. time = this.time += deltaTime,
  40090. timeDirection = Math.sign( deltaTime ),
  40091. accuIndex = this._accuIndex ^= 1;
  40092. // run active actions
  40093. for ( let i = 0; i !== nActions; ++ i ) {
  40094. const action = actions[ i ];
  40095. action._update( time, deltaTime, timeDirection, accuIndex );
  40096. }
  40097. // update scene graph
  40098. const bindings = this._bindings,
  40099. nBindings = this._nActiveBindings;
  40100. for ( let i = 0; i !== nBindings; ++ i ) {
  40101. bindings[ i ].apply( accuIndex );
  40102. }
  40103. return this;
  40104. }
  40105. /**
  40106. * Sets the global mixer to a specific time and updates the animation accordingly.
  40107. *
  40108. * This is useful when you need to jump to an exact time in an animation. The
  40109. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  40110. *
  40111. * @param {number} time - The time to set in seconds.
  40112. * @return {AnimationMixer} A reference to this animation mixer.
  40113. */
  40114. setTime( time ) {
  40115. this.time = 0; // Zero out time attribute for AnimationMixer object;
  40116. for ( let i = 0; i < this._actions.length; i ++ ) {
  40117. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  40118. }
  40119. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  40120. }
  40121. /**
  40122. * Returns this mixer's root object.
  40123. *
  40124. * @return {Object3D} The mixer's root object.
  40125. */
  40126. getRoot() {
  40127. return this._root;
  40128. }
  40129. /**
  40130. * Deallocates all memory resources for a clip. Before using this method make
  40131. * sure to call {@link AnimationAction#stop} for all related actions.
  40132. *
  40133. * @param {AnimationClip} clip - The clip to uncache.
  40134. */
  40135. uncacheClip( clip ) {
  40136. const actions = this._actions,
  40137. clipUuid = clip.uuid,
  40138. actionsByClip = this._actionsByClip,
  40139. actionsForClip = actionsByClip[ clipUuid ];
  40140. if ( actionsForClip !== undefined ) {
  40141. // note: just calling _removeInactiveAction would mess up the
  40142. // iteration state and also require updating the state we can
  40143. // just throw away
  40144. const actionsToRemove = actionsForClip.knownActions;
  40145. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  40146. const action = actionsToRemove[ i ];
  40147. this._deactivateAction( action );
  40148. const cacheIndex = action._cacheIndex,
  40149. lastInactiveAction = actions[ actions.length - 1 ];
  40150. action._cacheIndex = null;
  40151. action._byClipCacheIndex = null;
  40152. lastInactiveAction._cacheIndex = cacheIndex;
  40153. actions[ cacheIndex ] = lastInactiveAction;
  40154. actions.pop();
  40155. this._removeInactiveBindingsForAction( action );
  40156. }
  40157. delete actionsByClip[ clipUuid ];
  40158. }
  40159. }
  40160. /**
  40161. * Deallocates all memory resources for a root object. Before using this
  40162. * method make sure to call {@link AnimationAction#stop} for all related
  40163. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  40164. * mixer operates on a single root.
  40165. *
  40166. * @param {Object3D} root - The root object to uncache.
  40167. */
  40168. uncacheRoot( root ) {
  40169. const rootUuid = root.uuid,
  40170. actionsByClip = this._actionsByClip;
  40171. for ( const clipUuid in actionsByClip ) {
  40172. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  40173. action = actionByRoot[ rootUuid ];
  40174. if ( action !== undefined ) {
  40175. this._deactivateAction( action );
  40176. this._removeInactiveAction( action );
  40177. }
  40178. }
  40179. const bindingsByRoot = this._bindingsByRootAndName,
  40180. bindingByName = bindingsByRoot[ rootUuid ];
  40181. if ( bindingByName !== undefined ) {
  40182. for ( const trackName in bindingByName ) {
  40183. const binding = bindingByName[ trackName ];
  40184. binding.restoreOriginalState();
  40185. this._removeInactiveBinding( binding );
  40186. }
  40187. }
  40188. }
  40189. /**
  40190. * Deallocates all memory resources for an action. The action is identified by the
  40191. * given clip and an optional root object. Before using this method make
  40192. * sure to call {@link AnimationAction#stop} to deactivate the action.
  40193. *
  40194. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  40195. * @param {Object3D} [optionalRoot] - An alternative root object.
  40196. */
  40197. uncacheAction( clip, optionalRoot ) {
  40198. const action = this.existingAction( clip, optionalRoot );
  40199. if ( action !== null ) {
  40200. this._deactivateAction( action );
  40201. this._removeInactiveAction( action );
  40202. }
  40203. }
  40204. }
  40205. /**
  40206. * Represents a 3D render target.
  40207. *
  40208. * @augments RenderTarget
  40209. */
  40210. class RenderTarget3D extends RenderTarget {
  40211. /**
  40212. * Constructs a new 3D render target.
  40213. *
  40214. * @param {number} [width=1] - The width of the render target.
  40215. * @param {number} [height=1] - The height of the render target.
  40216. * @param {number} [depth=1] - The height of the render target.
  40217. * @param {RenderTarget~Options} [options] - The configuration object.
  40218. */
  40219. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  40220. super( width, height, options );
  40221. /**
  40222. * This flag can be used for type testing.
  40223. *
  40224. * @type {boolean}
  40225. * @readonly
  40226. * @default true
  40227. */
  40228. this.isRenderTarget3D = true;
  40229. this.depth = depth;
  40230. /**
  40231. * Overwritten with a different texture type.
  40232. *
  40233. * @type {Data3DTexture}
  40234. */
  40235. this.texture = new Data3DTexture( null, width, height, depth );
  40236. this._setTextureOptions( options );
  40237. this.texture.isRenderTargetTexture = true;
  40238. }
  40239. }
  40240. /**
  40241. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  40242. *
  40243. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  40244. * ```js
  40245. * uniforms: {
  40246. * time: { value: 1.0 },
  40247. * resolution: new Uniform( new Vector2() )
  40248. * };
  40249. * ```
  40250. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  40251. * in {@link WebGLRenderer}.
  40252. */
  40253. class Uniform {
  40254. /**
  40255. * Constructs a new uniform.
  40256. *
  40257. * @param {any} value - The uniform value.
  40258. */
  40259. constructor( value ) {
  40260. /**
  40261. * The uniform value.
  40262. *
  40263. * @type {any}
  40264. */
  40265. this.value = value;
  40266. }
  40267. /**
  40268. * Returns a new uniform with copied values from this instance.
  40269. * If the value has a `clone()` method, the value is cloned as well.
  40270. *
  40271. * @return {Uniform} A clone of this instance.
  40272. */
  40273. clone() {
  40274. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  40275. }
  40276. }
  40277. let _id = 0;
  40278. /**
  40279. * A class for managing multiple uniforms in a single group. The renderer will process
  40280. * such a definition as a single UBO.
  40281. *
  40282. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  40283. * in {@link WebGLRenderer}.
  40284. *
  40285. * @augments EventDispatcher
  40286. */
  40287. class UniformsGroup extends EventDispatcher {
  40288. /**
  40289. * Constructs a new uniforms group.
  40290. */
  40291. constructor() {
  40292. super();
  40293. /**
  40294. * This flag can be used for type testing.
  40295. *
  40296. * @type {boolean}
  40297. * @readonly
  40298. * @default true
  40299. */
  40300. this.isUniformsGroup = true;
  40301. /**
  40302. * The ID of the 3D object.
  40303. *
  40304. * @name UniformsGroup#id
  40305. * @type {number}
  40306. * @readonly
  40307. */
  40308. Object.defineProperty( this, 'id', { value: _id ++ } );
  40309. /**
  40310. * The name of the uniforms group.
  40311. *
  40312. * @type {string}
  40313. */
  40314. this.name = '';
  40315. /**
  40316. * The buffer usage.
  40317. *
  40318. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  40319. * @default StaticDrawUsage
  40320. */
  40321. this.usage = StaticDrawUsage;
  40322. /**
  40323. * An array holding the uniforms.
  40324. *
  40325. * @type {Array<Uniform>}
  40326. */
  40327. this.uniforms = [];
  40328. }
  40329. /**
  40330. * Adds the given uniform to this uniforms group.
  40331. *
  40332. * @param {Uniform} uniform - The uniform to add.
  40333. * @return {UniformsGroup} A reference to this uniforms group.
  40334. */
  40335. add( uniform ) {
  40336. this.uniforms.push( uniform );
  40337. return this;
  40338. }
  40339. /**
  40340. * Removes the given uniform from this uniforms group.
  40341. *
  40342. * @param {Uniform} uniform - The uniform to remove.
  40343. * @return {UniformsGroup} A reference to this uniforms group.
  40344. */
  40345. remove( uniform ) {
  40346. const index = this.uniforms.indexOf( uniform );
  40347. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  40348. return this;
  40349. }
  40350. /**
  40351. * Sets the name of this uniforms group.
  40352. *
  40353. * @param {string} name - The name to set.
  40354. * @return {UniformsGroup} A reference to this uniforms group.
  40355. */
  40356. setName( name ) {
  40357. this.name = name;
  40358. return this;
  40359. }
  40360. /**
  40361. * Sets the usage of this uniforms group.
  40362. *
  40363. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  40364. * @return {UniformsGroup} A reference to this uniforms group.
  40365. */
  40366. setUsage( value ) {
  40367. this.usage = value;
  40368. return this;
  40369. }
  40370. /**
  40371. * Frees the GPU-related resources allocated by this instance. Call this
  40372. * method whenever this instance is no longer used in your app.
  40373. *
  40374. * @fires Texture#dispose
  40375. */
  40376. dispose() {
  40377. this.dispatchEvent( { type: 'dispose' } );
  40378. }
  40379. /**
  40380. * Copies the values of the given uniforms group to this instance.
  40381. *
  40382. * @param {UniformsGroup} source - The uniforms group to copy.
  40383. * @return {UniformsGroup} A reference to this uniforms group.
  40384. */
  40385. copy( source ) {
  40386. this.name = source.name;
  40387. this.usage = source.usage;
  40388. const uniformsSource = source.uniforms;
  40389. this.uniforms.length = 0;
  40390. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  40391. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  40392. for ( let j = 0; j < uniforms.length; j ++ ) {
  40393. this.uniforms.push( uniforms[ j ].clone() );
  40394. }
  40395. }
  40396. return this;
  40397. }
  40398. /**
  40399. * Returns a new uniforms group with copied values from this instance.
  40400. *
  40401. * @return {UniformsGroup} A clone of this instance.
  40402. */
  40403. clone() {
  40404. return new this.constructor().copy( this );
  40405. }
  40406. }
  40407. /**
  40408. * An instanced version of an interleaved buffer.
  40409. *
  40410. * @augments InterleavedBuffer
  40411. */
  40412. class InstancedInterleavedBuffer extends InterleavedBuffer {
  40413. /**
  40414. * Constructs a new instanced interleaved buffer.
  40415. *
  40416. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  40417. * @param {number} stride - The number of typed-array elements per vertex.
  40418. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  40419. */
  40420. constructor( array, stride, meshPerAttribute = 1 ) {
  40421. super( array, stride );
  40422. /**
  40423. * This flag can be used for type testing.
  40424. *
  40425. * @type {boolean}
  40426. * @readonly
  40427. * @default true
  40428. */
  40429. this.isInstancedInterleavedBuffer = true;
  40430. /**
  40431. * Defines how often a value of this buffer attribute should be repeated,
  40432. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  40433. *
  40434. * @type {number}
  40435. * @default 1
  40436. */
  40437. this.meshPerAttribute = meshPerAttribute;
  40438. }
  40439. copy( source ) {
  40440. super.copy( source );
  40441. this.meshPerAttribute = source.meshPerAttribute;
  40442. return this;
  40443. }
  40444. clone( data ) {
  40445. const ib = super.clone( data );
  40446. ib.meshPerAttribute = this.meshPerAttribute;
  40447. return ib;
  40448. }
  40449. toJSON( data ) {
  40450. const json = super.toJSON( data );
  40451. json.isInstancedInterleavedBuffer = true;
  40452. json.meshPerAttribute = this.meshPerAttribute;
  40453. return json;
  40454. }
  40455. }
  40456. /**
  40457. * An alternative version of a buffer attribute with more control over the VBO.
  40458. *
  40459. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  40460. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  40461. *
  40462. * The most common use case for this class is when some kind of GPGPU calculation interferes
  40463. * or even produces the VBOs in question.
  40464. *
  40465. * Notice that this class can only be used with {@link WebGLRenderer}.
  40466. */
  40467. class GLBufferAttribute {
  40468. /**
  40469. * Constructs a new GL buffer attribute.
  40470. *
  40471. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  40472. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40473. * @param {number} itemSize - The item size.
  40474. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40475. * @param {number} count - The expected number of vertices in VBO.
  40476. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  40477. */
  40478. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  40479. /**
  40480. * This flag can be used for type testing.
  40481. *
  40482. * @type {boolean}
  40483. * @readonly
  40484. * @default true
  40485. */
  40486. this.isGLBufferAttribute = true;
  40487. /**
  40488. * The name of the buffer attribute.
  40489. *
  40490. * @type {string}
  40491. */
  40492. this.name = '';
  40493. /**
  40494. * The native WebGL buffer.
  40495. *
  40496. * @type {WebGLBuffer}
  40497. */
  40498. this.buffer = buffer;
  40499. /**
  40500. * The native data type.
  40501. *
  40502. * @type {number}
  40503. */
  40504. this.type = type;
  40505. /**
  40506. * The item size, see {@link BufferAttribute#itemSize}.
  40507. *
  40508. * @type {number}
  40509. */
  40510. this.itemSize = itemSize;
  40511. /**
  40512. * The corresponding size (in bytes) for the given `type` parameter.
  40513. *
  40514. * @type {number}
  40515. */
  40516. this.elementSize = elementSize;
  40517. /**
  40518. * The expected number of vertices in VBO.
  40519. *
  40520. * @type {number}
  40521. */
  40522. this.count = count;
  40523. /**
  40524. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  40525. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  40526. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  40527. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  40528. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  40529. *
  40530. * @type {boolean}
  40531. */
  40532. this.normalized = normalized;
  40533. /**
  40534. * A version number, incremented every time the `needsUpdate` is set to `true`.
  40535. *
  40536. * @type {number}
  40537. */
  40538. this.version = 0;
  40539. }
  40540. /**
  40541. * Flag to indicate that this attribute has changed and should be re-sent to
  40542. * the GPU. Set this to `true` when you modify the value of the array.
  40543. *
  40544. * @type {number}
  40545. * @default false
  40546. * @param {boolean} value
  40547. */
  40548. set needsUpdate( value ) {
  40549. if ( value === true ) this.version ++;
  40550. }
  40551. /**
  40552. * Sets the given native WebGL buffer.
  40553. *
  40554. * @param {WebGLBuffer} buffer - The buffer to set.
  40555. * @return {BufferAttribute} A reference to this instance.
  40556. */
  40557. setBuffer( buffer ) {
  40558. this.buffer = buffer;
  40559. return this;
  40560. }
  40561. /**
  40562. * Sets the given native data type and element size.
  40563. *
  40564. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  40565. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  40566. * @return {BufferAttribute} A reference to this instance.
  40567. */
  40568. setType( type, elementSize ) {
  40569. this.type = type;
  40570. this.elementSize = elementSize;
  40571. return this;
  40572. }
  40573. /**
  40574. * Sets the item size.
  40575. *
  40576. * @param {number} itemSize - The item size.
  40577. * @return {BufferAttribute} A reference to this instance.
  40578. */
  40579. setItemSize( itemSize ) {
  40580. this.itemSize = itemSize;
  40581. return this;
  40582. }
  40583. /**
  40584. * Sets the count (the expected number of vertices in VBO).
  40585. *
  40586. * @param {number} count - The count.
  40587. * @return {BufferAttribute} A reference to this instance.
  40588. */
  40589. setCount( count ) {
  40590. this.count = count;
  40591. return this;
  40592. }
  40593. }
  40594. const _matrix = /*@__PURE__*/ new Matrix4();
  40595. /**
  40596. * This class is designed to assist with raycasting. Raycasting is used for
  40597. * mouse picking (working out what objects in the 3d space the mouse is over)
  40598. * amongst other things.
  40599. */
  40600. class Raycaster {
  40601. /**
  40602. * Constructs a new raycaster.
  40603. *
  40604. * @param {Vector3} origin - The origin vector where the ray casts from.
  40605. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40606. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  40607. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  40608. */
  40609. constructor( origin, direction, near = 0, far = Infinity ) {
  40610. /**
  40611. * The ray used for raycasting.
  40612. *
  40613. * @type {Ray}
  40614. */
  40615. this.ray = new Ray( origin, direction );
  40616. /**
  40617. * All results returned are further away than near. Near can't be negative.
  40618. *
  40619. * @type {number}
  40620. * @default 0
  40621. */
  40622. this.near = near;
  40623. /**
  40624. * All results returned are closer than far. Far can't be lower than near.
  40625. *
  40626. * @type {number}
  40627. * @default Infinity
  40628. */
  40629. this.far = far;
  40630. /**
  40631. * The camera to use when raycasting against view-dependent objects such as
  40632. * billboarded objects like sprites. This field can be set manually or
  40633. * is set when calling `setFromCamera()`.
  40634. *
  40635. * @type {?Camera}
  40636. * @default null
  40637. */
  40638. this.camera = null;
  40639. /**
  40640. * Allows to selectively ignore 3D objects when performing intersection tests.
  40641. * The following code example ensures that only 3D objects on layer `1` will be
  40642. * honored by raycaster.
  40643. * ```js
  40644. * raycaster.layers.set( 1 );
  40645. * object.layers.enable( 1 );
  40646. * ```
  40647. *
  40648. * @type {Layers}
  40649. */
  40650. this.layers = new Layers();
  40651. /**
  40652. * A parameter object that configures the raycasting. It has the structure:
  40653. *
  40654. * ```
  40655. * {
  40656. * Mesh: {},
  40657. * Line: { threshold: 1 },
  40658. * LOD: {},
  40659. * Points: { threshold: 1 },
  40660. * Sprite: {}
  40661. * }
  40662. * ```
  40663. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40664. *
  40665. * @type {Object}
  40666. */
  40667. this.params = {
  40668. Mesh: {},
  40669. Line: { threshold: 1 },
  40670. LOD: {},
  40671. Points: { threshold: 1 },
  40672. Sprite: {}
  40673. };
  40674. }
  40675. /**
  40676. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40677. *
  40678. * @param {Vector3} origin - The origin vector where the ray casts from.
  40679. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40680. */
  40681. set( origin, direction ) {
  40682. // direction is assumed to be normalized (for accurate distance calculations)
  40683. this.ray.set( origin, direction );
  40684. }
  40685. /**
  40686. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40687. *
  40688. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40689. * X and Y components should be between `-1` and `1`.
  40690. * @param {Camera} camera - The camera from which the ray should originate.
  40691. */
  40692. setFromCamera( coords, camera ) {
  40693. if ( camera.isPerspectiveCamera ) {
  40694. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40695. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40696. this.camera = camera;
  40697. } else if ( camera.isOrthographicCamera ) {
  40698. this.ray.origin.set( coords.x, coords.y, camera.projectionMatrix.elements[ 14 ] ).unproject( camera ); // set origin in plane of camera
  40699. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40700. this.camera = camera;
  40701. } else {
  40702. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40703. }
  40704. }
  40705. /**
  40706. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40707. *
  40708. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40709. * @return {Raycaster} A reference to this raycaster.
  40710. */
  40711. setFromXRController( controller ) {
  40712. _matrix.identity().extractRotation( controller.matrixWorld );
  40713. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40714. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40715. return this;
  40716. }
  40717. /**
  40718. * The intersection point of a raycaster intersection test.
  40719. * @typedef {Object} Raycaster~Intersection
  40720. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40721. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40722. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40723. * @property {Vector3} point - The intersection point, in world coordinates.
  40724. * @property {Object} face - The face that has been intersected.
  40725. * @property {number} faceIndex - The face index.
  40726. * @property {Object3D} object - The 3D object that has been intersected.
  40727. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40728. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40729. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40730. * @property {number} instanceId - The index number of the instance where the ray
  40731. * intersects the {@link InstancedMesh}.
  40732. */
  40733. /**
  40734. * Checks all intersection between the ray and the object with or without the
  40735. * descendants. Intersections are returned sorted by distance, closest first.
  40736. *
  40737. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40738. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40739. * differently to ray casting than lines or points.
  40740. *
  40741. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40742. * to be detected; intersections of the ray passing through the back of a face will not
  40743. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40744. * to `THREE.DoubleSide`.
  40745. *
  40746. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40747. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40748. * Otherwise it only checks intersection with the object.
  40749. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40750. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40751. */
  40752. intersectObject( object, recursive = true, intersects = [] ) {
  40753. intersect( object, this, intersects, recursive );
  40754. intersects.sort( ascSort );
  40755. return intersects;
  40756. }
  40757. /**
  40758. * Checks all intersection between the ray and the objects with or without
  40759. * the descendants. Intersections are returned sorted by distance, closest first.
  40760. *
  40761. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40762. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40763. * Otherwise it only checks intersection with the object.
  40764. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40765. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40766. */
  40767. intersectObjects( objects, recursive = true, intersects = [] ) {
  40768. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40769. intersect( objects[ i ], this, intersects, recursive );
  40770. }
  40771. intersects.sort( ascSort );
  40772. return intersects;
  40773. }
  40774. }
  40775. function ascSort( a, b ) {
  40776. return a.distance - b.distance;
  40777. }
  40778. function intersect( object, raycaster, intersects, recursive ) {
  40779. let propagate = true;
  40780. if ( object.layers.test( raycaster.layers ) ) {
  40781. const result = object.raycast( raycaster, intersects );
  40782. if ( result === false ) propagate = false;
  40783. }
  40784. if ( propagate === true && recursive === true ) {
  40785. const children = object.children;
  40786. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40787. intersect( children[ i ], raycaster, intersects, true );
  40788. }
  40789. }
  40790. }
  40791. /**
  40792. * Class for keeping track of time.
  40793. *
  40794. * @deprecated since r183.
  40795. */
  40796. class Clock {
  40797. /**
  40798. * Constructs a new clock.
  40799. *
  40800. * @deprecated since 183.
  40801. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  40802. * `getDelta()` is called for the first time.
  40803. */
  40804. constructor( autoStart = true ) {
  40805. /**
  40806. * If set to `true`, the clock starts automatically when `getDelta()` is called
  40807. * for the first time.
  40808. *
  40809. * @type {boolean}
  40810. * @default true
  40811. */
  40812. this.autoStart = autoStart;
  40813. /**
  40814. * Holds the time at which the clock's `start()` method was last called.
  40815. *
  40816. * @type {number}
  40817. * @default 0
  40818. */
  40819. this.startTime = 0;
  40820. /**
  40821. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  40822. * `getDelta()` methods were last called.
  40823. *
  40824. * @type {number}
  40825. * @default 0
  40826. */
  40827. this.oldTime = 0;
  40828. /**
  40829. * Keeps track of the total time that the clock has been running.
  40830. *
  40831. * @type {number}
  40832. * @default 0
  40833. */
  40834. this.elapsedTime = 0;
  40835. /**
  40836. * Whether the clock is running or not.
  40837. *
  40838. * @type {boolean}
  40839. * @default true
  40840. */
  40841. this.running = false;
  40842. warn( 'Clock: This module has been deprecated. Please use THREE.Timer instead.' ); // @deprecated, r183
  40843. }
  40844. /**
  40845. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  40846. * called by the class.
  40847. */
  40848. start() {
  40849. this.startTime = performance.now();
  40850. this.oldTime = this.startTime;
  40851. this.elapsedTime = 0;
  40852. this.running = true;
  40853. }
  40854. /**
  40855. * Stops the clock.
  40856. */
  40857. stop() {
  40858. this.getElapsedTime();
  40859. this.running = false;
  40860. this.autoStart = false;
  40861. }
  40862. /**
  40863. * Returns the elapsed time in seconds.
  40864. *
  40865. * @return {number} The elapsed time.
  40866. */
  40867. getElapsedTime() {
  40868. this.getDelta();
  40869. return this.elapsedTime;
  40870. }
  40871. /**
  40872. * Returns the delta time in seconds.
  40873. *
  40874. * @return {number} The delta time.
  40875. */
  40876. getDelta() {
  40877. let diff = 0;
  40878. if ( this.autoStart && ! this.running ) {
  40879. this.start();
  40880. return 0;
  40881. }
  40882. if ( this.running ) {
  40883. const newTime = performance.now();
  40884. diff = ( newTime - this.oldTime ) / 1000;
  40885. this.oldTime = newTime;
  40886. this.elapsedTime += diff;
  40887. }
  40888. return diff;
  40889. }
  40890. }
  40891. /**
  40892. * This class can be used to represent points in 3D space as
  40893. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40894. */
  40895. class Spherical {
  40896. /**
  40897. * Constructs a new spherical.
  40898. *
  40899. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40900. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40901. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40902. */
  40903. constructor( radius = 1, phi = 0, theta = 0 ) {
  40904. /**
  40905. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40906. *
  40907. * @type {number}
  40908. * @default 1
  40909. */
  40910. this.radius = radius;
  40911. /**
  40912. * The polar angle in radians from the y (up) axis.
  40913. *
  40914. * @type {number}
  40915. * @default 0
  40916. */
  40917. this.phi = phi;
  40918. /**
  40919. * The equator/azimuthal angle in radians around the y (up) axis.
  40920. *
  40921. * @type {number}
  40922. * @default 0
  40923. */
  40924. this.theta = theta;
  40925. }
  40926. /**
  40927. * Sets the spherical components by copying the given values.
  40928. *
  40929. * @param {number} radius - The radius.
  40930. * @param {number} phi - The polar angle.
  40931. * @param {number} theta - The azimuthal angle.
  40932. * @return {Spherical} A reference to this spherical.
  40933. */
  40934. set( radius, phi, theta ) {
  40935. this.radius = radius;
  40936. this.phi = phi;
  40937. this.theta = theta;
  40938. return this;
  40939. }
  40940. /**
  40941. * Copies the values of the given spherical to this instance.
  40942. *
  40943. * @param {Spherical} other - The spherical to copy.
  40944. * @return {Spherical} A reference to this spherical.
  40945. */
  40946. copy( other ) {
  40947. this.radius = other.radius;
  40948. this.phi = other.phi;
  40949. this.theta = other.theta;
  40950. return this;
  40951. }
  40952. /**
  40953. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40954. * `0.000001`.
  40955. *
  40956. * @return {Spherical} A reference to this spherical.
  40957. */
  40958. makeSafe() {
  40959. const EPS = 0.000001;
  40960. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40961. return this;
  40962. }
  40963. /**
  40964. * Sets the spherical components from the given vector which is assumed to hold
  40965. * Cartesian coordinates.
  40966. *
  40967. * @param {Vector3} v - The vector to set.
  40968. * @return {Spherical} A reference to this spherical.
  40969. */
  40970. setFromVector3( v ) {
  40971. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40972. }
  40973. /**
  40974. * Sets the spherical components from the given Cartesian coordinates.
  40975. *
  40976. * @param {number} x - The x value.
  40977. * @param {number} y - The y value.
  40978. * @param {number} z - The z value.
  40979. * @return {Spherical} A reference to this spherical.
  40980. */
  40981. setFromCartesianCoords( x, y, z ) {
  40982. this.radius = Math.sqrt( x * x + y * y + z * z );
  40983. if ( this.radius === 0 ) {
  40984. this.theta = 0;
  40985. this.phi = 0;
  40986. } else {
  40987. this.theta = Math.atan2( x, z );
  40988. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40989. }
  40990. return this;
  40991. }
  40992. /**
  40993. * Returns a new spherical with copied values from this instance.
  40994. *
  40995. * @return {Spherical} A clone of this instance.
  40996. */
  40997. clone() {
  40998. return new this.constructor().copy( this );
  40999. }
  41000. }
  41001. /**
  41002. * This class can be used to represent points in 3D space as
  41003. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  41004. */
  41005. class Cylindrical {
  41006. /**
  41007. * Constructs a new cylindrical.
  41008. *
  41009. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  41010. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  41011. * @param {number} [y=0] - The height above the x-z plane.
  41012. */
  41013. constructor( radius = 1, theta = 0, y = 0 ) {
  41014. /**
  41015. * The distance from the origin to a point in the x-z plane.
  41016. *
  41017. * @type {number}
  41018. * @default 1
  41019. */
  41020. this.radius = radius;
  41021. /**
  41022. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  41023. *
  41024. * @type {number}
  41025. * @default 0
  41026. */
  41027. this.theta = theta;
  41028. /**
  41029. * The height above the x-z plane.
  41030. *
  41031. * @type {number}
  41032. * @default 0
  41033. */
  41034. this.y = y;
  41035. }
  41036. /**
  41037. * Sets the cylindrical components by copying the given values.
  41038. *
  41039. * @param {number} radius - The radius.
  41040. * @param {number} theta - The theta angle.
  41041. * @param {number} y - The height value.
  41042. * @return {Cylindrical} A reference to this cylindrical.
  41043. */
  41044. set( radius, theta, y ) {
  41045. this.radius = radius;
  41046. this.theta = theta;
  41047. this.y = y;
  41048. return this;
  41049. }
  41050. /**
  41051. * Copies the values of the given cylindrical to this instance.
  41052. *
  41053. * @param {Cylindrical} other - The cylindrical to copy.
  41054. * @return {Cylindrical} A reference to this cylindrical.
  41055. */
  41056. copy( other ) {
  41057. this.radius = other.radius;
  41058. this.theta = other.theta;
  41059. this.y = other.y;
  41060. return this;
  41061. }
  41062. /**
  41063. * Sets the cylindrical components from the given vector which is assumed to hold
  41064. * Cartesian coordinates.
  41065. *
  41066. * @param {Vector3} v - The vector to set.
  41067. * @return {Cylindrical} A reference to this cylindrical.
  41068. */
  41069. setFromVector3( v ) {
  41070. return this.setFromCartesianCoords( v.x, v.y, v.z );
  41071. }
  41072. /**
  41073. * Sets the cylindrical components from the given Cartesian coordinates.
  41074. *
  41075. * @param {number} x - The x value.
  41076. * @param {number} y - The x value.
  41077. * @param {number} z - The x value.
  41078. * @return {Cylindrical} A reference to this cylindrical.
  41079. */
  41080. setFromCartesianCoords( x, y, z ) {
  41081. this.radius = Math.sqrt( x * x + z * z );
  41082. this.theta = Math.atan2( x, z );
  41083. this.y = y;
  41084. return this;
  41085. }
  41086. /**
  41087. * Returns a new cylindrical with copied values from this instance.
  41088. *
  41089. * @return {Cylindrical} A clone of this instance.
  41090. */
  41091. clone() {
  41092. return new this.constructor().copy( this );
  41093. }
  41094. }
  41095. /**
  41096. * Represents a 2x2 matrix.
  41097. *
  41098. * A Note on Row-Major and Column-Major Ordering:
  41099. *
  41100. * The constructor and {@link Matrix2#set} method take arguments in
  41101. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  41102. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  41103. * This means that calling:
  41104. * ```js
  41105. * const m = new THREE.Matrix2();
  41106. * m.set( 11, 12,
  41107. * 21, 22 );
  41108. * ```
  41109. * will result in the elements array containing:
  41110. * ```js
  41111. * m.elements = [ 11, 21,
  41112. * 12, 22 ];
  41113. * ```
  41114. * and internally all calculations are performed using column-major ordering.
  41115. * However, as the actual ordering makes no difference mathematically and
  41116. * most people are used to thinking about matrices in row-major order, the
  41117. * three.js documentation shows matrices in row-major order. Just bear in
  41118. * mind that if you are reading the source code, you'll have to take the
  41119. * transpose of any matrices outlined here to make sense of the calculations.
  41120. */
  41121. class Matrix2 {
  41122. static {
  41123. /**
  41124. * This flag can be used for type testing.
  41125. *
  41126. * @type {boolean}
  41127. * @readonly
  41128. * @default true
  41129. */
  41130. Matrix2.prototype.isMatrix2 = true;
  41131. }
  41132. /**
  41133. * Constructs a new 2x2 matrix. The arguments are supposed to be
  41134. * in row-major order. If no arguments are provided, the constructor
  41135. * initializes the matrix as an identity matrix.
  41136. *
  41137. * @param {number} [n11] - 1-1 matrix element.
  41138. * @param {number} [n12] - 1-2 matrix element.
  41139. * @param {number} [n21] - 2-1 matrix element.
  41140. * @param {number} [n22] - 2-2 matrix element.
  41141. */
  41142. constructor( n11, n12, n21, n22 ) {
  41143. /**
  41144. * A column-major list of matrix values.
  41145. *
  41146. * @type {Array<number>}
  41147. */
  41148. this.elements = [
  41149. 1, 0,
  41150. 0, 1,
  41151. ];
  41152. if ( n11 !== undefined ) {
  41153. this.set( n11, n12, n21, n22 );
  41154. }
  41155. }
  41156. /**
  41157. * Sets this matrix to the 2x2 identity matrix.
  41158. *
  41159. * @return {Matrix2} A reference to this matrix.
  41160. */
  41161. identity() {
  41162. this.set(
  41163. 1, 0,
  41164. 0, 1,
  41165. );
  41166. return this;
  41167. }
  41168. /**
  41169. * Sets the elements of the matrix from the given array.
  41170. *
  41171. * @param {Array<number>} array - The matrix elements in column-major order.
  41172. * @param {number} [offset=0] - Index of the first element in the array.
  41173. * @return {Matrix2} A reference to this matrix.
  41174. */
  41175. fromArray( array, offset = 0 ) {
  41176. for ( let i = 0; i < 4; i ++ ) {
  41177. this.elements[ i ] = array[ i + offset ];
  41178. }
  41179. return this;
  41180. }
  41181. /**
  41182. * Sets the elements of the matrix.The arguments are supposed to be
  41183. * in row-major order.
  41184. *
  41185. * @param {number} n11 - 1-1 matrix element.
  41186. * @param {number} n12 - 1-2 matrix element.
  41187. * @param {number} n21 - 2-1 matrix element.
  41188. * @param {number} n22 - 2-2 matrix element.
  41189. * @return {Matrix2} A reference to this matrix.
  41190. */
  41191. set( n11, n12, n21, n22 ) {
  41192. const te = this.elements;
  41193. te[ 0 ] = n11; te[ 2 ] = n12;
  41194. te[ 1 ] = n21; te[ 3 ] = n22;
  41195. return this;
  41196. }
  41197. }
  41198. const _vector$4 = /*@__PURE__*/ new Vector2();
  41199. /**
  41200. * Represents an axis-aligned bounding box (AABB) in 2D space.
  41201. */
  41202. class Box2 {
  41203. /**
  41204. * Constructs a new bounding box.
  41205. *
  41206. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  41207. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  41208. */
  41209. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  41210. /**
  41211. * This flag can be used for type testing.
  41212. *
  41213. * @type {boolean}
  41214. * @readonly
  41215. * @default true
  41216. */
  41217. this.isBox2 = true;
  41218. /**
  41219. * The lower boundary of the box.
  41220. *
  41221. * @type {Vector2}
  41222. */
  41223. this.min = min;
  41224. /**
  41225. * The upper boundary of the box.
  41226. *
  41227. * @type {Vector2}
  41228. */
  41229. this.max = max;
  41230. }
  41231. /**
  41232. * Sets the lower and upper boundaries of this box.
  41233. * Please note that this method only copies the values from the given objects.
  41234. *
  41235. * @param {Vector2} min - The lower boundary of the box.
  41236. * @param {Vector2} max - The upper boundary of the box.
  41237. * @return {Box2} A reference to this bounding box.
  41238. */
  41239. set( min, max ) {
  41240. this.min.copy( min );
  41241. this.max.copy( max );
  41242. return this;
  41243. }
  41244. /**
  41245. * Sets the upper and lower bounds of this box so it encloses the position data
  41246. * in the given array.
  41247. *
  41248. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  41249. * @return {Box2} A reference to this bounding box.
  41250. */
  41251. setFromPoints( points ) {
  41252. this.makeEmpty();
  41253. for ( let i = 0, il = points.length; i < il; i ++ ) {
  41254. this.expandByPoint( points[ i ] );
  41255. }
  41256. return this;
  41257. }
  41258. /**
  41259. * Centers this box on the given center vector and sets this box's width, height and
  41260. * depth to the given size values.
  41261. *
  41262. * @param {Vector2} center - The center of the box.
  41263. * @param {Vector2} size - The x and y dimensions of the box.
  41264. * @return {Box2} A reference to this bounding box.
  41265. */
  41266. setFromCenterAndSize( center, size ) {
  41267. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  41268. this.min.copy( center ).sub( halfSize );
  41269. this.max.copy( center ).add( halfSize );
  41270. return this;
  41271. }
  41272. /**
  41273. * Returns a new box with copied values from this instance.
  41274. *
  41275. * @return {Box2} A clone of this instance.
  41276. */
  41277. clone() {
  41278. return new this.constructor().copy( this );
  41279. }
  41280. /**
  41281. * Copies the values of the given box to this instance.
  41282. *
  41283. * @param {Box2} box - The box to copy.
  41284. * @return {Box2} A reference to this bounding box.
  41285. */
  41286. copy( box ) {
  41287. this.min.copy( box.min );
  41288. this.max.copy( box.max );
  41289. return this;
  41290. }
  41291. /**
  41292. * Makes this box empty which means in encloses a zero space in 2D.
  41293. *
  41294. * @return {Box2} A reference to this bounding box.
  41295. */
  41296. makeEmpty() {
  41297. this.min.x = this.min.y = + Infinity;
  41298. this.max.x = this.max.y = - Infinity;
  41299. return this;
  41300. }
  41301. /**
  41302. * Returns true if this box includes zero points within its bounds.
  41303. * Note that a box with equal lower and upper bounds still includes one
  41304. * point, the one both bounds share.
  41305. *
  41306. * @return {boolean} Whether this box is empty or not.
  41307. */
  41308. isEmpty() {
  41309. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  41310. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  41311. }
  41312. /**
  41313. * Returns the center point of this box.
  41314. *
  41315. * @param {Vector2} target - The target vector that is used to store the method's result.
  41316. * @return {Vector2} The center point.
  41317. */
  41318. getCenter( target ) {
  41319. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  41320. }
  41321. /**
  41322. * Returns the dimensions of this box.
  41323. *
  41324. * @param {Vector2} target - The target vector that is used to store the method's result.
  41325. * @return {Vector2} The size.
  41326. */
  41327. getSize( target ) {
  41328. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  41329. }
  41330. /**
  41331. * Expands the boundaries of this box to include the given point.
  41332. *
  41333. * @param {Vector2} point - The point that should be included by the bounding box.
  41334. * @return {Box2} A reference to this bounding box.
  41335. */
  41336. expandByPoint( point ) {
  41337. this.min.min( point );
  41338. this.max.max( point );
  41339. return this;
  41340. }
  41341. /**
  41342. * Expands this box equilaterally by the given vector. The width of this
  41343. * box will be expanded by the x component of the vector in both
  41344. * directions. The height of this box will be expanded by the y component of
  41345. * the vector in both directions.
  41346. *
  41347. * @param {Vector2} vector - The vector that should expand the bounding box.
  41348. * @return {Box2} A reference to this bounding box.
  41349. */
  41350. expandByVector( vector ) {
  41351. this.min.sub( vector );
  41352. this.max.add( vector );
  41353. return this;
  41354. }
  41355. /**
  41356. * Expands each dimension of the box by the given scalar. If negative, the
  41357. * dimensions of the box will be contracted.
  41358. *
  41359. * @param {number} scalar - The scalar value that should expand the bounding box.
  41360. * @return {Box2} A reference to this bounding box.
  41361. */
  41362. expandByScalar( scalar ) {
  41363. this.min.addScalar( - scalar );
  41364. this.max.addScalar( scalar );
  41365. return this;
  41366. }
  41367. /**
  41368. * Returns `true` if the given point lies within or on the boundaries of this box.
  41369. *
  41370. * @param {Vector2} point - The point to test.
  41371. * @return {boolean} Whether the bounding box contains the given point or not.
  41372. */
  41373. containsPoint( point ) {
  41374. return point.x >= this.min.x && point.x <= this.max.x &&
  41375. point.y >= this.min.y && point.y <= this.max.y;
  41376. }
  41377. /**
  41378. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  41379. * If this box and the given one are identical, this function also returns `true`.
  41380. *
  41381. * @param {Box2} box - The bounding box to test.
  41382. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  41383. */
  41384. containsBox( box ) {
  41385. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  41386. this.min.y <= box.min.y && box.max.y <= this.max.y;
  41387. }
  41388. /**
  41389. * Returns a point as a proportion of this box's width and height.
  41390. *
  41391. * @param {Vector2} point - A point in 2D space.
  41392. * @param {Vector2} target - The target vector that is used to store the method's result.
  41393. * @return {Vector2} A point as a proportion of this box's width and height.
  41394. */
  41395. getParameter( point, target ) {
  41396. // This can potentially have a divide by zero if the box
  41397. // has a size dimension of 0.
  41398. return target.set(
  41399. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  41400. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  41401. );
  41402. }
  41403. /**
  41404. * Returns `true` if the given bounding box intersects with this bounding box.
  41405. *
  41406. * @param {Box2} box - The bounding box to test.
  41407. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  41408. */
  41409. intersectsBox( box ) {
  41410. // using 4 splitting planes to rule out intersections
  41411. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  41412. box.max.y >= this.min.y && box.min.y <= this.max.y;
  41413. }
  41414. /**
  41415. * Clamps the given point within the bounds of this box.
  41416. *
  41417. * @param {Vector2} point - The point to clamp.
  41418. * @param {Vector2} target - The target vector that is used to store the method's result.
  41419. * @return {Vector2} The clamped point.
  41420. */
  41421. clampPoint( point, target ) {
  41422. return target.copy( point ).clamp( this.min, this.max );
  41423. }
  41424. /**
  41425. * Returns the euclidean distance from any edge of this box to the specified point. If
  41426. * the given point lies inside of this box, the distance will be `0`.
  41427. *
  41428. * @param {Vector2} point - The point to compute the distance to.
  41429. * @return {number} The euclidean distance.
  41430. */
  41431. distanceToPoint( point ) {
  41432. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  41433. }
  41434. /**
  41435. * Computes the intersection of this bounding box and the given one, setting the upper
  41436. * bound of this box to the lesser of the two boxes' upper bounds and the
  41437. * lower bound of this box to the greater of the two boxes' lower bounds. If
  41438. * there's no overlap, makes this box empty.
  41439. *
  41440. * @param {Box2} box - The bounding box to intersect with.
  41441. * @return {Box2} A reference to this bounding box.
  41442. */
  41443. intersect( box ) {
  41444. this.min.max( box.min );
  41445. this.max.min( box.max );
  41446. if ( this.isEmpty() ) this.makeEmpty();
  41447. return this;
  41448. }
  41449. /**
  41450. * Computes the union of this box and another and the given one, setting the upper
  41451. * bound of this box to the greater of the two boxes' upper bounds and the
  41452. * lower bound of this box to the lesser of the two boxes' lower bounds.
  41453. *
  41454. * @param {Box2} box - The bounding box that will be unioned with this instance.
  41455. * @return {Box2} A reference to this bounding box.
  41456. */
  41457. union( box ) {
  41458. this.min.min( box.min );
  41459. this.max.max( box.max );
  41460. return this;
  41461. }
  41462. /**
  41463. * Adds the given offset to both the upper and lower bounds of this bounding box,
  41464. * effectively moving it in 2D space.
  41465. *
  41466. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  41467. * @return {Box2} A reference to this bounding box.
  41468. */
  41469. translate( offset ) {
  41470. this.min.add( offset );
  41471. this.max.add( offset );
  41472. return this;
  41473. }
  41474. /**
  41475. * Returns `true` if this bounding box is equal with the given one.
  41476. *
  41477. * @param {Box2} box - The box to test for equality.
  41478. * @return {boolean} Whether this bounding box is equal with the given one.
  41479. */
  41480. equals( box ) {
  41481. return box.min.equals( this.min ) && box.max.equals( this.max );
  41482. }
  41483. }
  41484. const _startP = /*@__PURE__*/ new Vector3();
  41485. const _startEnd = /*@__PURE__*/ new Vector3();
  41486. const _d1 = /*@__PURE__*/ new Vector3();
  41487. const _d2 = /*@__PURE__*/ new Vector3();
  41488. const _r = /*@__PURE__*/ new Vector3();
  41489. const _c1 = /*@__PURE__*/ new Vector3();
  41490. const _c2 = /*@__PURE__*/ new Vector3();
  41491. /**
  41492. * An analytical line segment in 3D space represented by a start and end point.
  41493. */
  41494. class Line3 {
  41495. /**
  41496. * Constructs a new line segment.
  41497. *
  41498. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  41499. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  41500. */
  41501. constructor( start = new Vector3(), end = new Vector3() ) {
  41502. /**
  41503. * Start of the line segment.
  41504. *
  41505. * @type {Vector3}
  41506. */
  41507. this.start = start;
  41508. /**
  41509. * End of the line segment.
  41510. *
  41511. * @type {Vector3}
  41512. */
  41513. this.end = end;
  41514. }
  41515. /**
  41516. * Sets the start and end values by copying the given vectors.
  41517. *
  41518. * @param {Vector3} start - The start point.
  41519. * @param {Vector3} end - The end point.
  41520. * @return {Line3} A reference to this line segment.
  41521. */
  41522. set( start, end ) {
  41523. this.start.copy( start );
  41524. this.end.copy( end );
  41525. return this;
  41526. }
  41527. /**
  41528. * Copies the values of the given line segment to this instance.
  41529. *
  41530. * @param {Line3} line - The line segment to copy.
  41531. * @return {Line3} A reference to this line segment.
  41532. */
  41533. copy( line ) {
  41534. this.start.copy( line.start );
  41535. this.end.copy( line.end );
  41536. return this;
  41537. }
  41538. /**
  41539. * Returns the center of the line segment.
  41540. *
  41541. * @param {Vector3} target - The target vector that is used to store the method's result.
  41542. * @return {Vector3} The center point.
  41543. */
  41544. getCenter( target ) {
  41545. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  41546. }
  41547. /**
  41548. * Returns the delta vector of the line segment's start and end point.
  41549. *
  41550. * @param {Vector3} target - The target vector that is used to store the method's result.
  41551. * @return {Vector3} The delta vector.
  41552. */
  41553. delta( target ) {
  41554. return target.subVectors( this.end, this.start );
  41555. }
  41556. /**
  41557. * Returns the squared Euclidean distance between the line' start and end point.
  41558. *
  41559. * @return {number} The squared Euclidean distance.
  41560. */
  41561. distanceSq() {
  41562. return this.start.distanceToSquared( this.end );
  41563. }
  41564. /**
  41565. * Returns the Euclidean distance between the line' start and end point.
  41566. *
  41567. * @return {number} The Euclidean distance.
  41568. */
  41569. distance() {
  41570. return this.start.distanceTo( this.end );
  41571. }
  41572. /**
  41573. * Returns a vector at a certain position along the line segment.
  41574. *
  41575. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  41576. * @param {Vector3} target - The target vector that is used to store the method's result.
  41577. * @return {Vector3} The delta vector.
  41578. */
  41579. at( t, target ) {
  41580. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41581. }
  41582. /**
  41583. * Returns a point parameter based on the closest point as projected on the line segment.
  41584. *
  41585. * @param {Vector3} point - The point for which to return a point parameter.
  41586. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41587. * @return {number} The point parameter.
  41588. */
  41589. closestPointToPointParameter( point, clampToLine ) {
  41590. _startP.subVectors( point, this.start );
  41591. _startEnd.subVectors( this.end, this.start );
  41592. const startEnd2 = _startEnd.dot( _startEnd );
  41593. if ( startEnd2 === 0 ) return 0;
  41594. const startEnd_startP = _startEnd.dot( _startP );
  41595. let t = startEnd_startP / startEnd2;
  41596. if ( clampToLine ) {
  41597. t = clamp( t, 0, 1 );
  41598. }
  41599. return t;
  41600. }
  41601. /**
  41602. * Returns the closest point on the line for a given point.
  41603. *
  41604. * @param {Vector3} point - The point to compute the closest point on the line for.
  41605. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41606. * @param {Vector3} target - The target vector that is used to store the method's result.
  41607. * @return {Vector3} The closest point on the line.
  41608. */
  41609. closestPointToPoint( point, clampToLine, target ) {
  41610. const t = this.closestPointToPointParameter( point, clampToLine );
  41611. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41612. }
  41613. /**
  41614. * Returns the closest squared distance between this line segment and the given one.
  41615. *
  41616. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41617. * @param {Vector3} [c1] - The closest point on this line segment.
  41618. * @param {Vector3} [c2] - The closest point on the given line segment.
  41619. * @return {number} The squared distance between this line segment and the given one.
  41620. */
  41621. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41622. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41623. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41624. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41625. // distance between between S1(s) and S2(t)
  41626. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41627. let s, t;
  41628. const p1 = this.start;
  41629. const p2 = line.start;
  41630. const q1 = this.end;
  41631. const q2 = line.end;
  41632. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41633. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41634. _r.subVectors( p1, p2 );
  41635. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41636. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41637. const f = _d2.dot( _r );
  41638. // Check if either or both segments degenerate into points
  41639. if ( a <= EPSILON && e <= EPSILON ) {
  41640. // Both segments degenerate into points
  41641. c1.copy( p1 );
  41642. c2.copy( p2 );
  41643. c1.sub( c2 );
  41644. return c1.dot( c1 );
  41645. }
  41646. if ( a <= EPSILON ) {
  41647. // First segment degenerates into a point
  41648. s = 0;
  41649. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41650. t = clamp( t, 0, 1 );
  41651. } else {
  41652. const c = _d1.dot( _r );
  41653. if ( e <= EPSILON ) {
  41654. // Second segment degenerates into a point
  41655. t = 0;
  41656. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41657. } else {
  41658. // The general nondegenerate case starts here
  41659. const b = _d1.dot( _d2 );
  41660. const denom = a * e - b * b; // Always nonnegative
  41661. // If segments not parallel, compute closest point on L1 to L2 and
  41662. // clamp to segment S1. Else pick arbitrary s (here 0)
  41663. if ( denom !== 0 ) {
  41664. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41665. } else {
  41666. s = 0;
  41667. }
  41668. // Compute point on L2 closest to S1(s) using
  41669. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41670. t = ( b * s + f ) / e;
  41671. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41672. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41673. // and clamp s to [0, 1]
  41674. if ( t < 0 ) {
  41675. t = 0.;
  41676. s = clamp( - c / a, 0, 1 );
  41677. } else if ( t > 1 ) {
  41678. t = 1;
  41679. s = clamp( ( b - c ) / a, 0, 1 );
  41680. }
  41681. }
  41682. }
  41683. c1.copy( p1 ).addScaledVector( _d1, s );
  41684. c2.copy( p2 ).addScaledVector( _d2, t );
  41685. return c1.distanceToSquared( c2 );
  41686. }
  41687. /**
  41688. * Applies a 4x4 transformation matrix to this line segment.
  41689. *
  41690. * @param {Matrix4} matrix - The transformation matrix.
  41691. * @return {Line3} A reference to this line segment.
  41692. */
  41693. applyMatrix4( matrix ) {
  41694. this.start.applyMatrix4( matrix );
  41695. this.end.applyMatrix4( matrix );
  41696. return this;
  41697. }
  41698. /**
  41699. * Returns `true` if this line segment is equal with the given one.
  41700. *
  41701. * @param {Line3} line - The line segment to test for equality.
  41702. * @return {boolean} Whether this line segment is equal with the given one.
  41703. */
  41704. equals( line ) {
  41705. return line.start.equals( this.start ) && line.end.equals( this.end );
  41706. }
  41707. /**
  41708. * Returns a new line segment with copied values from this instance.
  41709. *
  41710. * @return {Line3} A clone of this instance.
  41711. */
  41712. clone() {
  41713. return new this.constructor().copy( this );
  41714. }
  41715. }
  41716. const _vector$3 = /*@__PURE__*/ new Vector3();
  41717. /**
  41718. * This displays a cone shaped helper object for a {@link SpotLight}.
  41719. *
  41720. * When the spot light or its target are transformed or light properties are
  41721. * changed, it's necessary to call the `update()` method of the respective helper.
  41722. *
  41723. * ```js
  41724. * const spotLight = new THREE.SpotLight( 0xffffff );
  41725. * spotLight.position.set( 10, 10, 10 );
  41726. * scene.add( spotLight );
  41727. *
  41728. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41729. * scene.add( spotLightHelper );
  41730. * ```
  41731. *
  41732. * @augments Object3D
  41733. */
  41734. class SpotLightHelper extends Object3D {
  41735. /**
  41736. * Constructs a new spot light helper.
  41737. *
  41738. * @param {HemisphereLight} light - The light to be visualized.
  41739. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41740. * the color of the light.
  41741. */
  41742. constructor( light, color ) {
  41743. super();
  41744. /**
  41745. * The light being visualized.
  41746. *
  41747. * @type {SpotLight}
  41748. */
  41749. this.light = light;
  41750. this.matrixAutoUpdate = false;
  41751. /**
  41752. * The color parameter passed in the constructor.
  41753. * If not set, the helper will take the color of the light.
  41754. *
  41755. * @type {number|Color|string}
  41756. */
  41757. this.color = color;
  41758. this.type = 'SpotLightHelper';
  41759. const geometry = new BufferGeometry();
  41760. const positions = [
  41761. 0, 0, 0, 0, 0, 1,
  41762. 0, 0, 0, 1, 0, 1,
  41763. 0, 0, 0, -1, 0, 1,
  41764. 0, 0, 0, 0, 1, 1,
  41765. 0, 0, 0, 0, -1, 1
  41766. ];
  41767. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41768. const p1 = ( i / l ) * Math.PI * 2;
  41769. const p2 = ( j / l ) * Math.PI * 2;
  41770. positions.push(
  41771. Math.cos( p1 ), Math.sin( p1 ), 1,
  41772. Math.cos( p2 ), Math.sin( p2 ), 1
  41773. );
  41774. }
  41775. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41776. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41777. this.cone = new LineSegments( geometry, material );
  41778. this.add( this.cone );
  41779. this.update();
  41780. }
  41781. /**
  41782. * Frees the GPU-related resources allocated by this instance. Call this
  41783. * method whenever this instance is no longer used in your app.
  41784. */
  41785. dispose() {
  41786. this.cone.geometry.dispose();
  41787. this.cone.material.dispose();
  41788. }
  41789. /**
  41790. * Updates the helper to match the position and direction of the
  41791. * light being visualized.
  41792. */
  41793. update() {
  41794. this.light.updateWorldMatrix( true, false );
  41795. this.light.target.updateWorldMatrix( true, false );
  41796. // update the local matrix based on the parent and light target transforms
  41797. if ( this.parent ) {
  41798. this.parent.updateWorldMatrix( true );
  41799. this.matrix
  41800. .copy( this.parent.matrixWorld )
  41801. .invert()
  41802. .multiply( this.light.matrixWorld );
  41803. } else {
  41804. this.matrix.copy( this.light.matrixWorld );
  41805. }
  41806. this.matrixWorld.copy( this.light.matrixWorld );
  41807. const coneLength = this.light.distance ? this.light.distance : 1000;
  41808. const coneWidth = coneLength * Math.tan( this.light.angle );
  41809. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41810. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41811. this.cone.lookAt( _vector$3 );
  41812. if ( this.color !== undefined ) {
  41813. this.cone.material.color.set( this.color );
  41814. } else {
  41815. this.cone.material.color.copy( this.light.color );
  41816. }
  41817. }
  41818. }
  41819. const _vector$2 = /*@__PURE__*/ new Vector3();
  41820. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41821. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41822. /**
  41823. * A helper object to assist with visualizing a {@link Skeleton}.
  41824. *
  41825. * ```js
  41826. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41827. * scene.add( helper );
  41828. * ```
  41829. *
  41830. * @augments LineSegments
  41831. */
  41832. class SkeletonHelper extends LineSegments {
  41833. /**
  41834. * Constructs a new skeleton helper.
  41835. *
  41836. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41837. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41838. */
  41839. constructor( object ) {
  41840. const bones = getBoneList( object );
  41841. const geometry = new BufferGeometry();
  41842. const vertices = [];
  41843. const colors = [];
  41844. for ( let i = 0; i < bones.length; i ++ ) {
  41845. const bone = bones[ i ];
  41846. if ( bone.parent && bone.parent.isBone ) {
  41847. vertices.push( 0, 0, 0 );
  41848. vertices.push( 0, 0, 0 );
  41849. colors.push( 0, 0, 0 );
  41850. colors.push( 0, 0, 0 );
  41851. }
  41852. }
  41853. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41854. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41855. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41856. super( geometry, material );
  41857. /**
  41858. * This flag can be used for type testing.
  41859. *
  41860. * @type {boolean}
  41861. * @readonly
  41862. * @default true
  41863. */
  41864. this.isSkeletonHelper = true;
  41865. this.type = 'SkeletonHelper';
  41866. /**
  41867. * The object being visualized.
  41868. *
  41869. * @type {Object3D}
  41870. */
  41871. this.root = object;
  41872. /**
  41873. * The list of bones that the helper visualizes.
  41874. *
  41875. * @type {Array<Bone>}
  41876. */
  41877. this.bones = bones;
  41878. this.matrix = object.matrixWorld;
  41879. this.matrixAutoUpdate = false;
  41880. // colors
  41881. const color1 = new Color( 0x0000ff );
  41882. const color2 = new Color( 0x00ff00 );
  41883. this.setColors( color1, color2 );
  41884. }
  41885. updateMatrixWorld( force ) {
  41886. const bones = this.bones;
  41887. const geometry = this.geometry;
  41888. const position = geometry.getAttribute( 'position' );
  41889. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41890. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41891. const bone = bones[ i ];
  41892. if ( bone.parent && bone.parent.isBone ) {
  41893. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41894. _vector$2.setFromMatrixPosition( _boneMatrix );
  41895. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41896. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41897. _vector$2.setFromMatrixPosition( _boneMatrix );
  41898. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41899. j += 2;
  41900. }
  41901. }
  41902. geometry.getAttribute( 'position' ).needsUpdate = true;
  41903. super.updateMatrixWorld( force );
  41904. }
  41905. /**
  41906. * Defines the colors of the helper.
  41907. *
  41908. * @param {Color} color1 - The first line color for each bone.
  41909. * @param {Color} color2 - The second line color for each bone.
  41910. * @return {SkeletonHelper} A reference to this helper.
  41911. */
  41912. setColors( color1, color2 ) {
  41913. const geometry = this.geometry;
  41914. const colorAttribute = geometry.getAttribute( 'color' );
  41915. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41916. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41917. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41918. }
  41919. colorAttribute.needsUpdate = true;
  41920. return this;
  41921. }
  41922. /**
  41923. * Frees the GPU-related resources allocated by this instance. Call this
  41924. * method whenever this instance is no longer used in your app.
  41925. */
  41926. dispose() {
  41927. this.geometry.dispose();
  41928. this.material.dispose();
  41929. }
  41930. }
  41931. function getBoneList( object ) {
  41932. const boneList = [];
  41933. if ( object.isBone === true ) {
  41934. boneList.push( object );
  41935. }
  41936. for ( let i = 0; i < object.children.length; i ++ ) {
  41937. boneList.push( ...getBoneList( object.children[ i ] ) );
  41938. }
  41939. return boneList;
  41940. }
  41941. /**
  41942. * This displays a helper object consisting of a spherical mesh for
  41943. * visualizing an instance of {@link PointLight}.
  41944. *
  41945. * ```js
  41946. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41947. * pointLight.position.set( 10, 10, 10 );
  41948. * scene.add( pointLight );
  41949. *
  41950. * const sphereSize = 1;
  41951. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41952. * scene.add( pointLightHelper );
  41953. * ```
  41954. *
  41955. * @augments Mesh
  41956. */
  41957. class PointLightHelper extends Mesh {
  41958. /**
  41959. * Constructs a new point light helper.
  41960. *
  41961. * @param {PointLight} light - The light to be visualized.
  41962. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41963. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41964. * the color of the light.
  41965. */
  41966. constructor( light, sphereSize, color ) {
  41967. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41968. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41969. super( geometry, material );
  41970. /**
  41971. * The light being visualized.
  41972. *
  41973. * @type {PointLight}
  41974. */
  41975. this.light = light;
  41976. /**
  41977. * The color parameter passed in the constructor.
  41978. * If not set, the helper will take the color of the light.
  41979. *
  41980. * @type {number|Color|string}
  41981. */
  41982. this.color = color;
  41983. this.type = 'PointLightHelper';
  41984. this.matrix = this.light.matrixWorld;
  41985. this.matrixAutoUpdate = false;
  41986. this.update();
  41987. }
  41988. /**
  41989. * Frees the GPU-related resources allocated by this instance. Call this
  41990. * method whenever this instance is no longer used in your app.
  41991. */
  41992. dispose() {
  41993. this.geometry.dispose();
  41994. this.material.dispose();
  41995. }
  41996. /**
  41997. * Updates the helper to match the position of the
  41998. * light being visualized.
  41999. */
  42000. update() {
  42001. this.light.updateWorldMatrix( true, false );
  42002. if ( this.color !== undefined ) {
  42003. this.material.color.set( this.color );
  42004. } else {
  42005. this.material.color.copy( this.light.color );
  42006. }
  42007. /*
  42008. const d = this.light.distance;
  42009. if ( d === 0.0 ) {
  42010. this.lightDistance.visible = false;
  42011. } else {
  42012. this.lightDistance.visible = true;
  42013. this.lightDistance.scale.set( d, d, d );
  42014. }
  42015. */
  42016. }
  42017. }
  42018. const _vector$1 = /*@__PURE__*/ new Vector3();
  42019. const _color1 = /*@__PURE__*/ new Color();
  42020. const _color2 = /*@__PURE__*/ new Color();
  42021. /**
  42022. * Creates a visual aid consisting of a spherical mesh for a
  42023. * given {@link HemisphereLight}.
  42024. *
  42025. * When the hemisphere light is transformed or its light properties are changed,
  42026. * it's necessary to call the `update()` method of the respective helper.
  42027. *
  42028. * ```js
  42029. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  42030. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  42031. * scene.add( helper );
  42032. * ```
  42033. *
  42034. * @augments Object3D
  42035. */
  42036. class HemisphereLightHelper extends Object3D {
  42037. /**
  42038. * Constructs a new hemisphere light helper.
  42039. *
  42040. * @param {HemisphereLight} light - The light to be visualized.
  42041. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  42042. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42043. * the color of the light.
  42044. */
  42045. constructor( light, size, color ) {
  42046. super();
  42047. /**
  42048. * The light being visualized.
  42049. *
  42050. * @type {HemisphereLight}
  42051. */
  42052. this.light = light;
  42053. this.matrix = light.matrixWorld;
  42054. this.matrixAutoUpdate = false;
  42055. /**
  42056. * The color parameter passed in the constructor.
  42057. * If not set, the helper will take the color of the light.
  42058. *
  42059. * @type {number|Color|string}
  42060. */
  42061. this.color = color;
  42062. this.type = 'HemisphereLightHelper';
  42063. const geometry = new OctahedronGeometry( size );
  42064. geometry.rotateY( Math.PI * 0.5 );
  42065. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  42066. if ( this.color === undefined ) this.material.vertexColors = true;
  42067. const position = geometry.getAttribute( 'position' );
  42068. const colors = new Float32Array( position.count * 3 );
  42069. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  42070. this.add( new Mesh( geometry, this.material ) );
  42071. this.update();
  42072. }
  42073. /**
  42074. * Frees the GPU-related resources allocated by this instance. Call this
  42075. * method whenever this instance is no longer used in your app.
  42076. */
  42077. dispose() {
  42078. this.children[ 0 ].geometry.dispose();
  42079. this.children[ 0 ].material.dispose();
  42080. }
  42081. /**
  42082. * Updates the helper to match the position and direction of the
  42083. * light being visualized.
  42084. */
  42085. update() {
  42086. const mesh = this.children[ 0 ];
  42087. if ( this.color !== undefined ) {
  42088. this.material.color.set( this.color );
  42089. } else {
  42090. const colors = mesh.geometry.getAttribute( 'color' );
  42091. _color1.copy( this.light.color );
  42092. _color2.copy( this.light.groundColor );
  42093. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  42094. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  42095. colors.setXYZ( i, color.r, color.g, color.b );
  42096. }
  42097. colors.needsUpdate = true;
  42098. }
  42099. this.light.updateWorldMatrix( true, false );
  42100. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  42101. }
  42102. }
  42103. /**
  42104. * The helper is an object to define grids. Grids are two-dimensional
  42105. * arrays of lines.
  42106. *
  42107. * ```js
  42108. * const size = 10;
  42109. * const divisions = 10;
  42110. *
  42111. * const gridHelper = new THREE.GridHelper( size, divisions );
  42112. * scene.add( gridHelper );
  42113. * ```
  42114. *
  42115. * @augments LineSegments
  42116. */
  42117. class GridHelper extends LineSegments {
  42118. /**
  42119. * Constructs a new grid helper.
  42120. *
  42121. * @param {number} [size=10] - The size of the grid.
  42122. * @param {number} [divisions=10] - The number of divisions across the grid.
  42123. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  42124. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  42125. */
  42126. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  42127. color1 = new Color( color1 );
  42128. color2 = new Color( color2 );
  42129. const center = divisions / 2;
  42130. const step = size / divisions;
  42131. const halfSize = size / 2;
  42132. const vertices = [], colors = [];
  42133. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  42134. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  42135. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  42136. const color = i === center ? color1 : color2;
  42137. color.toArray( colors, j ); j += 3;
  42138. color.toArray( colors, j ); j += 3;
  42139. color.toArray( colors, j ); j += 3;
  42140. color.toArray( colors, j ); j += 3;
  42141. }
  42142. const geometry = new BufferGeometry();
  42143. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42144. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42145. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42146. super( geometry, material );
  42147. this.type = 'GridHelper';
  42148. }
  42149. /**
  42150. * Frees the GPU-related resources allocated by this instance. Call this
  42151. * method whenever this instance is no longer used in your app.
  42152. */
  42153. dispose() {
  42154. this.geometry.dispose();
  42155. this.material.dispose();
  42156. }
  42157. }
  42158. /**
  42159. * This helper is an object to define polar grids. Grids are
  42160. * two-dimensional arrays of lines.
  42161. *
  42162. * ```js
  42163. * const radius = 10;
  42164. * const sectors = 16;
  42165. * const rings = 8;
  42166. * const divisions = 64;
  42167. *
  42168. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  42169. * scene.add( helper );
  42170. * ```
  42171. *
  42172. * @augments LineSegments
  42173. */
  42174. class PolarGridHelper extends LineSegments {
  42175. /**
  42176. * Constructs a new polar grid helper.
  42177. *
  42178. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  42179. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  42180. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  42181. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  42182. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  42183. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  42184. */
  42185. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  42186. color1 = new Color( color1 );
  42187. color2 = new Color( color2 );
  42188. const vertices = [];
  42189. const colors = [];
  42190. // create the sectors
  42191. if ( sectors > 1 ) {
  42192. for ( let i = 0; i < sectors; i ++ ) {
  42193. const v = ( i / sectors ) * ( Math.PI * 2 );
  42194. const x = Math.sin( v ) * radius;
  42195. const z = Math.cos( v ) * radius;
  42196. vertices.push( 0, 0, 0 );
  42197. vertices.push( x, 0, z );
  42198. const color = ( i & 1 ) ? color1 : color2;
  42199. colors.push( color.r, color.g, color.b );
  42200. colors.push( color.r, color.g, color.b );
  42201. }
  42202. }
  42203. // create the rings
  42204. for ( let i = 0; i < rings; i ++ ) {
  42205. const color = ( i & 1 ) ? color1 : color2;
  42206. const r = radius - ( radius / rings * i );
  42207. for ( let j = 0; j < divisions; j ++ ) {
  42208. // first vertex
  42209. let v = ( j / divisions ) * ( Math.PI * 2 );
  42210. let x = Math.sin( v ) * r;
  42211. let z = Math.cos( v ) * r;
  42212. vertices.push( x, 0, z );
  42213. colors.push( color.r, color.g, color.b );
  42214. // second vertex
  42215. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  42216. x = Math.sin( v ) * r;
  42217. z = Math.cos( v ) * r;
  42218. vertices.push( x, 0, z );
  42219. colors.push( color.r, color.g, color.b );
  42220. }
  42221. }
  42222. const geometry = new BufferGeometry();
  42223. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42224. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42225. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42226. super( geometry, material );
  42227. this.type = 'PolarGridHelper';
  42228. }
  42229. /**
  42230. * Frees the GPU-related resources allocated by this instance. Call this
  42231. * method whenever this instance is no longer used in your app.
  42232. */
  42233. dispose() {
  42234. this.geometry.dispose();
  42235. this.material.dispose();
  42236. }
  42237. }
  42238. const _v1 = /*@__PURE__*/ new Vector3();
  42239. const _v2 = /*@__PURE__*/ new Vector3();
  42240. const _v3 = /*@__PURE__*/ new Vector3();
  42241. /**
  42242. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  42243. * effect on the scene. This consists of a plane and a line representing the
  42244. * light's position and direction.
  42245. *
  42246. * When the directional light or its target are transformed or light properties
  42247. * are changed, it's necessary to call the `update()` method of the respective helper.
  42248. *
  42249. * ```js
  42250. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  42251. * scene.add( light );
  42252. *
  42253. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  42254. * scene.add( helper );
  42255. * ```
  42256. *
  42257. * @augments Object3D
  42258. */
  42259. class DirectionalLightHelper extends Object3D {
  42260. /**
  42261. * Constructs a new directional light helper.
  42262. *
  42263. * @param {DirectionalLight} light - The light to be visualized.
  42264. * @param {number} [size=1] - The dimensions of the plane.
  42265. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  42266. * the color of the light.
  42267. */
  42268. constructor( light, size, color ) {
  42269. super();
  42270. /**
  42271. * The light being visualized.
  42272. *
  42273. * @type {DirectionalLight}
  42274. */
  42275. this.light = light;
  42276. this.matrix = light.matrixWorld;
  42277. this.matrixAutoUpdate = false;
  42278. /**
  42279. * The color parameter passed in the constructor.
  42280. * If not set, the helper will take the color of the light.
  42281. *
  42282. * @type {number|Color|string}
  42283. */
  42284. this.color = color;
  42285. this.type = 'DirectionalLightHelper';
  42286. if ( size === undefined ) size = 1;
  42287. let geometry = new BufferGeometry();
  42288. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  42289. - size, size, 0,
  42290. size, size, 0,
  42291. size, - size, 0,
  42292. - size, - size, 0,
  42293. - size, size, 0
  42294. ], 3 ) );
  42295. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  42296. /**
  42297. * Contains the line showing the location of the directional light.
  42298. *
  42299. * @type {Line}
  42300. */
  42301. this.lightPlane = new Line( geometry, material );
  42302. this.add( this.lightPlane );
  42303. geometry = new BufferGeometry();
  42304. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  42305. /**
  42306. * Represents the target line of the directional light.
  42307. *
  42308. * @type {Line}
  42309. */
  42310. this.targetLine = new Line( geometry, material );
  42311. this.add( this.targetLine );
  42312. this.update();
  42313. }
  42314. /**
  42315. * Frees the GPU-related resources allocated by this instance. Call this
  42316. * method whenever this instance is no longer used in your app.
  42317. */
  42318. dispose() {
  42319. this.lightPlane.geometry.dispose();
  42320. this.lightPlane.material.dispose();
  42321. this.targetLine.geometry.dispose();
  42322. this.targetLine.material.dispose();
  42323. }
  42324. /**
  42325. * Updates the helper to match the position and direction of the
  42326. * light being visualized.
  42327. */
  42328. update() {
  42329. this.light.updateWorldMatrix( true, false );
  42330. this.light.target.updateWorldMatrix( true, false );
  42331. _v1.setFromMatrixPosition( this.light.matrixWorld );
  42332. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  42333. _v3.subVectors( _v2, _v1 );
  42334. this.lightPlane.lookAt( _v2 );
  42335. if ( this.color !== undefined ) {
  42336. this.lightPlane.material.color.set( this.color );
  42337. this.targetLine.material.color.set( this.color );
  42338. } else {
  42339. this.lightPlane.material.color.copy( this.light.color );
  42340. this.targetLine.material.color.copy( this.light.color );
  42341. }
  42342. this.targetLine.lookAt( _v2 );
  42343. this.targetLine.scale.z = _v3.length();
  42344. }
  42345. }
  42346. const _vector = /*@__PURE__*/ new Vector3();
  42347. const _camera = /*@__PURE__*/ new Camera();
  42348. /**
  42349. * This helps with visualizing what a camera contains in its frustum. It
  42350. * visualizes the frustum of a camera using a line segments.
  42351. *
  42352. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  42353. *
  42354. * `CameraHelper` must be a child of the scene.
  42355. *
  42356. * When the camera is transformed or its projection matrix is changed, it's necessary
  42357. * to call the `update()` method of the respective helper.
  42358. *
  42359. * ```js
  42360. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  42361. * const helper = new THREE.CameraHelper( camera );
  42362. * scene.add( helper );
  42363. * ```
  42364. *
  42365. * @augments LineSegments
  42366. */
  42367. class CameraHelper extends LineSegments {
  42368. /**
  42369. * Constructs a new arrow helper.
  42370. *
  42371. * @param {Camera} camera - The camera to visualize.
  42372. */
  42373. constructor( camera ) {
  42374. const geometry = new BufferGeometry();
  42375. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  42376. const vertices = [];
  42377. const colors = [];
  42378. const pointMap = {};
  42379. // near
  42380. addLine( 'n1', 'n2' );
  42381. addLine( 'n2', 'n4' );
  42382. addLine( 'n4', 'n3' );
  42383. addLine( 'n3', 'n1' );
  42384. // far
  42385. addLine( 'f1', 'f2' );
  42386. addLine( 'f2', 'f4' );
  42387. addLine( 'f4', 'f3' );
  42388. addLine( 'f3', 'f1' );
  42389. // sides
  42390. addLine( 'n1', 'f1' );
  42391. addLine( 'n2', 'f2' );
  42392. addLine( 'n3', 'f3' );
  42393. addLine( 'n4', 'f4' );
  42394. // cone
  42395. addLine( 'p', 'n1' );
  42396. addLine( 'p', 'n2' );
  42397. addLine( 'p', 'n3' );
  42398. addLine( 'p', 'n4' );
  42399. // up
  42400. addLine( 'u1', 'u2' );
  42401. addLine( 'u2', 'u3' );
  42402. addLine( 'u3', 'u1' );
  42403. // target
  42404. addLine( 'c', 't' );
  42405. addLine( 'p', 'c' );
  42406. // cross
  42407. addLine( 'cn1', 'cn2' );
  42408. addLine( 'cn3', 'cn4' );
  42409. addLine( 'cf1', 'cf2' );
  42410. addLine( 'cf3', 'cf4' );
  42411. function addLine( a, b ) {
  42412. addPoint( a );
  42413. addPoint( b );
  42414. }
  42415. function addPoint( id ) {
  42416. vertices.push( 0, 0, 0 );
  42417. colors.push( 0, 0, 0 );
  42418. if ( pointMap[ id ] === undefined ) {
  42419. pointMap[ id ] = [];
  42420. }
  42421. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  42422. }
  42423. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42424. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42425. super( geometry, material );
  42426. this.type = 'CameraHelper';
  42427. /**
  42428. * The camera being visualized.
  42429. *
  42430. * @type {Camera}
  42431. */
  42432. this.camera = camera;
  42433. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  42434. this.matrix = camera.matrixWorld;
  42435. this.matrixAutoUpdate = false;
  42436. /**
  42437. * This contains the points used to visualize the camera.
  42438. *
  42439. * @type {Object<string,Array<number>>}
  42440. */
  42441. this.pointMap = pointMap;
  42442. this.update();
  42443. // colors
  42444. const colorFrustum = new Color( 0xffaa00 );
  42445. const colorCone = new Color( 0xff0000 );
  42446. const colorUp = new Color( 0x00aaff );
  42447. const colorTarget = new Color( 0xffffff );
  42448. const colorCross = new Color( 0x333333 );
  42449. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  42450. }
  42451. /**
  42452. * Defines the colors of the helper.
  42453. *
  42454. * @param {Color} frustum - The frustum line color.
  42455. * @param {Color} cone - The cone line color.
  42456. * @param {Color} up - The up line color.
  42457. * @param {Color} target - The target line color.
  42458. * @param {Color} cross - The cross line color.
  42459. * @return {CameraHelper} A reference to this helper.
  42460. */
  42461. setColors( frustum, cone, up, target, cross ) {
  42462. const geometry = this.geometry;
  42463. const colorAttribute = geometry.getAttribute( 'color' );
  42464. // near
  42465. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  42466. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  42467. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  42468. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  42469. // far
  42470. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  42471. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  42472. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  42473. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  42474. // sides
  42475. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  42476. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  42477. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  42478. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  42479. // cone
  42480. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  42481. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  42482. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  42483. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  42484. // up
  42485. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  42486. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  42487. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  42488. // target
  42489. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  42490. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  42491. // cross
  42492. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  42493. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  42494. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  42495. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  42496. colorAttribute.needsUpdate = true;
  42497. return this;
  42498. }
  42499. /**
  42500. * Updates the helper based on the projection matrix of the camera.
  42501. */
  42502. update() {
  42503. const geometry = this.geometry;
  42504. const pointMap = this.pointMap;
  42505. const w = 1, h = 1;
  42506. let nearZ, farZ;
  42507. // we need just camera projection matrix inverse
  42508. // world matrix must be identity
  42509. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  42510. // Adjust z values based on coordinate system
  42511. if ( this.camera.reversedDepth === true ) {
  42512. nearZ = 1;
  42513. farZ = 0;
  42514. } else {
  42515. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  42516. nearZ = -1;
  42517. farZ = 1;
  42518. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  42519. nearZ = 0;
  42520. farZ = 1;
  42521. } else {
  42522. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  42523. }
  42524. }
  42525. // center / target
  42526. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  42527. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  42528. // near
  42529. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  42530. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  42531. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  42532. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  42533. // far
  42534. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  42535. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  42536. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  42537. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  42538. // up
  42539. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  42540. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  42541. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  42542. // cross
  42543. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  42544. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  42545. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  42546. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  42547. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  42548. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  42549. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  42550. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  42551. geometry.getAttribute( 'position' ).needsUpdate = true;
  42552. }
  42553. /**
  42554. * Frees the GPU-related resources allocated by this instance. Call this
  42555. * method whenever this instance is no longer used in your app.
  42556. */
  42557. dispose() {
  42558. this.geometry.dispose();
  42559. this.material.dispose();
  42560. }
  42561. }
  42562. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  42563. _vector.set( x, y, z ).unproject( camera );
  42564. const points = pointMap[ point ];
  42565. if ( points !== undefined ) {
  42566. const position = geometry.getAttribute( 'position' );
  42567. for ( let i = 0, l = points.length; i < l; i ++ ) {
  42568. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  42569. }
  42570. }
  42571. }
  42572. const _box = /*@__PURE__*/ new Box3();
  42573. /**
  42574. * Helper object to graphically show the world-axis-aligned bounding box
  42575. * around an object. The actual bounding box is handled with {@link Box3},
  42576. * this is just a visual helper for debugging. It can be automatically
  42577. * resized with {@link BoxHelper#update} when the object it's created from
  42578. * is transformed. Note that the object must have a geometry for this to work,
  42579. * so it won't work with sprites.
  42580. *
  42581. * ```js
  42582. * const sphere = new THREE.SphereGeometry();
  42583. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42584. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42585. * scene.add( box );
  42586. * ```
  42587. *
  42588. * @augments LineSegments
  42589. */
  42590. class BoxHelper extends LineSegments {
  42591. /**
  42592. * Constructs a new box helper.
  42593. *
  42594. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42595. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42596. */
  42597. constructor( object, color = 0xffff00 ) {
  42598. 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 ] );
  42599. const positions = new Float32Array( 8 * 3 );
  42600. const geometry = new BufferGeometry();
  42601. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42602. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42603. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42604. /**
  42605. * The 3D object being visualized.
  42606. *
  42607. * @type {Object3D}
  42608. */
  42609. this.object = object;
  42610. this.type = 'BoxHelper';
  42611. this.matrixAutoUpdate = false;
  42612. this.update();
  42613. }
  42614. /**
  42615. * Updates the helper's geometry to match the dimensions of the object,
  42616. * including any children.
  42617. */
  42618. update() {
  42619. if ( this.object !== undefined ) {
  42620. _box.setFromObject( this.object );
  42621. }
  42622. if ( _box.isEmpty() ) return;
  42623. const min = _box.min;
  42624. const max = _box.max;
  42625. /*
  42626. 5____4
  42627. 1/___0/|
  42628. | 6__|_7
  42629. 2/___3/
  42630. 0: max.x, max.y, max.z
  42631. 1: min.x, max.y, max.z
  42632. 2: min.x, min.y, max.z
  42633. 3: max.x, min.y, max.z
  42634. 4: max.x, max.y, min.z
  42635. 5: min.x, max.y, min.z
  42636. 6: min.x, min.y, min.z
  42637. 7: max.x, min.y, min.z
  42638. */
  42639. const position = this.geometry.attributes.position;
  42640. const array = position.array;
  42641. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42642. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42643. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42644. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42645. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42646. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42647. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42648. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42649. position.needsUpdate = true;
  42650. this.geometry.computeBoundingSphere();
  42651. }
  42652. /**
  42653. * Updates the wireframe box for the passed object.
  42654. *
  42655. * @param {Object3D} object - The 3D object to create the helper for.
  42656. * @return {BoxHelper} A reference to this instance.
  42657. */
  42658. setFromObject( object ) {
  42659. this.object = object;
  42660. this.update();
  42661. return this;
  42662. }
  42663. copy( source, recursive ) {
  42664. super.copy( source, recursive );
  42665. this.object = source.object;
  42666. return this;
  42667. }
  42668. /**
  42669. * Frees the GPU-related resources allocated by this instance. Call this
  42670. * method whenever this instance is no longer used in your app.
  42671. */
  42672. dispose() {
  42673. this.geometry.dispose();
  42674. this.material.dispose();
  42675. }
  42676. }
  42677. /**
  42678. * A helper object to visualize an instance of {@link Box3}.
  42679. *
  42680. * ```js
  42681. * const box = new THREE.Box3();
  42682. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42683. *
  42684. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42685. * scene.add( helper )
  42686. * ```
  42687. *
  42688. * @augments LineSegments
  42689. */
  42690. class Box3Helper extends LineSegments {
  42691. /**
  42692. * Constructs a new box3 helper.
  42693. *
  42694. * @param {Box3} box - The box to visualize.
  42695. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42696. */
  42697. constructor( box, color = 0xffff00 ) {
  42698. 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 ] );
  42699. 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 ];
  42700. const geometry = new BufferGeometry();
  42701. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42702. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42703. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42704. /**
  42705. * The box being visualized.
  42706. *
  42707. * @type {Box3}
  42708. */
  42709. this.box = box;
  42710. this.type = 'Box3Helper';
  42711. this.geometry.computeBoundingSphere();
  42712. }
  42713. updateMatrixWorld( force ) {
  42714. const box = this.box;
  42715. if ( box.isEmpty() ) return;
  42716. box.getCenter( this.position );
  42717. box.getSize( this.scale );
  42718. this.scale.multiplyScalar( 0.5 );
  42719. super.updateMatrixWorld( force );
  42720. }
  42721. /**
  42722. * Frees the GPU-related resources allocated by this instance. Call this
  42723. * method whenever this instance is no longer used in your app.
  42724. */
  42725. dispose() {
  42726. this.geometry.dispose();
  42727. this.material.dispose();
  42728. }
  42729. }
  42730. /**
  42731. * A helper object to visualize an instance of {@link Plane}.
  42732. *
  42733. * ```js
  42734. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42735. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42736. * scene.add( helper );
  42737. * ```
  42738. *
  42739. * @augments Line
  42740. */
  42741. class PlaneHelper extends Line {
  42742. /**
  42743. * Constructs a new plane helper.
  42744. *
  42745. * @param {Plane} plane - The plane to be visualized.
  42746. * @param {number} [size=1] - The side length of plane helper.
  42747. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42748. */
  42749. constructor( plane, size = 1, hex = 0xffff00 ) {
  42750. const color = hex;
  42751. 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 ];
  42752. const geometry = new BufferGeometry();
  42753. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42754. geometry.computeBoundingSphere();
  42755. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42756. this.type = 'PlaneHelper';
  42757. /**
  42758. * The plane being visualized.
  42759. *
  42760. * @type {Plane}
  42761. */
  42762. this.plane = plane;
  42763. /**
  42764. * The side length of plane helper.
  42765. *
  42766. * @type {number}
  42767. * @default 1
  42768. */
  42769. this.size = size;
  42770. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42771. const geometry2 = new BufferGeometry();
  42772. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42773. geometry2.computeBoundingSphere();
  42774. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42775. }
  42776. updateMatrixWorld( force ) {
  42777. this.position.set( 0, 0, 0 );
  42778. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42779. this.lookAt( this.plane.normal );
  42780. this.translateZ( - this.plane.constant );
  42781. super.updateMatrixWorld( force );
  42782. }
  42783. /**
  42784. * Updates the helper to match the position and direction of the
  42785. * light being visualized.
  42786. */
  42787. dispose() {
  42788. this.geometry.dispose();
  42789. this.material.dispose();
  42790. this.children[ 0 ].geometry.dispose();
  42791. this.children[ 0 ].material.dispose();
  42792. }
  42793. }
  42794. const _axis = /*@__PURE__*/ new Vector3();
  42795. let _lineGeometry, _coneGeometry;
  42796. /**
  42797. * An 3D arrow object for visualizing directions.
  42798. *
  42799. * ```js
  42800. * const dir = new THREE.Vector3( 1, 2, 0 );
  42801. *
  42802. * //normalize the direction vector (convert to vector of length 1)
  42803. * dir.normalize();
  42804. *
  42805. * const origin = new THREE.Vector3( 0, 0, 0 );
  42806. * const length = 1;
  42807. * const hex = 0xffff00;
  42808. *
  42809. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42810. * scene.add( arrowHelper );
  42811. * ```
  42812. *
  42813. * @augments Object3D
  42814. */
  42815. class ArrowHelper extends Object3D {
  42816. /**
  42817. * Constructs a new arrow helper.
  42818. *
  42819. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42820. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42821. * @param {number} [length=1] - Length of the arrow in world units.
  42822. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42823. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42824. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42825. */
  42826. 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 ) {
  42827. super();
  42828. this.type = 'ArrowHelper';
  42829. if ( _lineGeometry === undefined ) {
  42830. _lineGeometry = new BufferGeometry();
  42831. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42832. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42833. _coneGeometry.translate( 0, -0.5, 0 );
  42834. }
  42835. this.position.copy( origin );
  42836. /**
  42837. * The line part of the arrow helper.
  42838. *
  42839. * @type {Line}
  42840. */
  42841. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42842. this.line.matrixAutoUpdate = false;
  42843. this.add( this.line );
  42844. /**
  42845. * The cone part of the arrow helper.
  42846. *
  42847. * @type {Mesh}
  42848. */
  42849. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42850. this.cone.matrixAutoUpdate = false;
  42851. this.add( this.cone );
  42852. this.setDirection( dir );
  42853. this.setLength( length, headLength, headWidth );
  42854. }
  42855. /**
  42856. * Sets the direction of the helper.
  42857. *
  42858. * @param {Vector3} dir - The normalized direction vector.
  42859. */
  42860. setDirection( dir ) {
  42861. // dir is assumed to be normalized
  42862. if ( dir.y > 0.99999 ) {
  42863. this.quaternion.set( 0, 0, 0, 1 );
  42864. } else if ( dir.y < -0.99999 ) {
  42865. this.quaternion.set( 1, 0, 0, 0 );
  42866. } else {
  42867. _axis.set( dir.z, 0, - dir.x ).normalize();
  42868. const radians = Math.acos( dir.y );
  42869. this.quaternion.setFromAxisAngle( _axis, radians );
  42870. }
  42871. }
  42872. /**
  42873. * Sets the length of the helper.
  42874. *
  42875. * @param {number} length - Length of the arrow in world units.
  42876. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42877. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42878. */
  42879. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42880. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42881. this.line.updateMatrix();
  42882. this.cone.scale.set( headWidth, headLength, headWidth );
  42883. this.cone.position.y = length;
  42884. this.cone.updateMatrix();
  42885. }
  42886. /**
  42887. * Sets the color of the helper.
  42888. *
  42889. * @param {number|Color|string} color - The color to set.
  42890. */
  42891. setColor( color ) {
  42892. this.line.material.color.set( color );
  42893. this.cone.material.color.set( color );
  42894. }
  42895. copy( source ) {
  42896. super.copy( source, false );
  42897. this.line.copy( source.line );
  42898. this.cone.copy( source.cone );
  42899. return this;
  42900. }
  42901. /**
  42902. * Frees the GPU-related resources allocated by this instance. Call this
  42903. * method whenever this instance is no longer used in your app.
  42904. */
  42905. dispose() {
  42906. this.line.geometry.dispose();
  42907. this.line.material.dispose();
  42908. this.cone.geometry.dispose();
  42909. this.cone.material.dispose();
  42910. }
  42911. }
  42912. /**
  42913. * An axis object to visualize the 3 axes in a simple way.
  42914. * The X axis is red. The Y axis is green. The Z axis is blue.
  42915. *
  42916. * ```js
  42917. * const axesHelper = new THREE.AxesHelper( 5 );
  42918. * scene.add( axesHelper );
  42919. * ```
  42920. *
  42921. * @augments LineSegments
  42922. */
  42923. class AxesHelper extends LineSegments {
  42924. /**
  42925. * Constructs a new axes helper.
  42926. *
  42927. * @param {number} [size=1] - Size of the lines representing the axes.
  42928. */
  42929. constructor( size = 1 ) {
  42930. const vertices = [
  42931. 0, 0, 0, size, 0, 0,
  42932. 0, 0, 0, 0, size, 0,
  42933. 0, 0, 0, 0, 0, size
  42934. ];
  42935. const colors = [
  42936. 1, 0, 0, 1, 0.6, 0,
  42937. 0, 1, 0, 0.6, 1, 0,
  42938. 0, 0, 1, 0, 0.6, 1
  42939. ];
  42940. const geometry = new BufferGeometry();
  42941. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42942. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42943. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42944. super( geometry, material );
  42945. this.type = 'AxesHelper';
  42946. }
  42947. /**
  42948. * Defines the colors of the axes helper.
  42949. *
  42950. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42951. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42952. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42953. * @return {AxesHelper} A reference to this axes helper.
  42954. */
  42955. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42956. const color = new Color();
  42957. const array = this.geometry.attributes.color.array;
  42958. color.set( xAxisColor );
  42959. color.toArray( array, 0 );
  42960. color.toArray( array, 3 );
  42961. color.set( yAxisColor );
  42962. color.toArray( array, 6 );
  42963. color.toArray( array, 9 );
  42964. color.set( zAxisColor );
  42965. color.toArray( array, 12 );
  42966. color.toArray( array, 15 );
  42967. this.geometry.attributes.color.needsUpdate = true;
  42968. return this;
  42969. }
  42970. /**
  42971. * Frees the GPU-related resources allocated by this instance. Call this
  42972. * method whenever this instance is no longer used in your app.
  42973. */
  42974. dispose() {
  42975. this.geometry.dispose();
  42976. this.material.dispose();
  42977. }
  42978. }
  42979. /**
  42980. * This class is used to convert a series of paths to an array of
  42981. * shapes. It is specifically used in context of fonts and SVG.
  42982. */
  42983. class ShapePath {
  42984. /**
  42985. * Constructs a new shape path.
  42986. */
  42987. constructor() {
  42988. this.type = 'ShapePath';
  42989. /**
  42990. * The color of the shape.
  42991. *
  42992. * @type {Color}
  42993. */
  42994. this.color = new Color();
  42995. /**
  42996. * The paths that have been generated for this shape.
  42997. *
  42998. * @type {Array<Path>}
  42999. * @default null
  43000. */
  43001. this.subPaths = [];
  43002. /**
  43003. * The current path that is being generated.
  43004. *
  43005. * @type {?Path}
  43006. * @default null
  43007. */
  43008. this.currentPath = null;
  43009. /**
  43010. * An object that can be used to store custom data about the shape path.
  43011. * Mainly used by SVGLoader to store style information.
  43012. *
  43013. * @type {Object}
  43014. */
  43015. this.userData = {};
  43016. }
  43017. /**
  43018. * Creates a new path and moves it current point to the given one.
  43019. *
  43020. * @param {number} x - The x coordinate.
  43021. * @param {number} y - The y coordinate.
  43022. * @return {ShapePath} A reference to this shape path.
  43023. */
  43024. moveTo( x, y ) {
  43025. this.currentPath = new Path();
  43026. this.subPaths.push( this.currentPath );
  43027. this.currentPath.moveTo( x, y );
  43028. return this;
  43029. }
  43030. /**
  43031. * Adds an instance of {@link LineCurve} to the path by connecting
  43032. * the current point with the given one.
  43033. *
  43034. * @param {number} x - The x coordinate of the end point.
  43035. * @param {number} y - The y coordinate of the end point.
  43036. * @return {ShapePath} A reference to this shape path.
  43037. */
  43038. lineTo( x, y ) {
  43039. this.currentPath.lineTo( x, y );
  43040. return this;
  43041. }
  43042. /**
  43043. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  43044. * the current point with the given one.
  43045. *
  43046. * @param {number} aCPx - The x coordinate of the control point.
  43047. * @param {number} aCPy - The y coordinate of the control point.
  43048. * @param {number} aX - The x coordinate of the end point.
  43049. * @param {number} aY - The y coordinate of the end point.
  43050. * @return {ShapePath} A reference to this shape path.
  43051. */
  43052. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  43053. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  43054. return this;
  43055. }
  43056. /**
  43057. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  43058. * the current point with the given one.
  43059. *
  43060. * @param {number} aCP1x - The x coordinate of the first control point.
  43061. * @param {number} aCP1y - The y coordinate of the first control point.
  43062. * @param {number} aCP2x - The x coordinate of the second control point.
  43063. * @param {number} aCP2y - The y coordinate of the second control point.
  43064. * @param {number} aX - The x coordinate of the end point.
  43065. * @param {number} aY - The y coordinate of the end point.
  43066. * @return {ShapePath} A reference to this shape path.
  43067. */
  43068. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  43069. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  43070. return this;
  43071. }
  43072. /**
  43073. * Adds an instance of {@link SplineCurve} to the path by connecting
  43074. * the current point with the given list of points.
  43075. *
  43076. * @param {Array<Vector2>} pts - An array of points in 2D space.
  43077. * @return {ShapePath} A reference to this shape path.
  43078. */
  43079. splineThru( pts ) {
  43080. this.currentPath.splineThru( pts );
  43081. return this;
  43082. }
  43083. /**
  43084. * Converts the paths into an array of shapes.
  43085. *
  43086. * @return {Array<Shape>} An array of shapes.
  43087. */
  43088. toShapes() {
  43089. // Point-in-polygon test using the even-odd ray-casting rule. Valid for
  43090. // simple (non self-intersecting) polygons.
  43091. function pointInPolygon( p, polygon ) {
  43092. let inside = false;
  43093. const n = polygon.length;
  43094. for ( let i = 0, j = n - 1; i < n; j = i ++ ) {
  43095. const a = polygon[ i ];
  43096. const b = polygon[ j ];
  43097. if ( ( a.y > p.y ) !== ( b.y > p.y ) &&
  43098. p.x < ( b.x - a.x ) * ( p.y - a.y ) / ( b.y - a.y ) + a.x ) {
  43099. inside = ! inside;
  43100. }
  43101. }
  43102. return inside;
  43103. }
  43104. // Returns a point guaranteed to be strictly inside the given simple
  43105. // polygon. First tries the bounding-box center; if that falls outside
  43106. // the polygon, casts a horizontal ray at the center's y and picks the
  43107. // midpoint between the first two sorted intercepts.
  43108. //
  43109. // Port of paper.js' Path#getInteriorPoint()
  43110. // https://github.com/paperjs/paper.js/blob/develop/src/path/PathItem.Boolean.js
  43111. function getInteriorPoint( polygon, boundingBox ) {
  43112. const point = boundingBox.getCenter( new Vector2() );
  43113. if ( pointInPolygon( point, polygon ) ) return point;
  43114. const y = point.y;
  43115. const intercepts = [];
  43116. const n = polygon.length;
  43117. for ( let i = 0; i < n; i ++ ) {
  43118. const a = polygon[ i ];
  43119. const b = polygon[ ( i + 1 ) % n ];
  43120. // Half-open crossing rule — counts each vertex exactly once and
  43121. // skips horizontal edges.
  43122. if ( ( a.y > y ) !== ( b.y > y ) ) {
  43123. const x = a.x + ( y - a.y ) * ( b.x - a.x ) / ( b.y - a.y );
  43124. intercepts.push( x );
  43125. }
  43126. }
  43127. if ( intercepts.length > 1 ) {
  43128. intercepts.sort( ( a, b ) => a - b );
  43129. point.x = ( intercepts[ 0 ] + intercepts[ 1 ] ) / 2;
  43130. }
  43131. return point;
  43132. }
  43133. // Resolve fill-rule. Defaults to 'nonzero'.
  43134. let fillRule = ( this.userData.style && this.userData.style.fillRule ) || 'nonzero';
  43135. if ( fillRule !== 'nonzero' && fillRule !== 'evenodd' ) {
  43136. warn( 'Fill-rule "' + fillRule + '" is not supported, falling back to "nonzero".' );
  43137. fillRule = 'nonzero';
  43138. }
  43139. // Predicate that decides whether a winding number falls inside the fill
  43140. // region, per the SVG fill-rule spec. Works for negative windings too,
  43141. // because JavaScript's bitwise AND preserves odd/even under two's
  43142. // complement.
  43143. const isInside = fillRule === 'nonzero'
  43144. ? ( w => w !== 0 )
  43145. : ( w => ( w & 1 ) !== 0 );
  43146. // Build an entry per usable subpath. Self-winding follows the standard
  43147. // convention used by ShapeUtils: counter-clockwise (signed area > 0)
  43148. // contributes +1 to the winding number at an interior point,
  43149. // clockwise contributes -1.
  43150. const entries = [];
  43151. for ( const subPath of this.subPaths ) {
  43152. const points = subPath.getPoints();
  43153. if ( points.length < 3 ) continue;
  43154. const area = ShapeUtils.area( points );
  43155. if ( area === 0 ) continue;
  43156. const boundingBox = new Box2();
  43157. for ( let i = 0; i < points.length; i ++ ) boundingBox.expandByPoint( points[ i ] );
  43158. entries.push( {
  43159. subPath: subPath,
  43160. points: points,
  43161. boundingBox: boundingBox,
  43162. interiorPoint: getInteriorPoint( points, boundingBox ),
  43163. absArea: Math.abs( area ),
  43164. winding: area < 0 ? -1 : 1,
  43165. container: null,
  43166. exclude: false,
  43167. role: null
  43168. } );
  43169. }
  43170. // Sort by area descending. This guarantees that any subpath that could
  43171. // contain `entries[i]` is located at a smaller index and has already
  43172. // been processed when it's entries[i]'s turn. Port of paper.js'
  43173. // reorientPaths() algorithm.
  43174. entries.sort( ( a, b ) => b.absArea - a.absArea );
  43175. // Walk already-processed entries from closest-in-size to largest,
  43176. // stopping at the innermost container. Accumulate the container's
  43177. // cumulative winding into this entry's winding so that the final value
  43178. // equals the winding number at this entry's interior point.
  43179. //
  43180. // A subpath only contributes to the fill boundary when crossing it
  43181. // actually flips the "insideness" per the fill rule; otherwise it's a
  43182. // redundant overlap and gets excluded to avoid double-counting.
  43183. for ( let i = 0; i < entries.length; i ++ ) {
  43184. const entry = entries[ i ];
  43185. let containerWinding = 0;
  43186. for ( let j = i - 1; j >= 0; j -- ) {
  43187. const candidate = entries[ j ];
  43188. if ( ! candidate.boundingBox.containsPoint( entry.interiorPoint ) ) continue;
  43189. if ( ! pointInPolygon( entry.interiorPoint, candidate.points ) ) continue;
  43190. entry.container = candidate.exclude ? candidate.container : candidate;
  43191. containerWinding = candidate.winding;
  43192. entry.winding += containerWinding;
  43193. break;
  43194. }
  43195. if ( isInside( entry.winding ) === isInside( containerWinding ) ) {
  43196. entry.exclude = true;
  43197. }
  43198. }
  43199. // Classify retained entries. An entry is an outer shape if it has no
  43200. // container or if its container is itself a hole (a solid nested inside
  43201. // a hole becomes a new top-level shape); otherwise it's a hole in its
  43202. // container. Entries were already sorted outermost-first, so each
  43203. // container's role is known by the time we look at it.
  43204. for ( const entry of entries ) {
  43205. if ( entry.exclude ) continue;
  43206. entry.role = ( entry.container === null || entry.container.role === 'hole' ) ? 'outer' : 'hole';
  43207. }
  43208. // Build Shapes for outers first, then attach holes to their container's
  43209. // Shape.
  43210. const shapes = [];
  43211. const shapeByEntry = new Map();
  43212. for ( const entry of entries ) {
  43213. if ( entry.exclude || entry.role !== 'outer' ) continue;
  43214. const shape = new Shape();
  43215. shape.curves = entry.subPath.curves;
  43216. shapes.push( shape );
  43217. shapeByEntry.set( entry, shape );
  43218. }
  43219. for ( const entry of entries ) {
  43220. if ( entry.exclude || entry.role !== 'hole' ) continue;
  43221. const shape = shapeByEntry.get( entry.container );
  43222. if ( ! shape ) continue;
  43223. const hole = new Path();
  43224. hole.curves = entry.subPath.curves;
  43225. shape.holes.push( hole );
  43226. }
  43227. return shapes;
  43228. }
  43229. }
  43230. /**
  43231. * Abstract base class for controls.
  43232. *
  43233. * @abstract
  43234. * @augments EventDispatcher
  43235. */
  43236. class Controls extends EventDispatcher {
  43237. /**
  43238. * Constructs a new controls instance.
  43239. *
  43240. * @param {Object3D} object - The object that is managed by the controls.
  43241. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  43242. */
  43243. constructor( object, domElement = null ) {
  43244. super();
  43245. /**
  43246. * The object that is managed by the controls.
  43247. *
  43248. * @type {Object3D}
  43249. */
  43250. this.object = object;
  43251. /**
  43252. * The HTML element used for event listeners.
  43253. *
  43254. * @type {?HTMLElement}
  43255. * @default null
  43256. */
  43257. this.domElement = domElement;
  43258. /**
  43259. * Whether the controls responds to user input or not.
  43260. *
  43261. * @type {boolean}
  43262. * @default true
  43263. */
  43264. this.enabled = true;
  43265. /**
  43266. * The internal state of the controls.
  43267. *
  43268. * @type {number}
  43269. * @default -1
  43270. */
  43271. this.state = -1;
  43272. /**
  43273. * This object defines the keyboard input of the controls.
  43274. *
  43275. * @type {Object}
  43276. */
  43277. this.keys = {};
  43278. /**
  43279. * This object defines what type of actions are assigned to the available mouse buttons.
  43280. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  43281. *
  43282. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  43283. */
  43284. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  43285. /**
  43286. * This object defines what type of actions are assigned to what kind of touch interaction.
  43287. * It depends on the control implementation what kind of touch interaction and actions are supported.
  43288. *
  43289. * @type {{ONE: ?number, TWO: ?number}}
  43290. */
  43291. this.touches = { ONE: null, TWO: null };
  43292. }
  43293. /**
  43294. * Connects the controls to the DOM. This method has so called "side effects" since
  43295. * it adds the module's event listeners to the DOM.
  43296. *
  43297. * @param {HTMLElement} element - The DOM element to connect to.
  43298. */
  43299. connect( element ) {
  43300. if ( element === undefined ) {
  43301. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  43302. return;
  43303. }
  43304. if ( this.domElement !== null ) this.disconnect();
  43305. this.domElement = element;
  43306. }
  43307. /**
  43308. * Disconnects the controls from the DOM.
  43309. */
  43310. disconnect() {}
  43311. /**
  43312. * Call this method if you no longer want use to the controls. It frees all internal
  43313. * resources and removes all event listeners.
  43314. */
  43315. dispose() {}
  43316. /**
  43317. * Controls should implement this method if they have to update their internal state
  43318. * per simulation step.
  43319. *
  43320. * @param {number} [delta] - The time delta in seconds.
  43321. */
  43322. update( /* delta */ ) {}
  43323. }
  43324. /**
  43325. * Scales the texture as large as possible within its surface without cropping
  43326. * or stretching the texture. The method preserves the original aspect ratio of
  43327. * the texture. Akin to CSS `object-fit: contain`
  43328. *
  43329. * @param {Texture} texture - The texture.
  43330. * @param {number} aspect - The texture's aspect ratio.
  43331. * @return {Texture} The updated texture.
  43332. */
  43333. function contain( texture, aspect ) {
  43334. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43335. if ( imageAspect > aspect ) {
  43336. texture.repeat.x = 1;
  43337. texture.repeat.y = imageAspect / aspect;
  43338. texture.offset.x = 0;
  43339. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43340. } else {
  43341. texture.repeat.x = aspect / imageAspect;
  43342. texture.repeat.y = 1;
  43343. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43344. texture.offset.y = 0;
  43345. }
  43346. return texture;
  43347. }
  43348. /**
  43349. * Scales the texture to the smallest possible size to fill the surface, leaving
  43350. * no empty space. The method preserves the original aspect ratio of the texture.
  43351. * Akin to CSS `object-fit: cover`.
  43352. *
  43353. * @param {Texture} texture - The texture.
  43354. * @param {number} aspect - The texture's aspect ratio.
  43355. * @return {Texture} The updated texture.
  43356. */
  43357. function cover( texture, aspect ) {
  43358. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  43359. if ( imageAspect > aspect ) {
  43360. texture.repeat.x = aspect / imageAspect;
  43361. texture.repeat.y = 1;
  43362. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  43363. texture.offset.y = 0;
  43364. } else {
  43365. texture.repeat.x = 1;
  43366. texture.repeat.y = imageAspect / aspect;
  43367. texture.offset.x = 0;
  43368. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  43369. }
  43370. return texture;
  43371. }
  43372. /**
  43373. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43374. *
  43375. * @param {Texture} texture - The texture.
  43376. * @return {Texture} The updated texture.
  43377. */
  43378. function fill( texture ) {
  43379. texture.repeat.x = 1;
  43380. texture.repeat.y = 1;
  43381. texture.offset.x = 0;
  43382. texture.offset.y = 0;
  43383. return texture;
  43384. }
  43385. /**
  43386. * Determines how many bytes must be used to represent the texture.
  43387. *
  43388. * @param {number} width - The width of the texture.
  43389. * @param {number} height - The height of the texture.
  43390. * @param {number} format - The texture's format.
  43391. * @param {number} type - The texture's type.
  43392. * @return {number} The byte length.
  43393. */
  43394. function getByteLength( width, height, format, type ) {
  43395. const typeByteLength = getTextureTypeByteLength( type );
  43396. switch ( format ) {
  43397. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  43398. case AlphaFormat:
  43399. return width * height;
  43400. case RedFormat:
  43401. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43402. case RedIntegerFormat:
  43403. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  43404. case RGFormat:
  43405. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43406. case RGIntegerFormat:
  43407. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43408. case RGBFormat:
  43409. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43410. case RGBAFormat:
  43411. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43412. case RGBAIntegerFormat:
  43413. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  43414. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  43415. case RGB_S3TC_DXT1_Format:
  43416. case RGBA_S3TC_DXT1_Format:
  43417. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43418. case RGBA_S3TC_DXT3_Format:
  43419. case RGBA_S3TC_DXT5_Format:
  43420. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43421. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  43422. case RGB_PVRTC_2BPPV1_Format:
  43423. case RGBA_PVRTC_2BPPV1_Format:
  43424. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  43425. case RGB_PVRTC_4BPPV1_Format:
  43426. case RGBA_PVRTC_4BPPV1_Format:
  43427. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  43428. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  43429. case RGB_ETC1_Format:
  43430. case RGB_ETC2_Format:
  43431. case R11_EAC_Format:
  43432. case SIGNED_R11_EAC_Format:
  43433. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  43434. case RGBA_ETC2_EAC_Format:
  43435. case RG11_EAC_Format:
  43436. case SIGNED_RG11_EAC_Format:
  43437. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43438. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  43439. case RGBA_ASTC_4x4_Format:
  43440. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43441. case RGBA_ASTC_5x4_Format:
  43442. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  43443. case RGBA_ASTC_5x5_Format:
  43444. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43445. case RGBA_ASTC_6x5_Format:
  43446. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43447. case RGBA_ASTC_6x6_Format:
  43448. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43449. case RGBA_ASTC_8x5_Format:
  43450. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43451. case RGBA_ASTC_8x6_Format:
  43452. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43453. case RGBA_ASTC_8x8_Format:
  43454. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43455. case RGBA_ASTC_10x5_Format:
  43456. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  43457. case RGBA_ASTC_10x6_Format:
  43458. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  43459. case RGBA_ASTC_10x8_Format:
  43460. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  43461. case RGBA_ASTC_10x10_Format:
  43462. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43463. case RGBA_ASTC_12x10_Format:
  43464. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  43465. case RGBA_ASTC_12x12_Format:
  43466. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  43467. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  43468. case RGBA_BPTC_Format:
  43469. case RGB_BPTC_SIGNED_Format:
  43470. case RGB_BPTC_UNSIGNED_Format:
  43471. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43472. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  43473. case RED_RGTC1_Format:
  43474. case SIGNED_RED_RGTC1_Format:
  43475. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  43476. case RED_GREEN_RGTC2_Format:
  43477. case SIGNED_RED_GREEN_RGTC2_Format:
  43478. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  43479. }
  43480. throw new Error(
  43481. `Unable to determine texture byte length for ${format} format.`,
  43482. );
  43483. }
  43484. function getTextureTypeByteLength( type ) {
  43485. switch ( type ) {
  43486. case UnsignedByteType:
  43487. case ByteType:
  43488. return { byteLength: 1, components: 1 };
  43489. case UnsignedShortType:
  43490. case ShortType:
  43491. case HalfFloatType:
  43492. return { byteLength: 2, components: 1 };
  43493. case UnsignedShort4444Type:
  43494. case UnsignedShort5551Type:
  43495. return { byteLength: 2, components: 4 };
  43496. case UnsignedIntType:
  43497. case IntType:
  43498. case FloatType:
  43499. return { byteLength: 4, components: 1 };
  43500. case UnsignedInt5999Type:
  43501. case UnsignedInt101111Type:
  43502. return { byteLength: 4, components: 3 };
  43503. }
  43504. throw new Error( `THREE.TextureUtils: Unknown texture type ${type}.` );
  43505. }
  43506. /**
  43507. * A class containing utility functions for textures.
  43508. *
  43509. * @hideconstructor
  43510. */
  43511. class TextureUtils {
  43512. /**
  43513. * Scales the texture as large as possible within its surface without cropping
  43514. * or stretching the texture. The method preserves the original aspect ratio of
  43515. * the texture. Akin to CSS `object-fit: contain`
  43516. *
  43517. * @param {Texture} texture - The texture.
  43518. * @param {number} aspect - The texture's aspect ratio.
  43519. * @return {Texture} The updated texture.
  43520. */
  43521. static contain( texture, aspect ) {
  43522. return contain( texture, aspect );
  43523. }
  43524. /**
  43525. * Scales the texture to the smallest possible size to fill the surface, leaving
  43526. * no empty space. The method preserves the original aspect ratio of the texture.
  43527. * Akin to CSS `object-fit: cover`.
  43528. *
  43529. * @param {Texture} texture - The texture.
  43530. * @param {number} aspect - The texture's aspect ratio.
  43531. * @return {Texture} The updated texture.
  43532. */
  43533. static cover( texture, aspect ) {
  43534. return cover( texture, aspect );
  43535. }
  43536. /**
  43537. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  43538. *
  43539. * @param {Texture} texture - The texture.
  43540. * @return {Texture} The updated texture.
  43541. */
  43542. static fill( texture ) {
  43543. return fill( texture );
  43544. }
  43545. /**
  43546. * Determines how many bytes must be used to represent the texture.
  43547. *
  43548. * @param {number} width - The width of the texture.
  43549. * @param {number} height - The height of the texture.
  43550. * @param {number} format - The texture's format.
  43551. * @param {number} type - The texture's type.
  43552. * @return {number} The byte length.
  43553. */
  43554. static getByteLength( width, height, format, type ) {
  43555. return getByteLength( width, height, format, type );
  43556. }
  43557. }
  43558. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  43559. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  43560. revision: REVISION,
  43561. } } ) );
  43562. }
  43563. if ( typeof window !== 'undefined' ) {
  43564. if ( window.__THREE__ ) {
  43565. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  43566. } else {
  43567. window.__THREE__ = REVISION;
  43568. }
  43569. }
  43570. 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, HTMLTexture, 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号