three.core.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '179dev';
  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. * A `source + destination` blending equation.
  145. *
  146. * @type {number}
  147. * @constant
  148. */
  149. const AddEquation = 100;
  150. /**
  151. * A `source - destination` blending equation.
  152. *
  153. * @type {number}
  154. * @constant
  155. */
  156. const SubtractEquation = 101;
  157. /**
  158. * A `destination - source` blending equation.
  159. *
  160. * @type {number}
  161. * @constant
  162. */
  163. const ReverseSubtractEquation = 102;
  164. /**
  165. * A blend equation that uses the minimum of source and destination.
  166. *
  167. * @type {number}
  168. * @constant
  169. */
  170. const MinEquation = 103;
  171. /**
  172. * A blend equation that uses the maximum of source and destination.
  173. *
  174. * @type {number}
  175. * @constant
  176. */
  177. const MaxEquation = 104;
  178. /**
  179. * Multiplies all colors by `0`.
  180. *
  181. * @type {number}
  182. * @constant
  183. */
  184. const ZeroFactor = 200;
  185. /**
  186. * Multiplies all colors by `1`.
  187. *
  188. * @type {number}
  189. * @constant
  190. */
  191. const OneFactor = 201;
  192. /**
  193. * Multiplies all colors by the source colors.
  194. *
  195. * @type {number}
  196. * @constant
  197. */
  198. const SrcColorFactor = 202;
  199. /**
  200. * Multiplies all colors by `1` minus each source color.
  201. *
  202. * @type {number}
  203. * @constant
  204. */
  205. const OneMinusSrcColorFactor = 203;
  206. /**
  207. * Multiplies all colors by the source alpha value.
  208. *
  209. * @type {number}
  210. * @constant
  211. */
  212. const SrcAlphaFactor = 204;
  213. /**
  214. * Multiplies all colors by 1 minus the source alpha value.
  215. *
  216. * @type {number}
  217. * @constant
  218. */
  219. const OneMinusSrcAlphaFactor = 205;
  220. /**
  221. * Multiplies all colors by the destination alpha value.
  222. *
  223. * @type {number}
  224. * @constant
  225. */
  226. const DstAlphaFactor = 206;
  227. /**
  228. * Multiplies all colors by `1` minus the destination alpha value.
  229. *
  230. * @type {number}
  231. * @constant
  232. */
  233. const OneMinusDstAlphaFactor = 207;
  234. /**
  235. * Multiplies all colors by the destination color.
  236. *
  237. * @type {number}
  238. * @constant
  239. */
  240. const DstColorFactor = 208;
  241. /**
  242. * Multiplies all colors by `1` minus each destination color.
  243. *
  244. * @type {number}
  245. * @constant
  246. */
  247. const OneMinusDstColorFactor = 209;
  248. /**
  249. * Multiplies the RGB colors by the smaller of either the source alpha
  250. * value or the value of `1` minus the destination alpha value. The alpha
  251. * value is multiplied by `1`.
  252. *
  253. * @type {number}
  254. * @constant
  255. */
  256. const SrcAlphaSaturateFactor = 210;
  257. /**
  258. * Multiplies all colors by a constant color.
  259. *
  260. * @type {number}
  261. * @constant
  262. */
  263. const ConstantColorFactor = 211;
  264. /**
  265. * Multiplies all colors by `1` minus a constant color.
  266. *
  267. * @type {number}
  268. * @constant
  269. */
  270. const OneMinusConstantColorFactor = 212;
  271. /**
  272. * Multiplies all colors by a constant alpha value.
  273. *
  274. * @type {number}
  275. * @constant
  276. */
  277. const ConstantAlphaFactor = 213;
  278. /**
  279. * Multiplies all colors by 1 minus a constant alpha value.
  280. *
  281. * @type {number}
  282. * @constant
  283. */
  284. const OneMinusConstantAlphaFactor = 214;
  285. /**
  286. * Never pass.
  287. *
  288. * @type {number}
  289. * @constant
  290. */
  291. const NeverDepth = 0;
  292. /**
  293. * Always pass.
  294. *
  295. * @type {number}
  296. * @constant
  297. */
  298. const AlwaysDepth = 1;
  299. /**
  300. * Pass if the incoming value is less than the depth buffer value.
  301. *
  302. * @type {number}
  303. * @constant
  304. */
  305. const LessDepth = 2;
  306. /**
  307. * Pass if the incoming value is less than or equal to the depth buffer value.
  308. *
  309. * @type {number}
  310. * @constant
  311. */
  312. const LessEqualDepth = 3;
  313. /**
  314. * Pass if the incoming value equals the depth buffer value.
  315. *
  316. * @type {number}
  317. * @constant
  318. */
  319. const EqualDepth = 4;
  320. /**
  321. * Pass if the incoming value is greater than or equal to the depth buffer value.
  322. *
  323. * @type {number}
  324. * @constant
  325. */
  326. const GreaterEqualDepth = 5;
  327. /**
  328. * Pass if the incoming value is greater than the depth buffer value.
  329. *
  330. * @type {number}
  331. * @constant
  332. */
  333. const GreaterDepth = 6;
  334. /**
  335. * Pass if the incoming value is not equal to the depth buffer value.
  336. *
  337. * @type {number}
  338. * @constant
  339. */
  340. const NotEqualDepth = 7;
  341. /**
  342. * Multiplies the environment map color with the surface color.
  343. *
  344. * @type {number}
  345. * @constant
  346. */
  347. const MultiplyOperation = 0;
  348. /**
  349. * Uses reflectivity to blend between the two colors.
  350. *
  351. * @type {number}
  352. * @constant
  353. */
  354. const MixOperation = 1;
  355. /**
  356. * Adds the two colors.
  357. *
  358. * @type {number}
  359. * @constant
  360. */
  361. const AddOperation = 2;
  362. /**
  363. * No tone mapping is applied.
  364. *
  365. * @type {number}
  366. * @constant
  367. */
  368. const NoToneMapping = 0;
  369. /**
  370. * Linear tone mapping.
  371. *
  372. * @type {number}
  373. * @constant
  374. */
  375. const LinearToneMapping = 1;
  376. /**
  377. * Reinhard tone mapping.
  378. *
  379. * @type {number}
  380. * @constant
  381. */
  382. const ReinhardToneMapping = 2;
  383. /**
  384. * Cineon tone mapping.
  385. *
  386. * @type {number}
  387. * @constant
  388. */
  389. const CineonToneMapping = 3;
  390. /**
  391. * ACES Filmic tone mapping.
  392. *
  393. * @type {number}
  394. * @constant
  395. */
  396. const ACESFilmicToneMapping = 4;
  397. /**
  398. * Custom tone mapping.
  399. *
  400. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  401. *
  402. * @type {number}
  403. * @constant
  404. */
  405. const CustomToneMapping = 5;
  406. /**
  407. * AgX tone mapping.
  408. *
  409. * @type {number}
  410. * @constant
  411. */
  412. const AgXToneMapping = 6;
  413. /**
  414. * Neutral tone mapping.
  415. *
  416. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  417. *
  418. * @type {number}
  419. * @constant
  420. */
  421. const NeutralToneMapping = 7;
  422. /**
  423. * The skinned mesh shares the same world space as the skeleton.
  424. *
  425. * @type {string}
  426. * @constant
  427. */
  428. const AttachedBindMode = 'attached';
  429. /**
  430. * The skinned mesh does not share the same world space as the skeleton.
  431. * This is useful when a skeleton is shared across multiple skinned meshes.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const DetachedBindMode = 'detached';
  437. /**
  438. * Maps textures using the geometry's UV coordinates.
  439. *
  440. * @type {number}
  441. * @constant
  442. */
  443. const UVMapping = 300;
  444. /**
  445. * Reflection mapping for cube textures.
  446. *
  447. * @type {number}
  448. * @constant
  449. */
  450. const CubeReflectionMapping = 301;
  451. /**
  452. * Refraction mapping for cube textures.
  453. *
  454. * @type {number}
  455. * @constant
  456. */
  457. const CubeRefractionMapping = 302;
  458. /**
  459. * Reflection mapping for equirectangular textures.
  460. *
  461. * @type {number}
  462. * @constant
  463. */
  464. const EquirectangularReflectionMapping = 303;
  465. /**
  466. * Refraction mapping for equirectangular textures.
  467. *
  468. * @type {number}
  469. * @constant
  470. */
  471. const EquirectangularRefractionMapping = 304;
  472. /**
  473. * Reflection mapping for PMREM textures.
  474. *
  475. * @type {number}
  476. * @constant
  477. */
  478. const CubeUVReflectionMapping = 306;
  479. /**
  480. * The texture will simply repeat to infinity.
  481. *
  482. * @type {number}
  483. * @constant
  484. */
  485. const RepeatWrapping = 1000;
  486. /**
  487. * The last pixel of the texture stretches to the edge of the mesh.
  488. *
  489. * @type {number}
  490. * @constant
  491. */
  492. const ClampToEdgeWrapping = 1001;
  493. /**
  494. * The texture will repeats to infinity, mirroring on each repeat.
  495. *
  496. * @type {number}
  497. * @constant
  498. */
  499. const MirroredRepeatWrapping = 1002;
  500. /**
  501. * Returns the value of the texture element that is nearest (in Manhattan distance)
  502. * to the specified texture coordinates.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const NearestFilter = 1003;
  508. /**
  509. * Chooses the mipmap that most closely matches the size of the pixel being textured
  510. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  511. * to produce a texture value.
  512. *
  513. * @type {number}
  514. * @constant
  515. */
  516. const NearestMipmapNearestFilter = 1004;
  517. const NearestMipMapNearestFilter = 1004; // legacy
  518. /**
  519. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  520. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  521. * The final texture value is a weighted average of those two values.
  522. *
  523. * @type {number}
  524. * @constant
  525. */
  526. const NearestMipmapLinearFilter = 1005;
  527. const NearestMipMapLinearFilter = 1005; // legacy
  528. /**
  529. * Returns the weighted average of the four texture elements that are closest to the specified
  530. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  531. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  532. *
  533. * @type {number}
  534. * @constant
  535. */
  536. const LinearFilter = 1006;
  537. /**
  538. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  539. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  540. * center of the pixel) to produce a texture value.
  541. *
  542. * @type {number}
  543. * @constant
  544. */
  545. const LinearMipmapNearestFilter = 1007;
  546. const LinearMipMapNearestFilter = 1007; // legacy
  547. /**
  548. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  549. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  550. * is a weighted average of those two values.
  551. *
  552. * @type {number}
  553. * @constant
  554. */
  555. const LinearMipmapLinearFilter = 1008;
  556. const LinearMipMapLinearFilter = 1008; // legacy
  557. /**
  558. * An unsigned byte data type for textures.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const UnsignedByteType = 1009;
  564. /**
  565. * A byte data type for textures.
  566. *
  567. * @type {number}
  568. * @constant
  569. */
  570. const ByteType = 1010;
  571. /**
  572. * A short data type for textures.
  573. *
  574. * @type {number}
  575. * @constant
  576. */
  577. const ShortType = 1011;
  578. /**
  579. * An unsigned short data type for textures.
  580. *
  581. * @type {number}
  582. * @constant
  583. */
  584. const UnsignedShortType = 1012;
  585. /**
  586. * An int data type for textures.
  587. *
  588. * @type {number}
  589. * @constant
  590. */
  591. const IntType = 1013;
  592. /**
  593. * An unsigned int data type for textures.
  594. *
  595. * @type {number}
  596. * @constant
  597. */
  598. const UnsignedIntType = 1014;
  599. /**
  600. * A float data type for textures.
  601. *
  602. * @type {number}
  603. * @constant
  604. */
  605. const FloatType = 1015;
  606. /**
  607. * A half float data type for textures.
  608. *
  609. * @type {number}
  610. * @constant
  611. */
  612. const HalfFloatType = 1016;
  613. /**
  614. * An unsigned short 4_4_4_4 (packed) data type for textures.
  615. *
  616. * @type {number}
  617. * @constant
  618. */
  619. const UnsignedShort4444Type = 1017;
  620. /**
  621. * An unsigned short 5_5_5_1 (packed) data type for textures.
  622. *
  623. * @type {number}
  624. * @constant
  625. */
  626. const UnsignedShort5551Type = 1018;
  627. /**
  628. * An unsigned int 24_8 data type for textures.
  629. *
  630. * @type {number}
  631. * @constant
  632. */
  633. const UnsignedInt248Type = 1020;
  634. /**
  635. * An unsigned int 5_9_9_9 (packed) data type for textures.
  636. *
  637. * @type {number}
  638. * @constant
  639. */
  640. const UnsignedInt5999Type = 35902;
  641. /**
  642. * Discards the red, green and blue components and reads just the alpha component.
  643. *
  644. * @type {number}
  645. * @constant
  646. */
  647. const AlphaFormat = 1021;
  648. /**
  649. * Discards the alpha component and reads the red, green and blue component.
  650. *
  651. * @type {number}
  652. * @constant
  653. */
  654. const RGBFormat = 1022;
  655. /**
  656. * Reads the red, green, blue and alpha components.
  657. *
  658. * @type {number}
  659. * @constant
  660. */
  661. const RGBAFormat = 1023;
  662. /**
  663. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  664. *
  665. * @type {number}
  666. * @constant
  667. */
  668. const DepthFormat = 1026;
  669. /**
  670. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  671. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const DepthStencilFormat = 1027;
  677. /**
  678. * Discards the green, blue and alpha components and reads just the red component.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const RedFormat = 1028;
  684. /**
  685. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  686. *
  687. * @type {number}
  688. * @constant
  689. */
  690. const RedIntegerFormat = 1029;
  691. /**
  692. * Discards the alpha, and blue components and reads the red, and green components.
  693. *
  694. * @type {number}
  695. * @constant
  696. */
  697. const RGFormat = 1030;
  698. /**
  699. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  700. *
  701. * @type {number}
  702. * @constant
  703. */
  704. const RGIntegerFormat = 1031;
  705. /**
  706. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  707. *
  708. * @type {number}
  709. * @constant
  710. */
  711. const RGBIntegerFormat = 1032;
  712. /**
  713. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  714. *
  715. * @type {number}
  716. * @constant
  717. */
  718. const RGBAIntegerFormat = 1033;
  719. /**
  720. * A DXT1-compressed image in an RGB image format.
  721. *
  722. * @type {number}
  723. * @constant
  724. */
  725. const RGB_S3TC_DXT1_Format = 33776;
  726. /**
  727. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  728. *
  729. * @type {number}
  730. * @constant
  731. */
  732. const RGBA_S3TC_DXT1_Format = 33777;
  733. /**
  734. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  735. *
  736. * @type {number}
  737. * @constant
  738. */
  739. const RGBA_S3TC_DXT3_Format = 33778;
  740. /**
  741. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  742. * compression in how the alpha compression is done.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT5_Format = 33779;
  748. /**
  749. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGB_PVRTC_4BPPV1_Format = 35840;
  755. /**
  756. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  757. *
  758. * @type {number}
  759. * @constant
  760. */
  761. const RGB_PVRTC_2BPPV1_Format = 35841;
  762. /**
  763. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  764. *
  765. * @type {number}
  766. * @constant
  767. */
  768. const RGBA_PVRTC_4BPPV1_Format = 35842;
  769. /**
  770. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  771. *
  772. * @type {number}
  773. * @constant
  774. */
  775. const RGBA_PVRTC_2BPPV1_Format = 35843;
  776. /**
  777. * ETC1 RGB format.
  778. *
  779. * @type {number}
  780. * @constant
  781. */
  782. const RGB_ETC1_Format = 36196;
  783. /**
  784. * ETC2 RGB format.
  785. *
  786. * @type {number}
  787. * @constant
  788. */
  789. const RGB_ETC2_Format = 37492;
  790. /**
  791. * ETC2 RGBA format.
  792. *
  793. * @type {number}
  794. * @constant
  795. */
  796. const RGBA_ETC2_EAC_Format = 37496;
  797. /**
  798. * ASTC RGBA 4x4 format.
  799. *
  800. * @type {number}
  801. * @constant
  802. */
  803. const RGBA_ASTC_4x4_Format = 37808;
  804. /**
  805. * ASTC RGBA 5x4 format.
  806. *
  807. * @type {number}
  808. * @constant
  809. */
  810. const RGBA_ASTC_5x4_Format = 37809;
  811. /**
  812. * ASTC RGBA 5x5 format.
  813. *
  814. * @type {number}
  815. * @constant
  816. */
  817. const RGBA_ASTC_5x5_Format = 37810;
  818. /**
  819. * ASTC RGBA 6x5 format.
  820. *
  821. * @type {number}
  822. * @constant
  823. */
  824. const RGBA_ASTC_6x5_Format = 37811;
  825. /**
  826. * ASTC RGBA 6x6 format.
  827. *
  828. * @type {number}
  829. * @constant
  830. */
  831. const RGBA_ASTC_6x6_Format = 37812;
  832. /**
  833. * ASTC RGBA 8x5 format.
  834. *
  835. * @type {number}
  836. * @constant
  837. */
  838. const RGBA_ASTC_8x5_Format = 37813;
  839. /**
  840. * ASTC RGBA 8x6 format.
  841. *
  842. * @type {number}
  843. * @constant
  844. */
  845. const RGBA_ASTC_8x6_Format = 37814;
  846. /**
  847. * ASTC RGBA 8x8 format.
  848. *
  849. * @type {number}
  850. * @constant
  851. */
  852. const RGBA_ASTC_8x8_Format = 37815;
  853. /**
  854. * ASTC RGBA 10x5 format.
  855. *
  856. * @type {number}
  857. * @constant
  858. */
  859. const RGBA_ASTC_10x5_Format = 37816;
  860. /**
  861. * ASTC RGBA 10x6 format.
  862. *
  863. * @type {number}
  864. * @constant
  865. */
  866. const RGBA_ASTC_10x6_Format = 37817;
  867. /**
  868. * ASTC RGBA 10x8 format.
  869. *
  870. * @type {number}
  871. * @constant
  872. */
  873. const RGBA_ASTC_10x8_Format = 37818;
  874. /**
  875. * ASTC RGBA 10x10 format.
  876. *
  877. * @type {number}
  878. * @constant
  879. */
  880. const RGBA_ASTC_10x10_Format = 37819;
  881. /**
  882. * ASTC RGBA 12x10 format.
  883. *
  884. * @type {number}
  885. * @constant
  886. */
  887. const RGBA_ASTC_12x10_Format = 37820;
  888. /**
  889. * ASTC RGBA 12x12 format.
  890. *
  891. * @type {number}
  892. * @constant
  893. */
  894. const RGBA_ASTC_12x12_Format = 37821;
  895. /**
  896. * BPTC RGBA format.
  897. *
  898. * @type {number}
  899. * @constant
  900. */
  901. const RGBA_BPTC_Format = 36492;
  902. /**
  903. * BPTC Signed RGB format.
  904. *
  905. * @type {number}
  906. * @constant
  907. */
  908. const RGB_BPTC_SIGNED_Format = 36494;
  909. /**
  910. * BPTC Unsigned RGB format.
  911. *
  912. * @type {number}
  913. * @constant
  914. */
  915. const RGB_BPTC_UNSIGNED_Format = 36495;
  916. /**
  917. * RGTC1 Red format.
  918. *
  919. * @type {number}
  920. * @constant
  921. */
  922. const RED_RGTC1_Format = 36283;
  923. /**
  924. * RGTC1 Signed Red format.
  925. *
  926. * @type {number}
  927. * @constant
  928. */
  929. const SIGNED_RED_RGTC1_Format = 36284;
  930. /**
  931. * RGTC2 Red Green format.
  932. *
  933. * @type {number}
  934. * @constant
  935. */
  936. const RED_GREEN_RGTC2_Format = 36285;
  937. /**
  938. * RGTC2 Signed Red Green format.
  939. *
  940. * @type {number}
  941. * @constant
  942. */
  943. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  944. /**
  945. * Animations are played once.
  946. *
  947. * @type {number}
  948. * @constant
  949. */
  950. const LoopOnce = 2200;
  951. /**
  952. * Animations are played with a chosen number of repetitions, each time jumping from
  953. * the end of the clip directly to its beginning.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const LoopRepeat = 2201;
  959. /**
  960. * Animations are played with a chosen number of repetitions, alternately playing forward
  961. * and backward.
  962. *
  963. * @type {number}
  964. * @constant
  965. */
  966. const LoopPingPong = 2202;
  967. /**
  968. * Discrete interpolation mode for keyframe tracks.
  969. *
  970. * @type {number}
  971. * @constant
  972. */
  973. const InterpolateDiscrete = 2300;
  974. /**
  975. * Linear interpolation mode for keyframe tracks.
  976. *
  977. * @type {number}
  978. * @constant
  979. */
  980. const InterpolateLinear = 2301;
  981. /**
  982. * Smooth interpolation mode for keyframe tracks.
  983. *
  984. * @type {number}
  985. * @constant
  986. */
  987. const InterpolateSmooth = 2302;
  988. /**
  989. * Zero curvature ending for animations.
  990. *
  991. * @type {number}
  992. * @constant
  993. */
  994. const ZeroCurvatureEnding = 2400;
  995. /**
  996. * Zero slope ending for animations.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const ZeroSlopeEnding = 2401;
  1002. /**
  1003. * Wrap around ending for animations.
  1004. *
  1005. * @type {number}
  1006. * @constant
  1007. */
  1008. const WrapAroundEnding = 2402;
  1009. /**
  1010. * Default animation blend mode.
  1011. *
  1012. * @type {number}
  1013. * @constant
  1014. */
  1015. const NormalAnimationBlendMode = 2500;
  1016. /**
  1017. * Additive animation blend mode. Can be used to layer motions on top of
  1018. * each other to build complex performances from smaller re-usable assets.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const AdditiveAnimationBlendMode = 2501;
  1024. /**
  1025. * For every three vertices draw a single triangle.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const TrianglesDrawMode = 0;
  1031. /**
  1032. * For each vertex draw a triangle from the last three vertices.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const TriangleStripDrawMode = 1;
  1038. /**
  1039. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const TriangleFanDrawMode = 2;
  1045. /**
  1046. * Basic depth packing.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const BasicDepthPacking = 3200;
  1052. /**
  1053. * A depth value is packed into 32 bit RGBA.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const RGBADepthPacking = 3201;
  1059. /**
  1060. * A depth value is packed into 24 bit RGB.
  1061. *
  1062. * @type {number}
  1063. * @constant
  1064. */
  1065. const RGBDepthPacking = 3202;
  1066. /**
  1067. * A depth value is packed into 16 bit RG.
  1068. *
  1069. * @type {number}
  1070. * @constant
  1071. */
  1072. const RGDepthPacking = 3203;
  1073. /**
  1074. * Normal information is relative to the underlying surface.
  1075. *
  1076. * @type {number}
  1077. * @constant
  1078. */
  1079. const TangentSpaceNormalMap = 0;
  1080. /**
  1081. * Normal information is relative to the object orientation.
  1082. *
  1083. * @type {number}
  1084. * @constant
  1085. */
  1086. const ObjectSpaceNormalMap = 1;
  1087. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1088. /**
  1089. * No color space.
  1090. *
  1091. * @type {string}
  1092. * @constant
  1093. */
  1094. const NoColorSpace = '';
  1095. /**
  1096. * sRGB color space.
  1097. *
  1098. * @type {string}
  1099. * @constant
  1100. */
  1101. const SRGBColorSpace = 'srgb';
  1102. /**
  1103. * sRGB-linear color space.
  1104. *
  1105. * @type {string}
  1106. * @constant
  1107. */
  1108. const LinearSRGBColorSpace = 'srgb-linear';
  1109. /**
  1110. * Linear transfer function.
  1111. *
  1112. * @type {string}
  1113. * @constant
  1114. */
  1115. const LinearTransfer = 'linear';
  1116. /**
  1117. * sRGB transfer function.
  1118. *
  1119. * @type {string}
  1120. * @constant
  1121. */
  1122. const SRGBTransfer = 'srgb';
  1123. /**
  1124. * Sets the stencil buffer value to `0`.
  1125. *
  1126. * @type {number}
  1127. * @constant
  1128. */
  1129. const ZeroStencilOp = 0;
  1130. /**
  1131. * Keeps the current value.
  1132. *
  1133. * @type {number}
  1134. * @constant
  1135. */
  1136. const KeepStencilOp = 7680;
  1137. /**
  1138. * Sets the stencil buffer value to the specified reference value.
  1139. *
  1140. * @type {number}
  1141. * @constant
  1142. */
  1143. const ReplaceStencilOp = 7681;
  1144. /**
  1145. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1146. *
  1147. * @type {number}
  1148. * @constant
  1149. */
  1150. const IncrementStencilOp = 7682;
  1151. /**
  1152. * Decrements the current stencil buffer value. Clamps to `0`.
  1153. *
  1154. * @type {number}
  1155. * @constant
  1156. */
  1157. const DecrementStencilOp = 7683;
  1158. /**
  1159. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1160. * the maximum representable unsigned value.
  1161. *
  1162. * @type {number}
  1163. * @constant
  1164. */
  1165. const IncrementWrapStencilOp = 34055;
  1166. /**
  1167. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1168. * unsigned value when decrementing a stencil buffer value of `0`.
  1169. *
  1170. * @type {number}
  1171. * @constant
  1172. */
  1173. const DecrementWrapStencilOp = 34056;
  1174. /**
  1175. * Inverts the current stencil buffer value bitwise.
  1176. *
  1177. * @type {number}
  1178. * @constant
  1179. */
  1180. const InvertStencilOp = 5386;
  1181. /**
  1182. * Will never return true.
  1183. *
  1184. * @type {number}
  1185. * @constant
  1186. */
  1187. const NeverStencilFunc = 512;
  1188. /**
  1189. * Will return true if the stencil reference value is less than the current stencil value.
  1190. *
  1191. * @type {number}
  1192. * @constant
  1193. */
  1194. const LessStencilFunc = 513;
  1195. /**
  1196. * Will return true if the stencil reference value is equal to the current stencil value.
  1197. *
  1198. * @type {number}
  1199. * @constant
  1200. */
  1201. const EqualStencilFunc = 514;
  1202. /**
  1203. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1204. *
  1205. * @type {number}
  1206. * @constant
  1207. */
  1208. const LessEqualStencilFunc = 515;
  1209. /**
  1210. * Will return true if the stencil reference value is greater than the current stencil value.
  1211. *
  1212. * @type {number}
  1213. * @constant
  1214. */
  1215. const GreaterStencilFunc = 516;
  1216. /**
  1217. * Will return true if the stencil reference value is not equal to the current stencil value.
  1218. *
  1219. * @type {number}
  1220. * @constant
  1221. */
  1222. const NotEqualStencilFunc = 517;
  1223. /**
  1224. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const GreaterEqualStencilFunc = 518;
  1230. /**
  1231. * Will always return true.
  1232. *
  1233. * @type {number}
  1234. * @constant
  1235. */
  1236. const AlwaysStencilFunc = 519;
  1237. /**
  1238. * Never pass.
  1239. *
  1240. * @type {number}
  1241. * @constant
  1242. */
  1243. const NeverCompare = 512;
  1244. /**
  1245. * Pass if the incoming value is less than the texture value.
  1246. *
  1247. * @type {number}
  1248. * @constant
  1249. */
  1250. const LessCompare = 513;
  1251. /**
  1252. * Pass if the incoming value equals the texture value.
  1253. *
  1254. * @type {number}
  1255. * @constant
  1256. */
  1257. const EqualCompare = 514;
  1258. /**
  1259. * Pass if the incoming value is less than or equal to the texture value.
  1260. *
  1261. * @type {number}
  1262. * @constant
  1263. */
  1264. const LessEqualCompare = 515;
  1265. /**
  1266. * Pass if the incoming value is greater than the texture value.
  1267. *
  1268. * @type {number}
  1269. * @constant
  1270. */
  1271. const GreaterCompare = 516;
  1272. /**
  1273. * Pass if the incoming value is not equal to the texture value.
  1274. *
  1275. * @type {number}
  1276. * @constant
  1277. */
  1278. const NotEqualCompare = 517;
  1279. /**
  1280. * Pass if the incoming value is greater than or equal to the texture value.
  1281. *
  1282. * @type {number}
  1283. * @constant
  1284. */
  1285. const GreaterEqualCompare = 518;
  1286. /**
  1287. * Always pass.
  1288. *
  1289. * @type {number}
  1290. * @constant
  1291. */
  1292. const AlwaysCompare = 519;
  1293. /**
  1294. * The contents are intended to be specified once by the application, and used many
  1295. * times as the source for drawing and image specification commands.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const StaticDrawUsage = 35044;
  1301. /**
  1302. * The contents are intended to be respecified repeatedly by the application, and
  1303. * used many times as the source for drawing and image specification commands.
  1304. *
  1305. * @type {number}
  1306. * @constant
  1307. */
  1308. const DynamicDrawUsage = 35048;
  1309. /**
  1310. * The contents are intended to be specified once by the application, and used at most
  1311. * a few times as the source for drawing and image specification commands.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const StreamDrawUsage = 35040;
  1317. /**
  1318. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1319. * many times by the application.
  1320. *
  1321. * @type {number}
  1322. * @constant
  1323. */
  1324. const StaticReadUsage = 35045;
  1325. /**
  1326. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1327. * many times by the application.
  1328. *
  1329. * @type {number}
  1330. * @constant
  1331. */
  1332. const DynamicReadUsage = 35049;
  1333. /**
  1334. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1335. * a few times by the application
  1336. *
  1337. * @type {number}
  1338. * @constant
  1339. */
  1340. const StreamReadUsage = 35041;
  1341. /**
  1342. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1343. * the source for WebGL drawing and image specification commands.
  1344. *
  1345. * @type {number}
  1346. * @constant
  1347. */
  1348. const StaticCopyUsage = 35046;
  1349. /**
  1350. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1351. * as the source for WebGL drawing and image specification commands.
  1352. *
  1353. * @type {number}
  1354. * @constant
  1355. */
  1356. const DynamicCopyUsage = 35050;
  1357. /**
  1358. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1359. * as the source for WebGL drawing and image specification commands.
  1360. *
  1361. * @type {number}
  1362. * @constant
  1363. */
  1364. const StreamCopyUsage = 35042;
  1365. /**
  1366. * GLSL 1 shader code.
  1367. *
  1368. * @type {string}
  1369. * @constant
  1370. */
  1371. const GLSL1 = '100';
  1372. /**
  1373. * GLSL 3 shader code.
  1374. *
  1375. * @type {string}
  1376. * @constant
  1377. */
  1378. const GLSL3 = '300 es';
  1379. /**
  1380. * WebGL coordinate system.
  1381. *
  1382. * @type {number}
  1383. * @constant
  1384. */
  1385. const WebGLCoordinateSystem = 2000;
  1386. /**
  1387. * WebGPU coordinate system.
  1388. *
  1389. * @type {number}
  1390. * @constant
  1391. */
  1392. const WebGPUCoordinateSystem = 2001;
  1393. /**
  1394. * Represents the different timestamp query types.
  1395. *
  1396. * @type {ConstantsTimestampQuery}
  1397. * @constant
  1398. */
  1399. const TimestampQuery = {
  1400. COMPUTE: 'compute',
  1401. RENDER: 'render'
  1402. };
  1403. /**
  1404. * Represents mouse buttons and interaction types in context of controls.
  1405. *
  1406. * @type {ConstantsInterpolationSamplingType}
  1407. * @constant
  1408. */
  1409. const InterpolationSamplingType = {
  1410. PERSPECTIVE: 'perspective',
  1411. LINEAR: 'linear',
  1412. FLAT: 'flat'
  1413. };
  1414. /**
  1415. * Represents the different interpolation sampling modes.
  1416. *
  1417. * @type {ConstantsInterpolationSamplingMode}
  1418. * @constant
  1419. */
  1420. const InterpolationSamplingMode = {
  1421. NORMAL: 'normal',
  1422. CENTROID: 'centroid',
  1423. SAMPLE: 'sample',
  1424. FIRST: 'first',
  1425. EITHER: 'either'
  1426. };
  1427. /**
  1428. * This type represents mouse buttons and interaction types in context of controls.
  1429. *
  1430. * @typedef {Object} ConstantsMouse
  1431. * @property {number} MIDDLE - The left mouse button.
  1432. * @property {number} LEFT - The middle mouse button.
  1433. * @property {number} RIGHT - The right mouse button.
  1434. * @property {number} ROTATE - A rotate interaction.
  1435. * @property {number} DOLLY - A dolly interaction.
  1436. * @property {number} PAN - A pan interaction.
  1437. **/
  1438. /**
  1439. * This type represents touch interaction types in context of controls.
  1440. *
  1441. * @typedef {Object} ConstantsTouch
  1442. * @property {number} ROTATE - A rotate interaction.
  1443. * @property {number} PAN - A pan interaction.
  1444. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1445. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1446. **/
  1447. /**
  1448. * This type represents the different timestamp query types.
  1449. *
  1450. * @typedef {Object} ConstantsTimestampQuery
  1451. * @property {string} COMPUTE - A `compute` timestamp query.
  1452. * @property {string} RENDER - A `render` timestamp query.
  1453. **/
  1454. /**
  1455. * Represents the different interpolation sampling types.
  1456. *
  1457. * @typedef {Object} ConstantsInterpolationSamplingType
  1458. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1459. * @property {string} LINEAR - Linear interpolation.
  1460. * @property {string} FLAT - Flat interpolation.
  1461. */
  1462. /**
  1463. * Represents the different interpolation sampling modes.
  1464. *
  1465. * @typedef {Object} ConstantsInterpolationSamplingMode
  1466. * @property {string} NORMAL - Normal sampling mode.
  1467. * @property {string} CENTROID - Centroid sampling mode.
  1468. * @property {string} SAMPLE - Sample-specific sampling mode.
  1469. * @property {string} FLAT_FIRST - Flat interpolation using the first vertex.
  1470. * @property {string} FLAT_EITHER - Flat interpolation using either vertex.
  1471. */
  1472. /**
  1473. * This modules allows to dispatch event objects on custom JavaScript objects.
  1474. *
  1475. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1476. *
  1477. * Code Example:
  1478. * ```js
  1479. * class Car extends EventDispatcher {
  1480. * start() {
  1481. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1482. * }
  1483. *};
  1484. *
  1485. * // Using events with the custom object
  1486. * const car = new Car();
  1487. * car.addEventListener( 'start', function ( event ) {
  1488. * alert( event.message );
  1489. * } );
  1490. *
  1491. * car.start();
  1492. * ```
  1493. */
  1494. class EventDispatcher {
  1495. /**
  1496. * Adds the given event listener to the given event type.
  1497. *
  1498. * @param {string} type - The type of event to listen to.
  1499. * @param {Function} listener - The function that gets called when the event is fired.
  1500. */
  1501. addEventListener( type, listener ) {
  1502. if ( this._listeners === undefined ) this._listeners = {};
  1503. const listeners = this._listeners;
  1504. if ( listeners[ type ] === undefined ) {
  1505. listeners[ type ] = [];
  1506. }
  1507. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1508. listeners[ type ].push( listener );
  1509. }
  1510. }
  1511. /**
  1512. * Returns `true` if the given event listener has been added to the given event type.
  1513. *
  1514. * @param {string} type - The type of event.
  1515. * @param {Function} listener - The listener to check.
  1516. * @return {boolean} Whether the given event listener has been added to the given event type.
  1517. */
  1518. hasEventListener( type, listener ) {
  1519. const listeners = this._listeners;
  1520. if ( listeners === undefined ) return false;
  1521. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1522. }
  1523. /**
  1524. * Removes the given event listener from the given event type.
  1525. *
  1526. * @param {string} type - The type of event.
  1527. * @param {Function} listener - The listener to remove.
  1528. */
  1529. removeEventListener( type, listener ) {
  1530. const listeners = this._listeners;
  1531. if ( listeners === undefined ) return;
  1532. const listenerArray = listeners[ type ];
  1533. if ( listenerArray !== undefined ) {
  1534. const index = listenerArray.indexOf( listener );
  1535. if ( index !== -1 ) {
  1536. listenerArray.splice( index, 1 );
  1537. }
  1538. }
  1539. }
  1540. /**
  1541. * Dispatches an event object.
  1542. *
  1543. * @param {Object} event - The event that gets fired.
  1544. */
  1545. dispatchEvent( event ) {
  1546. const listeners = this._listeners;
  1547. if ( listeners === undefined ) return;
  1548. const listenerArray = listeners[ event.type ];
  1549. if ( listenerArray !== undefined ) {
  1550. event.target = this;
  1551. // Make a copy, in case listeners are removed while iterating.
  1552. const array = listenerArray.slice( 0 );
  1553. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1554. array[ i ].call( this, event );
  1555. }
  1556. event.target = null;
  1557. }
  1558. }
  1559. }
  1560. 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' ];
  1561. let _seed = 1234567;
  1562. const DEG2RAD = Math.PI / 180;
  1563. const RAD2DEG = 180 / Math.PI;
  1564. /**
  1565. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1566. * (universally unique identifier).
  1567. *
  1568. * @return {string} The UUID.
  1569. */
  1570. function generateUUID() {
  1571. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1572. const d0 = Math.random() * 0xffffffff | 0;
  1573. const d1 = Math.random() * 0xffffffff | 0;
  1574. const d2 = Math.random() * 0xffffffff | 0;
  1575. const d3 = Math.random() * 0xffffffff | 0;
  1576. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1577. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1578. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1579. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1580. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1581. return uuid.toLowerCase();
  1582. }
  1583. /**
  1584. * Clamps the given value between min and max.
  1585. *
  1586. * @param {number} value - The value to clamp.
  1587. * @param {number} min - The min value.
  1588. * @param {number} max - The max value.
  1589. * @return {number} The clamped value.
  1590. */
  1591. function clamp( value, min, max ) {
  1592. return Math.max( min, Math.min( max, value ) );
  1593. }
  1594. /**
  1595. * Computes the Euclidean modulo of the given parameters that
  1596. * is `( ( n % m ) + m ) % m`.
  1597. *
  1598. * @param {number} n - The first parameter.
  1599. * @param {number} m - The second parameter.
  1600. * @return {number} The Euclidean modulo.
  1601. */
  1602. function euclideanModulo( n, m ) {
  1603. // https://en.wikipedia.org/wiki/Modulo_operation
  1604. return ( ( n % m ) + m ) % m;
  1605. }
  1606. /**
  1607. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1608. * for the given value.
  1609. *
  1610. * @param {number} x - The value to be mapped.
  1611. * @param {number} a1 - Minimum value for range A.
  1612. * @param {number} a2 - Maximum value for range A.
  1613. * @param {number} b1 - Minimum value for range B.
  1614. * @param {number} b2 - Maximum value for range B.
  1615. * @return {number} The mapped value.
  1616. */
  1617. function mapLinear( x, a1, a2, b1, b2 ) {
  1618. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1619. }
  1620. /**
  1621. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1622. * between the start and end point.
  1623. *
  1624. * @param {number} x - The start point
  1625. * @param {number} y - The end point.
  1626. * @param {number} value - A value between start and end.
  1627. * @return {number} The interpolation factor.
  1628. */
  1629. function inverseLerp( x, y, value ) {
  1630. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1631. if ( x !== y ) {
  1632. return ( value - x ) / ( y - x );
  1633. } else {
  1634. return 0;
  1635. }
  1636. }
  1637. /**
  1638. * Returns a value linearly interpolated from two known points based on the given interval -
  1639. * `t = 0` will return `x` and `t = 1` will return `y`.
  1640. *
  1641. * @param {number} x - The start point
  1642. * @param {number} y - The end point.
  1643. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1644. * @return {number} The interpolated value.
  1645. */
  1646. function lerp( x, y, t ) {
  1647. return ( 1 - t ) * x + t * y;
  1648. }
  1649. /**
  1650. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1651. * time to maintain frame rate independent movement. For details, see
  1652. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1653. *
  1654. * @param {number} x - The current point.
  1655. * @param {number} y - The target point.
  1656. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1657. * and a lower value will make the movement more gradual.
  1658. * @param {number} dt - Delta time in seconds.
  1659. * @return {number} The interpolated value.
  1660. */
  1661. function damp( x, y, lambda, dt ) {
  1662. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1663. }
  1664. /**
  1665. * Returns a value that alternates between `0` and the given `length` parameter.
  1666. *
  1667. * @param {number} x - The value to pingpong.
  1668. * @param {number} [length=1] - The positive value the function will pingpong to.
  1669. * @return {number} The alternated value.
  1670. */
  1671. function pingpong( x, length = 1 ) {
  1672. // https://www.desmos.com/calculator/vcsjnyz7x4
  1673. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1674. }
  1675. /**
  1676. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1677. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1678. * the `min` and `max`.
  1679. *
  1680. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1681. *
  1682. * @param {number} x - The value to evaluate based on its position between min and max.
  1683. * @param {number} min - The min value. Any x value below min will be `0`.
  1684. * @param {number} max - The max value. Any x value above max will be `1`.
  1685. * @return {number} The alternated value.
  1686. */
  1687. function smoothstep( x, min, max ) {
  1688. if ( x <= min ) return 0;
  1689. if ( x >= max ) return 1;
  1690. x = ( x - min ) / ( max - min );
  1691. return x * x * ( 3 - 2 * x );
  1692. }
  1693. /**
  1694. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1695. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1696. *
  1697. * @param {number} x - The value to evaluate based on its position between min and max.
  1698. * @param {number} min - The min value. Any x value below min will be `0`.
  1699. * @param {number} max - The max value. Any x value above max will be `1`.
  1700. * @return {number} The alternated value.
  1701. */
  1702. function smootherstep( x, min, max ) {
  1703. if ( x <= min ) return 0;
  1704. if ( x >= max ) return 1;
  1705. x = ( x - min ) / ( max - min );
  1706. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1707. }
  1708. /**
  1709. * Returns a random integer from `<low, high>` interval.
  1710. *
  1711. * @param {number} low - The lower value boundary.
  1712. * @param {number} high - The upper value boundary
  1713. * @return {number} A random integer.
  1714. */
  1715. function randInt( low, high ) {
  1716. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1717. }
  1718. /**
  1719. * Returns a random float from `<low, high>` interval.
  1720. *
  1721. * @param {number} low - The lower value boundary.
  1722. * @param {number} high - The upper value boundary
  1723. * @return {number} A random float.
  1724. */
  1725. function randFloat( low, high ) {
  1726. return low + Math.random() * ( high - low );
  1727. }
  1728. /**
  1729. * Returns a random integer from `<-range/2, range/2>` interval.
  1730. *
  1731. * @param {number} range - Defines the value range.
  1732. * @return {number} A random float.
  1733. */
  1734. function randFloatSpread( range ) {
  1735. return range * ( 0.5 - Math.random() );
  1736. }
  1737. /**
  1738. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1739. *
  1740. * @param {number} [s] - The integer seed.
  1741. * @return {number} A random float.
  1742. */
  1743. function seededRandom( s ) {
  1744. if ( s !== undefined ) _seed = s;
  1745. // Mulberry32 generator
  1746. let t = _seed += 0x6D2B79F5;
  1747. t = Math.imul( t ^ t >>> 15, t | 1 );
  1748. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1749. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1750. }
  1751. /**
  1752. * Converts degrees to radians.
  1753. *
  1754. * @param {number} degrees - A value in degrees.
  1755. * @return {number} The converted value in radians.
  1756. */
  1757. function degToRad( degrees ) {
  1758. return degrees * DEG2RAD;
  1759. }
  1760. /**
  1761. * Converts radians to degrees.
  1762. *
  1763. * @param {number} radians - A value in radians.
  1764. * @return {number} The converted value in degrees.
  1765. */
  1766. function radToDeg( radians ) {
  1767. return radians * RAD2DEG;
  1768. }
  1769. /**
  1770. * Returns `true` if the given number is a power of two.
  1771. *
  1772. * @param {number} value - The value to check.
  1773. * @return {boolean} Whether the given number is a power of two or not.
  1774. */
  1775. function isPowerOfTwo( value ) {
  1776. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1777. }
  1778. /**
  1779. * Returns the smallest power of two that is greater than or equal to the given number.
  1780. *
  1781. * @param {number} value - The value to find a POT for.
  1782. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1783. */
  1784. function ceilPowerOfTwo( value ) {
  1785. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1786. }
  1787. /**
  1788. * Returns the largest power of two that is less than or equal to the given number.
  1789. *
  1790. * @param {number} value - The value to find a POT for.
  1791. * @return {number} The largest power of two that is less than or equal to the given number.
  1792. */
  1793. function floorPowerOfTwo( value ) {
  1794. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1795. }
  1796. /**
  1797. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1798. * defined by the given angles and order.
  1799. *
  1800. * Rotations are applied to the axes in the order specified by order:
  1801. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1802. *
  1803. * @param {Quaternion} q - The quaternion to set.
  1804. * @param {number} a - The rotation applied to the first axis, in radians.
  1805. * @param {number} b - The rotation applied to the second axis, in radians.
  1806. * @param {number} c - The rotation applied to the third axis, in radians.
  1807. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1808. */
  1809. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1810. const cos = Math.cos;
  1811. const sin = Math.sin;
  1812. const c2 = cos( b / 2 );
  1813. const s2 = sin( b / 2 );
  1814. const c13 = cos( ( a + c ) / 2 );
  1815. const s13 = sin( ( a + c ) / 2 );
  1816. const c1_3 = cos( ( a - c ) / 2 );
  1817. const s1_3 = sin( ( a - c ) / 2 );
  1818. const c3_1 = cos( ( c - a ) / 2 );
  1819. const s3_1 = sin( ( c - a ) / 2 );
  1820. switch ( order ) {
  1821. case 'XYX':
  1822. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1823. break;
  1824. case 'YZY':
  1825. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1826. break;
  1827. case 'ZXZ':
  1828. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1829. break;
  1830. case 'XZX':
  1831. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1832. break;
  1833. case 'YXY':
  1834. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1835. break;
  1836. case 'ZYZ':
  1837. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1838. break;
  1839. default:
  1840. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1841. }
  1842. }
  1843. /**
  1844. * Denormalizes the given value according to the given typed array.
  1845. *
  1846. * @param {number} value - The value to denormalize.
  1847. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1848. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1849. */
  1850. function denormalize( value, array ) {
  1851. switch ( array.constructor ) {
  1852. case Float32Array:
  1853. return value;
  1854. case Uint32Array:
  1855. return value / 4294967295.0;
  1856. case Uint16Array:
  1857. return value / 65535.0;
  1858. case Uint8Array:
  1859. return value / 255.0;
  1860. case Int32Array:
  1861. return Math.max( value / 2147483647.0, -1 );
  1862. case Int16Array:
  1863. return Math.max( value / 32767.0, -1 );
  1864. case Int8Array:
  1865. return Math.max( value / 127.0, -1 );
  1866. default:
  1867. throw new Error( 'Invalid component type.' );
  1868. }
  1869. }
  1870. /**
  1871. * Normalizes the given value according to the given typed array.
  1872. *
  1873. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1874. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1875. * @return {number} The normalize value.
  1876. */
  1877. function normalize( value, array ) {
  1878. switch ( array.constructor ) {
  1879. case Float32Array:
  1880. return value;
  1881. case Uint32Array:
  1882. return Math.round( value * 4294967295.0 );
  1883. case Uint16Array:
  1884. return Math.round( value * 65535.0 );
  1885. case Uint8Array:
  1886. return Math.round( value * 255.0 );
  1887. case Int32Array:
  1888. return Math.round( value * 2147483647.0 );
  1889. case Int16Array:
  1890. return Math.round( value * 32767.0 );
  1891. case Int8Array:
  1892. return Math.round( value * 127.0 );
  1893. default:
  1894. throw new Error( 'Invalid component type.' );
  1895. }
  1896. }
  1897. /**
  1898. * @class
  1899. * @classdesc A collection of math utility functions.
  1900. * @hideconstructor
  1901. */
  1902. const MathUtils = {
  1903. DEG2RAD: DEG2RAD,
  1904. RAD2DEG: RAD2DEG,
  1905. /**
  1906. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1907. * (universally unique identifier).
  1908. *
  1909. * @static
  1910. * @method
  1911. * @return {string} The UUID.
  1912. */
  1913. generateUUID: generateUUID,
  1914. /**
  1915. * Clamps the given value between min and max.
  1916. *
  1917. * @static
  1918. * @method
  1919. * @param {number} value - The value to clamp.
  1920. * @param {number} min - The min value.
  1921. * @param {number} max - The max value.
  1922. * @return {number} The clamped value.
  1923. */
  1924. clamp: clamp,
  1925. /**
  1926. * Computes the Euclidean modulo of the given parameters that
  1927. * is `( ( n % m ) + m ) % m`.
  1928. *
  1929. * @static
  1930. * @method
  1931. * @param {number} n - The first parameter.
  1932. * @param {number} m - The second parameter.
  1933. * @return {number} The Euclidean modulo.
  1934. */
  1935. euclideanModulo: euclideanModulo,
  1936. /**
  1937. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1938. * for the given value.
  1939. *
  1940. * @static
  1941. * @method
  1942. * @param {number} x - The value to be mapped.
  1943. * @param {number} a1 - Minimum value for range A.
  1944. * @param {number} a2 - Maximum value for range A.
  1945. * @param {number} b1 - Minimum value for range B.
  1946. * @param {number} b2 - Maximum value for range B.
  1947. * @return {number} The mapped value.
  1948. */
  1949. mapLinear: mapLinear,
  1950. /**
  1951. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1952. * between the start and end point.
  1953. *
  1954. * @static
  1955. * @method
  1956. * @param {number} x - The start point
  1957. * @param {number} y - The end point.
  1958. * @param {number} value - A value between start and end.
  1959. * @return {number} The interpolation factor.
  1960. */
  1961. inverseLerp: inverseLerp,
  1962. /**
  1963. * Returns a value linearly interpolated from two known points based on the given interval -
  1964. * `t = 0` will return `x` and `t = 1` will return `y`.
  1965. *
  1966. * @static
  1967. * @method
  1968. * @param {number} x - The start point
  1969. * @param {number} y - The end point.
  1970. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1971. * @return {number} The interpolated value.
  1972. */
  1973. lerp: lerp,
  1974. /**
  1975. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1976. * time to maintain frame rate independent movement. For details, see
  1977. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1978. *
  1979. * @static
  1980. * @method
  1981. * @param {number} x - The current point.
  1982. * @param {number} y - The target point.
  1983. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1984. * and a lower value will make the movement more gradual.
  1985. * @param {number} dt - Delta time in seconds.
  1986. * @return {number} The interpolated value.
  1987. */
  1988. damp: damp,
  1989. /**
  1990. * Returns a value that alternates between `0` and the given `length` parameter.
  1991. *
  1992. * @static
  1993. * @method
  1994. * @param {number} x - The value to pingpong.
  1995. * @param {number} [length=1] - The positive value the function will pingpong to.
  1996. * @return {number} The alternated value.
  1997. */
  1998. pingpong: pingpong,
  1999. /**
  2000. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2001. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2002. * the `min` and `max`.
  2003. *
  2004. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2005. *
  2006. * @static
  2007. * @method
  2008. * @param {number} x - The value to evaluate based on its position between min and max.
  2009. * @param {number} min - The min value. Any x value below min will be `0`.
  2010. * @param {number} max - The max value. Any x value above max will be `1`.
  2011. * @return {number} The alternated value.
  2012. */
  2013. smoothstep: smoothstep,
  2014. /**
  2015. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2016. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2017. *
  2018. * @static
  2019. * @method
  2020. * @param {number} x - The value to evaluate based on its position between min and max.
  2021. * @param {number} min - The min value. Any x value below min will be `0`.
  2022. * @param {number} max - The max value. Any x value above max will be `1`.
  2023. * @return {number} The alternated value.
  2024. */
  2025. smootherstep: smootherstep,
  2026. /**
  2027. * Returns a random integer from `<low, high>` interval.
  2028. *
  2029. * @static
  2030. * @method
  2031. * @param {number} low - The lower value boundary.
  2032. * @param {number} high - The upper value boundary
  2033. * @return {number} A random integer.
  2034. */
  2035. randInt: randInt,
  2036. /**
  2037. * Returns a random float from `<low, high>` interval.
  2038. *
  2039. * @static
  2040. * @method
  2041. * @param {number} low - The lower value boundary.
  2042. * @param {number} high - The upper value boundary
  2043. * @return {number} A random float.
  2044. */
  2045. randFloat: randFloat,
  2046. /**
  2047. * Returns a random integer from `<-range/2, range/2>` interval.
  2048. *
  2049. * @static
  2050. * @method
  2051. * @param {number} range - Defines the value range.
  2052. * @return {number} A random float.
  2053. */
  2054. randFloatSpread: randFloatSpread,
  2055. /**
  2056. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2057. *
  2058. * @static
  2059. * @method
  2060. * @param {number} [s] - The integer seed.
  2061. * @return {number} A random float.
  2062. */
  2063. seededRandom: seededRandom,
  2064. /**
  2065. * Converts degrees to radians.
  2066. *
  2067. * @static
  2068. * @method
  2069. * @param {number} degrees - A value in degrees.
  2070. * @return {number} The converted value in radians.
  2071. */
  2072. degToRad: degToRad,
  2073. /**
  2074. * Converts radians to degrees.
  2075. *
  2076. * @static
  2077. * @method
  2078. * @param {number} radians - A value in radians.
  2079. * @return {number} The converted value in degrees.
  2080. */
  2081. radToDeg: radToDeg,
  2082. /**
  2083. * Returns `true` if the given number is a power of two.
  2084. *
  2085. * @static
  2086. * @method
  2087. * @param {number} value - The value to check.
  2088. * @return {boolean} Whether the given number is a power of two or not.
  2089. */
  2090. isPowerOfTwo: isPowerOfTwo,
  2091. /**
  2092. * Returns the smallest power of two that is greater than or equal to the given number.
  2093. *
  2094. * @static
  2095. * @method
  2096. * @param {number} value - The value to find a POT for.
  2097. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2098. */
  2099. ceilPowerOfTwo: ceilPowerOfTwo,
  2100. /**
  2101. * Returns the largest power of two that is less than or equal to the given number.
  2102. *
  2103. * @static
  2104. * @method
  2105. * @param {number} value - The value to find a POT for.
  2106. * @return {number} The largest power of two that is less than or equal to the given number.
  2107. */
  2108. floorPowerOfTwo: floorPowerOfTwo,
  2109. /**
  2110. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2111. * defined by the given angles and order.
  2112. *
  2113. * Rotations are applied to the axes in the order specified by order:
  2114. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2115. *
  2116. * @static
  2117. * @method
  2118. * @param {Quaternion} q - The quaternion to set.
  2119. * @param {number} a - The rotation applied to the first axis, in radians.
  2120. * @param {number} b - The rotation applied to the second axis, in radians.
  2121. * @param {number} c - The rotation applied to the third axis, in radians.
  2122. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2123. */
  2124. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2125. /**
  2126. * Normalizes the given value according to the given typed array.
  2127. *
  2128. * @static
  2129. * @method
  2130. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2131. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2132. * @return {number} The normalize value.
  2133. */
  2134. normalize: normalize,
  2135. /**
  2136. * Denormalizes the given value according to the given typed array.
  2137. *
  2138. * @static
  2139. * @method
  2140. * @param {number} value - The value to denormalize.
  2141. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2142. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2143. */
  2144. denormalize: denormalize
  2145. };
  2146. /**
  2147. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2148. * (labeled x and y), which can be used to represent a number of things, such as:
  2149. *
  2150. * - A point in 2D space (i.e. a position on a plane).
  2151. * - A direction and length across a plane. In three.js the length will
  2152. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2153. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2154. * - Any arbitrary ordered pair of numbers.
  2155. *
  2156. * There are other things a 2D vector can be used to represent, such as
  2157. * momentum vectors, complex numbers and so on, however these are the most
  2158. * common uses in three.js.
  2159. *
  2160. * Iterating through a vector instance will yield its components `(x, y)` in
  2161. * the corresponding order.
  2162. * ```js
  2163. * const a = new THREE.Vector2( 0, 1 );
  2164. *
  2165. * //no arguments; will be initialised to (0, 0)
  2166. * const b = new THREE.Vector2( );
  2167. *
  2168. * const d = a.distanceTo( b );
  2169. * ```
  2170. */
  2171. class Vector2 {
  2172. /**
  2173. * Constructs a new 2D vector.
  2174. *
  2175. * @param {number} [x=0] - The x value of this vector.
  2176. * @param {number} [y=0] - The y value of this vector.
  2177. */
  2178. constructor( x = 0, y = 0 ) {
  2179. /**
  2180. * This flag can be used for type testing.
  2181. *
  2182. * @type {boolean}
  2183. * @readonly
  2184. * @default true
  2185. */
  2186. Vector2.prototype.isVector2 = true;
  2187. /**
  2188. * The x value of this vector.
  2189. *
  2190. * @type {number}
  2191. */
  2192. this.x = x;
  2193. /**
  2194. * The y value of this vector.
  2195. *
  2196. * @type {number}
  2197. */
  2198. this.y = y;
  2199. }
  2200. /**
  2201. * Alias for {@link Vector2#x}.
  2202. *
  2203. * @type {number}
  2204. */
  2205. get width() {
  2206. return this.x;
  2207. }
  2208. set width( value ) {
  2209. this.x = value;
  2210. }
  2211. /**
  2212. * Alias for {@link Vector2#y}.
  2213. *
  2214. * @type {number}
  2215. */
  2216. get height() {
  2217. return this.y;
  2218. }
  2219. set height( value ) {
  2220. this.y = value;
  2221. }
  2222. /**
  2223. * Sets the vector components.
  2224. *
  2225. * @param {number} x - The value of the x component.
  2226. * @param {number} y - The value of the y component.
  2227. * @return {Vector2} A reference to this vector.
  2228. */
  2229. set( x, y ) {
  2230. this.x = x;
  2231. this.y = y;
  2232. return this;
  2233. }
  2234. /**
  2235. * Sets the vector components to the same value.
  2236. *
  2237. * @param {number} scalar - The value to set for all vector components.
  2238. * @return {Vector2} A reference to this vector.
  2239. */
  2240. setScalar( scalar ) {
  2241. this.x = scalar;
  2242. this.y = scalar;
  2243. return this;
  2244. }
  2245. /**
  2246. * Sets the vector's x component to the given value
  2247. *
  2248. * @param {number} x - The value to set.
  2249. * @return {Vector2} A reference to this vector.
  2250. */
  2251. setX( x ) {
  2252. this.x = x;
  2253. return this;
  2254. }
  2255. /**
  2256. * Sets the vector's y component to the given value
  2257. *
  2258. * @param {number} y - The value to set.
  2259. * @return {Vector2} A reference to this vector.
  2260. */
  2261. setY( y ) {
  2262. this.y = y;
  2263. return this;
  2264. }
  2265. /**
  2266. * Allows to set a vector component with an index.
  2267. *
  2268. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2269. * @param {number} value - The value to set.
  2270. * @return {Vector2} A reference to this vector.
  2271. */
  2272. setComponent( index, value ) {
  2273. switch ( index ) {
  2274. case 0: this.x = value; break;
  2275. case 1: this.y = value; break;
  2276. default: throw new Error( 'index is out of range: ' + index );
  2277. }
  2278. return this;
  2279. }
  2280. /**
  2281. * Returns the value of the vector component which matches the given index.
  2282. *
  2283. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2284. * @return {number} A vector component value.
  2285. */
  2286. getComponent( index ) {
  2287. switch ( index ) {
  2288. case 0: return this.x;
  2289. case 1: return this.y;
  2290. default: throw new Error( 'index is out of range: ' + index );
  2291. }
  2292. }
  2293. /**
  2294. * Returns a new vector with copied values from this instance.
  2295. *
  2296. * @return {Vector2} A clone of this instance.
  2297. */
  2298. clone() {
  2299. return new this.constructor( this.x, this.y );
  2300. }
  2301. /**
  2302. * Copies the values of the given vector to this instance.
  2303. *
  2304. * @param {Vector2} v - The vector to copy.
  2305. * @return {Vector2} A reference to this vector.
  2306. */
  2307. copy( v ) {
  2308. this.x = v.x;
  2309. this.y = v.y;
  2310. return this;
  2311. }
  2312. /**
  2313. * Adds the given vector to this instance.
  2314. *
  2315. * @param {Vector2} v - The vector to add.
  2316. * @return {Vector2} A reference to this vector.
  2317. */
  2318. add( v ) {
  2319. this.x += v.x;
  2320. this.y += v.y;
  2321. return this;
  2322. }
  2323. /**
  2324. * Adds the given scalar value to all components of this instance.
  2325. *
  2326. * @param {number} s - The scalar to add.
  2327. * @return {Vector2} A reference to this vector.
  2328. */
  2329. addScalar( s ) {
  2330. this.x += s;
  2331. this.y += s;
  2332. return this;
  2333. }
  2334. /**
  2335. * Adds the given vectors and stores the result in this instance.
  2336. *
  2337. * @param {Vector2} a - The first vector.
  2338. * @param {Vector2} b - The second vector.
  2339. * @return {Vector2} A reference to this vector.
  2340. */
  2341. addVectors( a, b ) {
  2342. this.x = a.x + b.x;
  2343. this.y = a.y + b.y;
  2344. return this;
  2345. }
  2346. /**
  2347. * Adds the given vector scaled by the given factor to this instance.
  2348. *
  2349. * @param {Vector2} v - The vector.
  2350. * @param {number} s - The factor that scales `v`.
  2351. * @return {Vector2} A reference to this vector.
  2352. */
  2353. addScaledVector( v, s ) {
  2354. this.x += v.x * s;
  2355. this.y += v.y * s;
  2356. return this;
  2357. }
  2358. /**
  2359. * Subtracts the given vector from this instance.
  2360. *
  2361. * @param {Vector2} v - The vector to subtract.
  2362. * @return {Vector2} A reference to this vector.
  2363. */
  2364. sub( v ) {
  2365. this.x -= v.x;
  2366. this.y -= v.y;
  2367. return this;
  2368. }
  2369. /**
  2370. * Subtracts the given scalar value from all components of this instance.
  2371. *
  2372. * @param {number} s - The scalar to subtract.
  2373. * @return {Vector2} A reference to this vector.
  2374. */
  2375. subScalar( s ) {
  2376. this.x -= s;
  2377. this.y -= s;
  2378. return this;
  2379. }
  2380. /**
  2381. * Subtracts the given vectors and stores the result in this instance.
  2382. *
  2383. * @param {Vector2} a - The first vector.
  2384. * @param {Vector2} b - The second vector.
  2385. * @return {Vector2} A reference to this vector.
  2386. */
  2387. subVectors( a, b ) {
  2388. this.x = a.x - b.x;
  2389. this.y = a.y - b.y;
  2390. return this;
  2391. }
  2392. /**
  2393. * Multiplies the given vector with this instance.
  2394. *
  2395. * @param {Vector2} v - The vector to multiply.
  2396. * @return {Vector2} A reference to this vector.
  2397. */
  2398. multiply( v ) {
  2399. this.x *= v.x;
  2400. this.y *= v.y;
  2401. return this;
  2402. }
  2403. /**
  2404. * Multiplies the given scalar value with all components of this instance.
  2405. *
  2406. * @param {number} scalar - The scalar to multiply.
  2407. * @return {Vector2} A reference to this vector.
  2408. */
  2409. multiplyScalar( scalar ) {
  2410. this.x *= scalar;
  2411. this.y *= scalar;
  2412. return this;
  2413. }
  2414. /**
  2415. * Divides this instance by the given vector.
  2416. *
  2417. * @param {Vector2} v - The vector to divide.
  2418. * @return {Vector2} A reference to this vector.
  2419. */
  2420. divide( v ) {
  2421. this.x /= v.x;
  2422. this.y /= v.y;
  2423. return this;
  2424. }
  2425. /**
  2426. * Divides this vector by the given scalar.
  2427. *
  2428. * @param {number} scalar - The scalar to divide.
  2429. * @return {Vector2} A reference to this vector.
  2430. */
  2431. divideScalar( scalar ) {
  2432. return this.multiplyScalar( 1 / scalar );
  2433. }
  2434. /**
  2435. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2436. * the given 3x3 matrix.
  2437. *
  2438. * @param {Matrix3} m - The matrix to apply.
  2439. * @return {Vector2} A reference to this vector.
  2440. */
  2441. applyMatrix3( m ) {
  2442. const x = this.x, y = this.y;
  2443. const e = m.elements;
  2444. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2445. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2446. return this;
  2447. }
  2448. /**
  2449. * If this vector's x or y value is greater than the given vector's x or y
  2450. * value, replace that value with the corresponding min value.
  2451. *
  2452. * @param {Vector2} v - The vector.
  2453. * @return {Vector2} A reference to this vector.
  2454. */
  2455. min( v ) {
  2456. this.x = Math.min( this.x, v.x );
  2457. this.y = Math.min( this.y, v.y );
  2458. return this;
  2459. }
  2460. /**
  2461. * If this vector's x or y value is less than the given vector's x or y
  2462. * value, replace that value with the corresponding max value.
  2463. *
  2464. * @param {Vector2} v - The vector.
  2465. * @return {Vector2} A reference to this vector.
  2466. */
  2467. max( v ) {
  2468. this.x = Math.max( this.x, v.x );
  2469. this.y = Math.max( this.y, v.y );
  2470. return this;
  2471. }
  2472. /**
  2473. * If this vector's x or y value is greater than the max vector's x or y
  2474. * value, it is replaced by the corresponding value.
  2475. * If this vector's x or y value is less than the min vector's x or y value,
  2476. * it is replaced by the corresponding value.
  2477. *
  2478. * @param {Vector2} min - The minimum x and y values.
  2479. * @param {Vector2} max - The maximum x and y values in the desired range.
  2480. * @return {Vector2} A reference to this vector.
  2481. */
  2482. clamp( min, max ) {
  2483. // assumes min < max, componentwise
  2484. this.x = clamp( this.x, min.x, max.x );
  2485. this.y = clamp( this.y, min.y, max.y );
  2486. return this;
  2487. }
  2488. /**
  2489. * If this vector's x or y values are greater than the max value, they are
  2490. * replaced by the max value.
  2491. * If this vector's x or y values are less than the min value, they are
  2492. * replaced by the min value.
  2493. *
  2494. * @param {number} minVal - The minimum value the components will be clamped to.
  2495. * @param {number} maxVal - The maximum value the components will be clamped to.
  2496. * @return {Vector2} A reference to this vector.
  2497. */
  2498. clampScalar( minVal, maxVal ) {
  2499. this.x = clamp( this.x, minVal, maxVal );
  2500. this.y = clamp( this.y, minVal, maxVal );
  2501. return this;
  2502. }
  2503. /**
  2504. * If this vector's length is greater than the max value, it is replaced by
  2505. * the max value.
  2506. * If this vector's length is less than the min value, it is replaced by the
  2507. * min value.
  2508. *
  2509. * @param {number} min - The minimum value the vector length will be clamped to.
  2510. * @param {number} max - The maximum value the vector length will be clamped to.
  2511. * @return {Vector2} A reference to this vector.
  2512. */
  2513. clampLength( min, max ) {
  2514. const length = this.length();
  2515. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2516. }
  2517. /**
  2518. * The components of this vector are rounded down to the nearest integer value.
  2519. *
  2520. * @return {Vector2} A reference to this vector.
  2521. */
  2522. floor() {
  2523. this.x = Math.floor( this.x );
  2524. this.y = Math.floor( this.y );
  2525. return this;
  2526. }
  2527. /**
  2528. * The components of this vector are rounded up to the nearest integer value.
  2529. *
  2530. * @return {Vector2} A reference to this vector.
  2531. */
  2532. ceil() {
  2533. this.x = Math.ceil( this.x );
  2534. this.y = Math.ceil( this.y );
  2535. return this;
  2536. }
  2537. /**
  2538. * The components of this vector are rounded to the nearest integer value
  2539. *
  2540. * @return {Vector2} A reference to this vector.
  2541. */
  2542. round() {
  2543. this.x = Math.round( this.x );
  2544. this.y = Math.round( this.y );
  2545. return this;
  2546. }
  2547. /**
  2548. * The components of this vector are rounded towards zero (up if negative,
  2549. * down if positive) to an integer value.
  2550. *
  2551. * @return {Vector2} A reference to this vector.
  2552. */
  2553. roundToZero() {
  2554. this.x = Math.trunc( this.x );
  2555. this.y = Math.trunc( this.y );
  2556. return this;
  2557. }
  2558. /**
  2559. * Inverts this vector - i.e. sets x = -x and y = -y.
  2560. *
  2561. * @return {Vector2} A reference to this vector.
  2562. */
  2563. negate() {
  2564. this.x = - this.x;
  2565. this.y = - this.y;
  2566. return this;
  2567. }
  2568. /**
  2569. * Calculates the dot product of the given vector with this instance.
  2570. *
  2571. * @param {Vector2} v - The vector to compute the dot product with.
  2572. * @return {number} The result of the dot product.
  2573. */
  2574. dot( v ) {
  2575. return this.x * v.x + this.y * v.y;
  2576. }
  2577. /**
  2578. * Calculates the cross product of the given vector with this instance.
  2579. *
  2580. * @param {Vector2} v - The vector to compute the cross product with.
  2581. * @return {number} The result of the cross product.
  2582. */
  2583. cross( v ) {
  2584. return this.x * v.y - this.y * v.x;
  2585. }
  2586. /**
  2587. * Computes the square of the Euclidean length (straight-line length) from
  2588. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2589. * compare the length squared instead as it is slightly more efficient to calculate.
  2590. *
  2591. * @return {number} The square length of this vector.
  2592. */
  2593. lengthSq() {
  2594. return this.x * this.x + this.y * this.y;
  2595. }
  2596. /**
  2597. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2598. *
  2599. * @return {number} The length of this vector.
  2600. */
  2601. length() {
  2602. return Math.sqrt( this.x * this.x + this.y * this.y );
  2603. }
  2604. /**
  2605. * Computes the Manhattan length of this vector.
  2606. *
  2607. * @return {number} The length of this vector.
  2608. */
  2609. manhattanLength() {
  2610. return Math.abs( this.x ) + Math.abs( this.y );
  2611. }
  2612. /**
  2613. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2614. * with the same direction as this one, but with a vector length of `1`.
  2615. *
  2616. * @return {Vector2} A reference to this vector.
  2617. */
  2618. normalize() {
  2619. return this.divideScalar( this.length() || 1 );
  2620. }
  2621. /**
  2622. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2623. *
  2624. * @return {number} The angle in radians.
  2625. */
  2626. angle() {
  2627. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2628. return angle;
  2629. }
  2630. /**
  2631. * Returns the angle between the given vector and this instance in radians.
  2632. *
  2633. * @param {Vector2} v - The vector to compute the angle with.
  2634. * @return {number} The angle in radians.
  2635. */
  2636. angleTo( v ) {
  2637. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2638. if ( denominator === 0 ) return Math.PI / 2;
  2639. const theta = this.dot( v ) / denominator;
  2640. // clamp, to handle numerical problems
  2641. return Math.acos( clamp( theta, -1, 1 ) );
  2642. }
  2643. /**
  2644. * Computes the distance from the given vector to this instance.
  2645. *
  2646. * @param {Vector2} v - The vector to compute the distance to.
  2647. * @return {number} The distance.
  2648. */
  2649. distanceTo( v ) {
  2650. return Math.sqrt( this.distanceToSquared( v ) );
  2651. }
  2652. /**
  2653. * Computes the squared distance from the given vector to this instance.
  2654. * If you are just comparing the distance with another distance, you should compare
  2655. * the distance squared instead as it is slightly more efficient to calculate.
  2656. *
  2657. * @param {Vector2} v - The vector to compute the squared distance to.
  2658. * @return {number} The squared distance.
  2659. */
  2660. distanceToSquared( v ) {
  2661. const dx = this.x - v.x, dy = this.y - v.y;
  2662. return dx * dx + dy * dy;
  2663. }
  2664. /**
  2665. * Computes the Manhattan distance from the given vector to this instance.
  2666. *
  2667. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2668. * @return {number} The Manhattan distance.
  2669. */
  2670. manhattanDistanceTo( v ) {
  2671. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2672. }
  2673. /**
  2674. * Sets this vector to a vector with the same direction as this one, but
  2675. * with the specified length.
  2676. *
  2677. * @param {number} length - The new length of this vector.
  2678. * @return {Vector2} A reference to this vector.
  2679. */
  2680. setLength( length ) {
  2681. return this.normalize().multiplyScalar( length );
  2682. }
  2683. /**
  2684. * Linearly interpolates between the given vector and this instance, where
  2685. * alpha is the percent distance along the line - alpha = 0 will be this
  2686. * vector, and alpha = 1 will be the given one.
  2687. *
  2688. * @param {Vector2} v - The vector to interpolate towards.
  2689. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2690. * @return {Vector2} A reference to this vector.
  2691. */
  2692. lerp( v, alpha ) {
  2693. this.x += ( v.x - this.x ) * alpha;
  2694. this.y += ( v.y - this.y ) * alpha;
  2695. return this;
  2696. }
  2697. /**
  2698. * Linearly interpolates between the given vectors, where alpha is the percent
  2699. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2700. * be the second one. The result is stored in this instance.
  2701. *
  2702. * @param {Vector2} v1 - The first vector.
  2703. * @param {Vector2} v2 - The second vector.
  2704. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2705. * @return {Vector2} A reference to this vector.
  2706. */
  2707. lerpVectors( v1, v2, alpha ) {
  2708. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2709. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2710. return this;
  2711. }
  2712. /**
  2713. * Returns `true` if this vector is equal with the given one.
  2714. *
  2715. * @param {Vector2} v - The vector to test for equality.
  2716. * @return {boolean} Whether this vector is equal with the given one.
  2717. */
  2718. equals( v ) {
  2719. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2720. }
  2721. /**
  2722. * Sets this vector's x value to be `array[ offset ]` and y
  2723. * value to be `array[ offset + 1 ]`.
  2724. *
  2725. * @param {Array<number>} array - An array holding the vector component values.
  2726. * @param {number} [offset=0] - The offset into the array.
  2727. * @return {Vector2} A reference to this vector.
  2728. */
  2729. fromArray( array, offset = 0 ) {
  2730. this.x = array[ offset ];
  2731. this.y = array[ offset + 1 ];
  2732. return this;
  2733. }
  2734. /**
  2735. * Writes the components of this vector to the given array. If no array is provided,
  2736. * the method returns a new instance.
  2737. *
  2738. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2739. * @param {number} [offset=0] - Index of the first element in the array.
  2740. * @return {Array<number>} The vector components.
  2741. */
  2742. toArray( array = [], offset = 0 ) {
  2743. array[ offset ] = this.x;
  2744. array[ offset + 1 ] = this.y;
  2745. return array;
  2746. }
  2747. /**
  2748. * Sets the components of this vector from the given buffer attribute.
  2749. *
  2750. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2751. * @param {number} index - The index into the attribute.
  2752. * @return {Vector2} A reference to this vector.
  2753. */
  2754. fromBufferAttribute( attribute, index ) {
  2755. this.x = attribute.getX( index );
  2756. this.y = attribute.getY( index );
  2757. return this;
  2758. }
  2759. /**
  2760. * Rotates this vector around the given center by the given angle.
  2761. *
  2762. * @param {Vector2} center - The point around which to rotate.
  2763. * @param {number} angle - The angle to rotate, in radians.
  2764. * @return {Vector2} A reference to this vector.
  2765. */
  2766. rotateAround( center, angle ) {
  2767. const c = Math.cos( angle ), s = Math.sin( angle );
  2768. const x = this.x - center.x;
  2769. const y = this.y - center.y;
  2770. this.x = x * c - y * s + center.x;
  2771. this.y = x * s + y * c + center.y;
  2772. return this;
  2773. }
  2774. /**
  2775. * Sets each component of this vector to a pseudo-random value between `0` and
  2776. * `1`, excluding `1`.
  2777. *
  2778. * @return {Vector2} A reference to this vector.
  2779. */
  2780. random() {
  2781. this.x = Math.random();
  2782. this.y = Math.random();
  2783. return this;
  2784. }
  2785. *[ Symbol.iterator ]() {
  2786. yield this.x;
  2787. yield this.y;
  2788. }
  2789. }
  2790. /**
  2791. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2792. *
  2793. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2794. * the corresponding order.
  2795. *
  2796. * Note that three.js expects Quaternions to be normalized.
  2797. * ```js
  2798. * const quaternion = new THREE.Quaternion();
  2799. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2800. *
  2801. * const vector = new THREE.Vector3( 1, 0, 0 );
  2802. * vector.applyQuaternion( quaternion );
  2803. * ```
  2804. */
  2805. class Quaternion {
  2806. /**
  2807. * Constructs a new quaternion.
  2808. *
  2809. * @param {number} [x=0] - The x value of this quaternion.
  2810. * @param {number} [y=0] - The y value of this quaternion.
  2811. * @param {number} [z=0] - The z value of this quaternion.
  2812. * @param {number} [w=1] - The w value of this quaternion.
  2813. */
  2814. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2815. /**
  2816. * This flag can be used for type testing.
  2817. *
  2818. * @type {boolean}
  2819. * @readonly
  2820. * @default true
  2821. */
  2822. this.isQuaternion = true;
  2823. this._x = x;
  2824. this._y = y;
  2825. this._z = z;
  2826. this._w = w;
  2827. }
  2828. /**
  2829. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2830. * quaternion data are managed in flat arrays.
  2831. *
  2832. * @param {Array<number>} dst - The destination array.
  2833. * @param {number} dstOffset - An offset into the destination array.
  2834. * @param {Array<number>} src0 - The source array of the first quaternion.
  2835. * @param {number} srcOffset0 - An offset into the first source array.
  2836. * @param {Array<number>} src1 - The source array of the second quaternion.
  2837. * @param {number} srcOffset1 - An offset into the second source array.
  2838. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2839. * @see {@link Quaternion#slerp}
  2840. */
  2841. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2842. // fuzz-free, array-based Quaternion SLERP operation
  2843. let x0 = src0[ srcOffset0 + 0 ],
  2844. y0 = src0[ srcOffset0 + 1 ],
  2845. z0 = src0[ srcOffset0 + 2 ],
  2846. w0 = src0[ srcOffset0 + 3 ];
  2847. const x1 = src1[ srcOffset1 + 0 ],
  2848. y1 = src1[ srcOffset1 + 1 ],
  2849. z1 = src1[ srcOffset1 + 2 ],
  2850. w1 = src1[ srcOffset1 + 3 ];
  2851. if ( t === 0 ) {
  2852. dst[ dstOffset + 0 ] = x0;
  2853. dst[ dstOffset + 1 ] = y0;
  2854. dst[ dstOffset + 2 ] = z0;
  2855. dst[ dstOffset + 3 ] = w0;
  2856. return;
  2857. }
  2858. if ( t === 1 ) {
  2859. dst[ dstOffset + 0 ] = x1;
  2860. dst[ dstOffset + 1 ] = y1;
  2861. dst[ dstOffset + 2 ] = z1;
  2862. dst[ dstOffset + 3 ] = w1;
  2863. return;
  2864. }
  2865. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2866. let s = 1 - t;
  2867. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2868. dir = ( cos >= 0 ? 1 : -1 ),
  2869. sqrSin = 1 - cos * cos;
  2870. // Skip the Slerp for tiny steps to avoid numeric problems:
  2871. if ( sqrSin > Number.EPSILON ) {
  2872. const sin = Math.sqrt( sqrSin ),
  2873. len = Math.atan2( sin, cos * dir );
  2874. s = Math.sin( s * len ) / sin;
  2875. t = Math.sin( t * len ) / sin;
  2876. }
  2877. const tDir = t * dir;
  2878. x0 = x0 * s + x1 * tDir;
  2879. y0 = y0 * s + y1 * tDir;
  2880. z0 = z0 * s + z1 * tDir;
  2881. w0 = w0 * s + w1 * tDir;
  2882. // Normalize in case we just did a lerp:
  2883. if ( s === 1 - t ) {
  2884. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2885. x0 *= f;
  2886. y0 *= f;
  2887. z0 *= f;
  2888. w0 *= f;
  2889. }
  2890. }
  2891. dst[ dstOffset ] = x0;
  2892. dst[ dstOffset + 1 ] = y0;
  2893. dst[ dstOffset + 2 ] = z0;
  2894. dst[ dstOffset + 3 ] = w0;
  2895. }
  2896. /**
  2897. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2898. * in flat arrays.
  2899. *
  2900. * @param {Array<number>} dst - The destination array.
  2901. * @param {number} dstOffset - An offset into the destination array.
  2902. * @param {Array<number>} src0 - The source array of the first quaternion.
  2903. * @param {number} srcOffset0 - An offset into the first source array.
  2904. * @param {Array<number>} src1 - The source array of the second quaternion.
  2905. * @param {number} srcOffset1 - An offset into the second source array.
  2906. * @return {Array<number>} The destination array.
  2907. * @see {@link Quaternion#multiplyQuaternions}.
  2908. */
  2909. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2910. const x0 = src0[ srcOffset0 ];
  2911. const y0 = src0[ srcOffset0 + 1 ];
  2912. const z0 = src0[ srcOffset0 + 2 ];
  2913. const w0 = src0[ srcOffset0 + 3 ];
  2914. const x1 = src1[ srcOffset1 ];
  2915. const y1 = src1[ srcOffset1 + 1 ];
  2916. const z1 = src1[ srcOffset1 + 2 ];
  2917. const w1 = src1[ srcOffset1 + 3 ];
  2918. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2919. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2920. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2921. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2922. return dst;
  2923. }
  2924. /**
  2925. * The x value of this quaternion.
  2926. *
  2927. * @type {number}
  2928. * @default 0
  2929. */
  2930. get x() {
  2931. return this._x;
  2932. }
  2933. set x( value ) {
  2934. this._x = value;
  2935. this._onChangeCallback();
  2936. }
  2937. /**
  2938. * The y value of this quaternion.
  2939. *
  2940. * @type {number}
  2941. * @default 0
  2942. */
  2943. get y() {
  2944. return this._y;
  2945. }
  2946. set y( value ) {
  2947. this._y = value;
  2948. this._onChangeCallback();
  2949. }
  2950. /**
  2951. * The z value of this quaternion.
  2952. *
  2953. * @type {number}
  2954. * @default 0
  2955. */
  2956. get z() {
  2957. return this._z;
  2958. }
  2959. set z( value ) {
  2960. this._z = value;
  2961. this._onChangeCallback();
  2962. }
  2963. /**
  2964. * The w value of this quaternion.
  2965. *
  2966. * @type {number}
  2967. * @default 1
  2968. */
  2969. get w() {
  2970. return this._w;
  2971. }
  2972. set w( value ) {
  2973. this._w = value;
  2974. this._onChangeCallback();
  2975. }
  2976. /**
  2977. * Sets the quaternion components.
  2978. *
  2979. * @param {number} x - The x value of this quaternion.
  2980. * @param {number} y - The y value of this quaternion.
  2981. * @param {number} z - The z value of this quaternion.
  2982. * @param {number} w - The w value of this quaternion.
  2983. * @return {Quaternion} A reference to this quaternion.
  2984. */
  2985. set( x, y, z, w ) {
  2986. this._x = x;
  2987. this._y = y;
  2988. this._z = z;
  2989. this._w = w;
  2990. this._onChangeCallback();
  2991. return this;
  2992. }
  2993. /**
  2994. * Returns a new quaternion with copied values from this instance.
  2995. *
  2996. * @return {Quaternion} A clone of this instance.
  2997. */
  2998. clone() {
  2999. return new this.constructor( this._x, this._y, this._z, this._w );
  3000. }
  3001. /**
  3002. * Copies the values of the given quaternion to this instance.
  3003. *
  3004. * @param {Quaternion} quaternion - The quaternion to copy.
  3005. * @return {Quaternion} A reference to this quaternion.
  3006. */
  3007. copy( quaternion ) {
  3008. this._x = quaternion.x;
  3009. this._y = quaternion.y;
  3010. this._z = quaternion.z;
  3011. this._w = quaternion.w;
  3012. this._onChangeCallback();
  3013. return this;
  3014. }
  3015. /**
  3016. * Sets this quaternion from the rotation specified by the given
  3017. * Euler angles.
  3018. *
  3019. * @param {Euler} euler - The Euler angles.
  3020. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3021. * @return {Quaternion} A reference to this quaternion.
  3022. */
  3023. setFromEuler( euler, update = true ) {
  3024. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3025. // http://www.mathworks.com/matlabcentral/fileexchange/
  3026. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3027. // content/SpinCalc.m
  3028. const cos = Math.cos;
  3029. const sin = Math.sin;
  3030. const c1 = cos( x / 2 );
  3031. const c2 = cos( y / 2 );
  3032. const c3 = cos( z / 2 );
  3033. const s1 = sin( x / 2 );
  3034. const s2 = sin( y / 2 );
  3035. const s3 = sin( z / 2 );
  3036. switch ( order ) {
  3037. case 'XYZ':
  3038. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3039. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3040. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3041. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3042. break;
  3043. case 'YXZ':
  3044. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3045. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3046. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3047. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3048. break;
  3049. case 'ZXY':
  3050. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3051. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3052. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3053. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3054. break;
  3055. case 'ZYX':
  3056. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3057. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3058. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3059. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3060. break;
  3061. case 'YZX':
  3062. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3063. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3064. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3065. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3066. break;
  3067. case 'XZY':
  3068. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3069. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3070. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3071. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3072. break;
  3073. default:
  3074. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3075. }
  3076. if ( update === true ) this._onChangeCallback();
  3077. return this;
  3078. }
  3079. /**
  3080. * Sets this quaternion from the given axis and angle.
  3081. *
  3082. * @param {Vector3} axis - The normalized axis.
  3083. * @param {number} angle - The angle in radians.
  3084. * @return {Quaternion} A reference to this quaternion.
  3085. */
  3086. setFromAxisAngle( axis, angle ) {
  3087. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3088. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3089. this._x = axis.x * s;
  3090. this._y = axis.y * s;
  3091. this._z = axis.z * s;
  3092. this._w = Math.cos( halfAngle );
  3093. this._onChangeCallback();
  3094. return this;
  3095. }
  3096. /**
  3097. * Sets this quaternion from the given rotation matrix.
  3098. *
  3099. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3100. * @return {Quaternion} A reference to this quaternion.
  3101. */
  3102. setFromRotationMatrix( m ) {
  3103. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3104. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3105. const te = m.elements,
  3106. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3107. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3108. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3109. trace = m11 + m22 + m33;
  3110. if ( trace > 0 ) {
  3111. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3112. this._w = 0.25 / s;
  3113. this._x = ( m32 - m23 ) * s;
  3114. this._y = ( m13 - m31 ) * s;
  3115. this._z = ( m21 - m12 ) * s;
  3116. } else if ( m11 > m22 && m11 > m33 ) {
  3117. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3118. this._w = ( m32 - m23 ) / s;
  3119. this._x = 0.25 * s;
  3120. this._y = ( m12 + m21 ) / s;
  3121. this._z = ( m13 + m31 ) / s;
  3122. } else if ( m22 > m33 ) {
  3123. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3124. this._w = ( m13 - m31 ) / s;
  3125. this._x = ( m12 + m21 ) / s;
  3126. this._y = 0.25 * s;
  3127. this._z = ( m23 + m32 ) / s;
  3128. } else {
  3129. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3130. this._w = ( m21 - m12 ) / s;
  3131. this._x = ( m13 + m31 ) / s;
  3132. this._y = ( m23 + m32 ) / s;
  3133. this._z = 0.25 * s;
  3134. }
  3135. this._onChangeCallback();
  3136. return this;
  3137. }
  3138. /**
  3139. * Sets this quaternion to the rotation required to rotate the direction vector
  3140. * `vFrom` to the direction vector `vTo`.
  3141. *
  3142. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3143. * @param {Vector3} vTo - The second (normalized) direction vector.
  3144. * @return {Quaternion} A reference to this quaternion.
  3145. */
  3146. setFromUnitVectors( vFrom, vTo ) {
  3147. // assumes direction vectors vFrom and vTo are normalized
  3148. let r = vFrom.dot( vTo ) + 1;
  3149. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3150. // vFrom and vTo point in opposite directions
  3151. r = 0;
  3152. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3153. this._x = - vFrom.y;
  3154. this._y = vFrom.x;
  3155. this._z = 0;
  3156. this._w = r;
  3157. } else {
  3158. this._x = 0;
  3159. this._y = - vFrom.z;
  3160. this._z = vFrom.y;
  3161. this._w = r;
  3162. }
  3163. } else {
  3164. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3165. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3166. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3167. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3168. this._w = r;
  3169. }
  3170. return this.normalize();
  3171. }
  3172. /**
  3173. * Returns the angle between this quaternion and the given one in radians.
  3174. *
  3175. * @param {Quaternion} q - The quaternion to compute the angle with.
  3176. * @return {number} The angle in radians.
  3177. */
  3178. angleTo( q ) {
  3179. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3180. }
  3181. /**
  3182. * Rotates this quaternion by a given angular step to the given quaternion.
  3183. * The method ensures that the final quaternion will not overshoot `q`.
  3184. *
  3185. * @param {Quaternion} q - The target quaternion.
  3186. * @param {number} step - The angular step in radians.
  3187. * @return {Quaternion} A reference to this quaternion.
  3188. */
  3189. rotateTowards( q, step ) {
  3190. const angle = this.angleTo( q );
  3191. if ( angle === 0 ) return this;
  3192. const t = Math.min( 1, step / angle );
  3193. this.slerp( q, t );
  3194. return this;
  3195. }
  3196. /**
  3197. * Sets this quaternion to the identity quaternion; that is, to the
  3198. * quaternion that represents "no rotation".
  3199. *
  3200. * @return {Quaternion} A reference to this quaternion.
  3201. */
  3202. identity() {
  3203. return this.set( 0, 0, 0, 1 );
  3204. }
  3205. /**
  3206. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3207. * quaternion is assumed to have unit length.
  3208. *
  3209. * @return {Quaternion} A reference to this quaternion.
  3210. */
  3211. invert() {
  3212. return this.conjugate();
  3213. }
  3214. /**
  3215. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3216. * quaternion represents the same rotation in the opposite direction about
  3217. * the rotational axis.
  3218. *
  3219. * @return {Quaternion} A reference to this quaternion.
  3220. */
  3221. conjugate() {
  3222. this._x *= -1;
  3223. this._y *= -1;
  3224. this._z *= -1;
  3225. this._onChangeCallback();
  3226. return this;
  3227. }
  3228. /**
  3229. * Calculates the dot product of this quaternion and the given one.
  3230. *
  3231. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3232. * @return {number} The result of the dot product.
  3233. */
  3234. dot( v ) {
  3235. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3236. }
  3237. /**
  3238. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3239. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3240. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3241. * {@link Quaternion#length}.
  3242. *
  3243. * @return {number} The squared Euclidean length.
  3244. */
  3245. lengthSq() {
  3246. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3247. }
  3248. /**
  3249. * Computes the Euclidean length (straight-line length) of this quaternion,
  3250. * considered as a 4 dimensional vector.
  3251. *
  3252. * @return {number} The Euclidean length.
  3253. */
  3254. length() {
  3255. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3256. }
  3257. /**
  3258. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3259. * the same rotation as this one, but has a length equal to `1`.
  3260. *
  3261. * @return {Quaternion} A reference to this quaternion.
  3262. */
  3263. normalize() {
  3264. let l = this.length();
  3265. if ( l === 0 ) {
  3266. this._x = 0;
  3267. this._y = 0;
  3268. this._z = 0;
  3269. this._w = 1;
  3270. } else {
  3271. l = 1 / l;
  3272. this._x = this._x * l;
  3273. this._y = this._y * l;
  3274. this._z = this._z * l;
  3275. this._w = this._w * l;
  3276. }
  3277. this._onChangeCallback();
  3278. return this;
  3279. }
  3280. /**
  3281. * Multiplies this quaternion by the given one.
  3282. *
  3283. * @param {Quaternion} q - The quaternion.
  3284. * @return {Quaternion} A reference to this quaternion.
  3285. */
  3286. multiply( q ) {
  3287. return this.multiplyQuaternions( this, q );
  3288. }
  3289. /**
  3290. * Pre-multiplies this quaternion by the given one.
  3291. *
  3292. * @param {Quaternion} q - The quaternion.
  3293. * @return {Quaternion} A reference to this quaternion.
  3294. */
  3295. premultiply( q ) {
  3296. return this.multiplyQuaternions( q, this );
  3297. }
  3298. /**
  3299. * Multiplies the given quaternions and stores the result in this instance.
  3300. *
  3301. * @param {Quaternion} a - The first quaternion.
  3302. * @param {Quaternion} b - The second quaternion.
  3303. * @return {Quaternion} A reference to this quaternion.
  3304. */
  3305. multiplyQuaternions( a, b ) {
  3306. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3307. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3308. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3309. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3310. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3311. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3312. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3313. this._onChangeCallback();
  3314. return this;
  3315. }
  3316. /**
  3317. * Performs a spherical linear interpolation between quaternions.
  3318. *
  3319. * @param {Quaternion} qb - The target quaternion.
  3320. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3321. * @return {Quaternion} A reference to this quaternion.
  3322. */
  3323. slerp( qb, t ) {
  3324. if ( t === 0 ) return this;
  3325. if ( t === 1 ) return this.copy( qb );
  3326. const x = this._x, y = this._y, z = this._z, w = this._w;
  3327. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3328. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3329. if ( cosHalfTheta < 0 ) {
  3330. this._w = - qb._w;
  3331. this._x = - qb._x;
  3332. this._y = - qb._y;
  3333. this._z = - qb._z;
  3334. cosHalfTheta = - cosHalfTheta;
  3335. } else {
  3336. this.copy( qb );
  3337. }
  3338. if ( cosHalfTheta >= 1.0 ) {
  3339. this._w = w;
  3340. this._x = x;
  3341. this._y = y;
  3342. this._z = z;
  3343. return this;
  3344. }
  3345. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3346. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3347. const s = 1 - t;
  3348. this._w = s * w + t * this._w;
  3349. this._x = s * x + t * this._x;
  3350. this._y = s * y + t * this._y;
  3351. this._z = s * z + t * this._z;
  3352. this.normalize(); // normalize calls _onChangeCallback()
  3353. return this;
  3354. }
  3355. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3356. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3357. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3358. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3359. this._w = ( w * ratioA + this._w * ratioB );
  3360. this._x = ( x * ratioA + this._x * ratioB );
  3361. this._y = ( y * ratioA + this._y * ratioB );
  3362. this._z = ( z * ratioA + this._z * ratioB );
  3363. this._onChangeCallback();
  3364. return this;
  3365. }
  3366. /**
  3367. * Performs a spherical linear interpolation between the given quaternions
  3368. * and stores the result in this quaternion.
  3369. *
  3370. * @param {Quaternion} qa - The source quaternion.
  3371. * @param {Quaternion} qb - The target quaternion.
  3372. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3373. * @return {Quaternion} A reference to this quaternion.
  3374. */
  3375. slerpQuaternions( qa, qb, t ) {
  3376. return this.copy( qa ).slerp( qb, t );
  3377. }
  3378. /**
  3379. * Sets this quaternion to a uniformly random, normalized quaternion.
  3380. *
  3381. * @return {Quaternion} A reference to this quaternion.
  3382. */
  3383. random() {
  3384. // Ken Shoemake
  3385. // Uniform random rotations
  3386. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3387. const theta1 = 2 * Math.PI * Math.random();
  3388. const theta2 = 2 * Math.PI * Math.random();
  3389. const x0 = Math.random();
  3390. const r1 = Math.sqrt( 1 - x0 );
  3391. const r2 = Math.sqrt( x0 );
  3392. return this.set(
  3393. r1 * Math.sin( theta1 ),
  3394. r1 * Math.cos( theta1 ),
  3395. r2 * Math.sin( theta2 ),
  3396. r2 * Math.cos( theta2 ),
  3397. );
  3398. }
  3399. /**
  3400. * Returns `true` if this quaternion is equal with the given one.
  3401. *
  3402. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3403. * @return {boolean} Whether this quaternion is equal with the given one.
  3404. */
  3405. equals( quaternion ) {
  3406. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3407. }
  3408. /**
  3409. * Sets this quaternion's components from the given array.
  3410. *
  3411. * @param {Array<number>} array - An array holding the quaternion component values.
  3412. * @param {number} [offset=0] - The offset into the array.
  3413. * @return {Quaternion} A reference to this quaternion.
  3414. */
  3415. fromArray( array, offset = 0 ) {
  3416. this._x = array[ offset ];
  3417. this._y = array[ offset + 1 ];
  3418. this._z = array[ offset + 2 ];
  3419. this._w = array[ offset + 3 ];
  3420. this._onChangeCallback();
  3421. return this;
  3422. }
  3423. /**
  3424. * Writes the components of this quaternion to the given array. If no array is provided,
  3425. * the method returns a new instance.
  3426. *
  3427. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3428. * @param {number} [offset=0] - Index of the first element in the array.
  3429. * @return {Array<number>} The quaternion components.
  3430. */
  3431. toArray( array = [], offset = 0 ) {
  3432. array[ offset ] = this._x;
  3433. array[ offset + 1 ] = this._y;
  3434. array[ offset + 2 ] = this._z;
  3435. array[ offset + 3 ] = this._w;
  3436. return array;
  3437. }
  3438. /**
  3439. * Sets the components of this quaternion from the given buffer attribute.
  3440. *
  3441. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3442. * @param {number} index - The index into the attribute.
  3443. * @return {Quaternion} A reference to this quaternion.
  3444. */
  3445. fromBufferAttribute( attribute, index ) {
  3446. this._x = attribute.getX( index );
  3447. this._y = attribute.getY( index );
  3448. this._z = attribute.getZ( index );
  3449. this._w = attribute.getW( index );
  3450. this._onChangeCallback();
  3451. return this;
  3452. }
  3453. /**
  3454. * This methods defines the serialization result of this class. Returns the
  3455. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3456. *
  3457. * @return {Array<number>} The serialized quaternion.
  3458. */
  3459. toJSON() {
  3460. return this.toArray();
  3461. }
  3462. _onChange( callback ) {
  3463. this._onChangeCallback = callback;
  3464. return this;
  3465. }
  3466. _onChangeCallback() {}
  3467. *[ Symbol.iterator ]() {
  3468. yield this._x;
  3469. yield this._y;
  3470. yield this._z;
  3471. yield this._w;
  3472. }
  3473. }
  3474. /**
  3475. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3476. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3477. *
  3478. * - A point in 3D space.
  3479. * - A direction and length in 3D space. In three.js the length will
  3480. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3481. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3482. * - Any arbitrary ordered triplet of numbers.
  3483. *
  3484. * There are other things a 3D vector can be used to represent, such as
  3485. * momentum vectors and so on, however these are the most
  3486. * common uses in three.js.
  3487. *
  3488. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3489. * the corresponding order.
  3490. * ```js
  3491. * const a = new THREE.Vector3( 0, 1, 0 );
  3492. *
  3493. * //no arguments; will be initialised to (0, 0, 0)
  3494. * const b = new THREE.Vector3( );
  3495. *
  3496. * const d = a.distanceTo( b );
  3497. * ```
  3498. */
  3499. class Vector3 {
  3500. /**
  3501. * Constructs a new 3D vector.
  3502. *
  3503. * @param {number} [x=0] - The x value of this vector.
  3504. * @param {number} [y=0] - The y value of this vector.
  3505. * @param {number} [z=0] - The z value of this vector.
  3506. */
  3507. constructor( x = 0, y = 0, z = 0 ) {
  3508. /**
  3509. * This flag can be used for type testing.
  3510. *
  3511. * @type {boolean}
  3512. * @readonly
  3513. * @default true
  3514. */
  3515. Vector3.prototype.isVector3 = true;
  3516. /**
  3517. * The x value of this vector.
  3518. *
  3519. * @type {number}
  3520. */
  3521. this.x = x;
  3522. /**
  3523. * The y value of this vector.
  3524. *
  3525. * @type {number}
  3526. */
  3527. this.y = y;
  3528. /**
  3529. * The z value of this vector.
  3530. *
  3531. * @type {number}
  3532. */
  3533. this.z = z;
  3534. }
  3535. /**
  3536. * Sets the vector components.
  3537. *
  3538. * @param {number} x - The value of the x component.
  3539. * @param {number} y - The value of the y component.
  3540. * @param {number} z - The value of the z component.
  3541. * @return {Vector3} A reference to this vector.
  3542. */
  3543. set( x, y, z ) {
  3544. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3545. this.x = x;
  3546. this.y = y;
  3547. this.z = z;
  3548. return this;
  3549. }
  3550. /**
  3551. * Sets the vector components to the same value.
  3552. *
  3553. * @param {number} scalar - The value to set for all vector components.
  3554. * @return {Vector3} A reference to this vector.
  3555. */
  3556. setScalar( scalar ) {
  3557. this.x = scalar;
  3558. this.y = scalar;
  3559. this.z = scalar;
  3560. return this;
  3561. }
  3562. /**
  3563. * Sets the vector's x component to the given value
  3564. *
  3565. * @param {number} x - The value to set.
  3566. * @return {Vector3} A reference to this vector.
  3567. */
  3568. setX( x ) {
  3569. this.x = x;
  3570. return this;
  3571. }
  3572. /**
  3573. * Sets the vector's y component to the given value
  3574. *
  3575. * @param {number} y - The value to set.
  3576. * @return {Vector3} A reference to this vector.
  3577. */
  3578. setY( y ) {
  3579. this.y = y;
  3580. return this;
  3581. }
  3582. /**
  3583. * Sets the vector's z component to the given value
  3584. *
  3585. * @param {number} z - The value to set.
  3586. * @return {Vector3} A reference to this vector.
  3587. */
  3588. setZ( z ) {
  3589. this.z = z;
  3590. return this;
  3591. }
  3592. /**
  3593. * Allows to set a vector component with an index.
  3594. *
  3595. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3596. * @param {number} value - The value to set.
  3597. * @return {Vector3} A reference to this vector.
  3598. */
  3599. setComponent( index, value ) {
  3600. switch ( index ) {
  3601. case 0: this.x = value; break;
  3602. case 1: this.y = value; break;
  3603. case 2: this.z = value; break;
  3604. default: throw new Error( 'index is out of range: ' + index );
  3605. }
  3606. return this;
  3607. }
  3608. /**
  3609. * Returns the value of the vector component which matches the given index.
  3610. *
  3611. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3612. * @return {number} A vector component value.
  3613. */
  3614. getComponent( index ) {
  3615. switch ( index ) {
  3616. case 0: return this.x;
  3617. case 1: return this.y;
  3618. case 2: return this.z;
  3619. default: throw new Error( 'index is out of range: ' + index );
  3620. }
  3621. }
  3622. /**
  3623. * Returns a new vector with copied values from this instance.
  3624. *
  3625. * @return {Vector3} A clone of this instance.
  3626. */
  3627. clone() {
  3628. return new this.constructor( this.x, this.y, this.z );
  3629. }
  3630. /**
  3631. * Copies the values of the given vector to this instance.
  3632. *
  3633. * @param {Vector3} v - The vector to copy.
  3634. * @return {Vector3} A reference to this vector.
  3635. */
  3636. copy( v ) {
  3637. this.x = v.x;
  3638. this.y = v.y;
  3639. this.z = v.z;
  3640. return this;
  3641. }
  3642. /**
  3643. * Adds the given vector to this instance.
  3644. *
  3645. * @param {Vector3} v - The vector to add.
  3646. * @return {Vector3} A reference to this vector.
  3647. */
  3648. add( v ) {
  3649. this.x += v.x;
  3650. this.y += v.y;
  3651. this.z += v.z;
  3652. return this;
  3653. }
  3654. /**
  3655. * Adds the given scalar value to all components of this instance.
  3656. *
  3657. * @param {number} s - The scalar to add.
  3658. * @return {Vector3} A reference to this vector.
  3659. */
  3660. addScalar( s ) {
  3661. this.x += s;
  3662. this.y += s;
  3663. this.z += s;
  3664. return this;
  3665. }
  3666. /**
  3667. * Adds the given vectors and stores the result in this instance.
  3668. *
  3669. * @param {Vector3} a - The first vector.
  3670. * @param {Vector3} b - The second vector.
  3671. * @return {Vector3} A reference to this vector.
  3672. */
  3673. addVectors( a, b ) {
  3674. this.x = a.x + b.x;
  3675. this.y = a.y + b.y;
  3676. this.z = a.z + b.z;
  3677. return this;
  3678. }
  3679. /**
  3680. * Adds the given vector scaled by the given factor to this instance.
  3681. *
  3682. * @param {Vector3|Vector4} v - The vector.
  3683. * @param {number} s - The factor that scales `v`.
  3684. * @return {Vector3} A reference to this vector.
  3685. */
  3686. addScaledVector( v, s ) {
  3687. this.x += v.x * s;
  3688. this.y += v.y * s;
  3689. this.z += v.z * s;
  3690. return this;
  3691. }
  3692. /**
  3693. * Subtracts the given vector from this instance.
  3694. *
  3695. * @param {Vector3} v - The vector to subtract.
  3696. * @return {Vector3} A reference to this vector.
  3697. */
  3698. sub( v ) {
  3699. this.x -= v.x;
  3700. this.y -= v.y;
  3701. this.z -= v.z;
  3702. return this;
  3703. }
  3704. /**
  3705. * Subtracts the given scalar value from all components of this instance.
  3706. *
  3707. * @param {number} s - The scalar to subtract.
  3708. * @return {Vector3} A reference to this vector.
  3709. */
  3710. subScalar( s ) {
  3711. this.x -= s;
  3712. this.y -= s;
  3713. this.z -= s;
  3714. return this;
  3715. }
  3716. /**
  3717. * Subtracts the given vectors and stores the result in this instance.
  3718. *
  3719. * @param {Vector3} a - The first vector.
  3720. * @param {Vector3} b - The second vector.
  3721. * @return {Vector3} A reference to this vector.
  3722. */
  3723. subVectors( a, b ) {
  3724. this.x = a.x - b.x;
  3725. this.y = a.y - b.y;
  3726. this.z = a.z - b.z;
  3727. return this;
  3728. }
  3729. /**
  3730. * Multiplies the given vector with this instance.
  3731. *
  3732. * @param {Vector3} v - The vector to multiply.
  3733. * @return {Vector3} A reference to this vector.
  3734. */
  3735. multiply( v ) {
  3736. this.x *= v.x;
  3737. this.y *= v.y;
  3738. this.z *= v.z;
  3739. return this;
  3740. }
  3741. /**
  3742. * Multiplies the given scalar value with all components of this instance.
  3743. *
  3744. * @param {number} scalar - The scalar to multiply.
  3745. * @return {Vector3} A reference to this vector.
  3746. */
  3747. multiplyScalar( scalar ) {
  3748. this.x *= scalar;
  3749. this.y *= scalar;
  3750. this.z *= scalar;
  3751. return this;
  3752. }
  3753. /**
  3754. * Multiplies the given vectors and stores the result in this instance.
  3755. *
  3756. * @param {Vector3} a - The first vector.
  3757. * @param {Vector3} b - The second vector.
  3758. * @return {Vector3} A reference to this vector.
  3759. */
  3760. multiplyVectors( a, b ) {
  3761. this.x = a.x * b.x;
  3762. this.y = a.y * b.y;
  3763. this.z = a.z * b.z;
  3764. return this;
  3765. }
  3766. /**
  3767. * Applies the given Euler rotation to this vector.
  3768. *
  3769. * @param {Euler} euler - The Euler angles.
  3770. * @return {Vector3} A reference to this vector.
  3771. */
  3772. applyEuler( euler ) {
  3773. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3774. }
  3775. /**
  3776. * Applies a rotation specified by an axis and an angle to this vector.
  3777. *
  3778. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3779. * @param {number} angle - The angle in radians.
  3780. * @return {Vector3} A reference to this vector.
  3781. */
  3782. applyAxisAngle( axis, angle ) {
  3783. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3784. }
  3785. /**
  3786. * Multiplies this vector with the given 3x3 matrix.
  3787. *
  3788. * @param {Matrix3} m - The 3x3 matrix.
  3789. * @return {Vector3} A reference to this vector.
  3790. */
  3791. applyMatrix3( m ) {
  3792. const x = this.x, y = this.y, z = this.z;
  3793. const e = m.elements;
  3794. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3795. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3796. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3797. return this;
  3798. }
  3799. /**
  3800. * Multiplies this vector by the given normal matrix and normalizes
  3801. * the result.
  3802. *
  3803. * @param {Matrix3} m - The normal matrix.
  3804. * @return {Vector3} A reference to this vector.
  3805. */
  3806. applyNormalMatrix( m ) {
  3807. return this.applyMatrix3( m ).normalize();
  3808. }
  3809. /**
  3810. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3811. * divides by perspective.
  3812. *
  3813. * @param {Matrix4} m - The matrix to apply.
  3814. * @return {Vector3} A reference to this vector.
  3815. */
  3816. applyMatrix4( m ) {
  3817. const x = this.x, y = this.y, z = this.z;
  3818. const e = m.elements;
  3819. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3820. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3821. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3822. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3823. return this;
  3824. }
  3825. /**
  3826. * Applies the given Quaternion to this vector.
  3827. *
  3828. * @param {Quaternion} q - The Quaternion.
  3829. * @return {Vector3} A reference to this vector.
  3830. */
  3831. applyQuaternion( q ) {
  3832. // quaternion q is assumed to have unit length
  3833. const vx = this.x, vy = this.y, vz = this.z;
  3834. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3835. // t = 2 * cross( q.xyz, v );
  3836. const tx = 2 * ( qy * vz - qz * vy );
  3837. const ty = 2 * ( qz * vx - qx * vz );
  3838. const tz = 2 * ( qx * vy - qy * vx );
  3839. // v + q.w * t + cross( q.xyz, t );
  3840. this.x = vx + qw * tx + qy * tz - qz * ty;
  3841. this.y = vy + qw * ty + qz * tx - qx * tz;
  3842. this.z = vz + qw * tz + qx * ty - qy * tx;
  3843. return this;
  3844. }
  3845. /**
  3846. * Projects this vector from world space into the camera's normalized
  3847. * device coordinate (NDC) space.
  3848. *
  3849. * @param {Camera} camera - The camera.
  3850. * @return {Vector3} A reference to this vector.
  3851. */
  3852. project( camera ) {
  3853. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3854. }
  3855. /**
  3856. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3857. * space into world space.
  3858. *
  3859. * @param {Camera} camera - The camera.
  3860. * @return {Vector3} A reference to this vector.
  3861. */
  3862. unproject( camera ) {
  3863. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3864. }
  3865. /**
  3866. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3867. * subset of the given 4x4 matrix and then normalizes the result.
  3868. *
  3869. * @param {Matrix4} m - The matrix.
  3870. * @return {Vector3} A reference to this vector.
  3871. */
  3872. transformDirection( m ) {
  3873. // input: THREE.Matrix4 affine matrix
  3874. // vector interpreted as a direction
  3875. const x = this.x, y = this.y, z = this.z;
  3876. const e = m.elements;
  3877. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3878. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3879. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3880. return this.normalize();
  3881. }
  3882. /**
  3883. * Divides this instance by the given vector.
  3884. *
  3885. * @param {Vector3} v - The vector to divide.
  3886. * @return {Vector3} A reference to this vector.
  3887. */
  3888. divide( v ) {
  3889. this.x /= v.x;
  3890. this.y /= v.y;
  3891. this.z /= v.z;
  3892. return this;
  3893. }
  3894. /**
  3895. * Divides this vector by the given scalar.
  3896. *
  3897. * @param {number} scalar - The scalar to divide.
  3898. * @return {Vector3} A reference to this vector.
  3899. */
  3900. divideScalar( scalar ) {
  3901. return this.multiplyScalar( 1 / scalar );
  3902. }
  3903. /**
  3904. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3905. * value, replace that value with the corresponding min value.
  3906. *
  3907. * @param {Vector3} v - The vector.
  3908. * @return {Vector3} A reference to this vector.
  3909. */
  3910. min( v ) {
  3911. this.x = Math.min( this.x, v.x );
  3912. this.y = Math.min( this.y, v.y );
  3913. this.z = Math.min( this.z, v.z );
  3914. return this;
  3915. }
  3916. /**
  3917. * If this vector's x, y or z value is less than the given vector's x, y or z
  3918. * value, replace that value with the corresponding max value.
  3919. *
  3920. * @param {Vector3} v - The vector.
  3921. * @return {Vector3} A reference to this vector.
  3922. */
  3923. max( v ) {
  3924. this.x = Math.max( this.x, v.x );
  3925. this.y = Math.max( this.y, v.y );
  3926. this.z = Math.max( this.z, v.z );
  3927. return this;
  3928. }
  3929. /**
  3930. * If this vector's x, y or z value is greater than the max vector's x, y or z
  3931. * value, it is replaced by the corresponding value.
  3932. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  3933. * it is replaced by the corresponding value.
  3934. *
  3935. * @param {Vector3} min - The minimum x, y and z values.
  3936. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  3937. * @return {Vector3} A reference to this vector.
  3938. */
  3939. clamp( min, max ) {
  3940. // assumes min < max, componentwise
  3941. this.x = clamp( this.x, min.x, max.x );
  3942. this.y = clamp( this.y, min.y, max.y );
  3943. this.z = clamp( this.z, min.z, max.z );
  3944. return this;
  3945. }
  3946. /**
  3947. * If this vector's x, y or z values are greater than the max value, they are
  3948. * replaced by the max value.
  3949. * If this vector's x, y or z values are less than the min value, they are
  3950. * replaced by the min value.
  3951. *
  3952. * @param {number} minVal - The minimum value the components will be clamped to.
  3953. * @param {number} maxVal - The maximum value the components will be clamped to.
  3954. * @return {Vector3} A reference to this vector.
  3955. */
  3956. clampScalar( minVal, maxVal ) {
  3957. this.x = clamp( this.x, minVal, maxVal );
  3958. this.y = clamp( this.y, minVal, maxVal );
  3959. this.z = clamp( this.z, minVal, maxVal );
  3960. return this;
  3961. }
  3962. /**
  3963. * If this vector's length is greater than the max value, it is replaced by
  3964. * the max value.
  3965. * If this vector's length is less than the min value, it is replaced by the
  3966. * min value.
  3967. *
  3968. * @param {number} min - The minimum value the vector length will be clamped to.
  3969. * @param {number} max - The maximum value the vector length will be clamped to.
  3970. * @return {Vector3} A reference to this vector.
  3971. */
  3972. clampLength( min, max ) {
  3973. const length = this.length();
  3974. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3975. }
  3976. /**
  3977. * The components of this vector are rounded down to the nearest integer value.
  3978. *
  3979. * @return {Vector3} A reference to this vector.
  3980. */
  3981. floor() {
  3982. this.x = Math.floor( this.x );
  3983. this.y = Math.floor( this.y );
  3984. this.z = Math.floor( this.z );
  3985. return this;
  3986. }
  3987. /**
  3988. * The components of this vector are rounded up to the nearest integer value.
  3989. *
  3990. * @return {Vector3} A reference to this vector.
  3991. */
  3992. ceil() {
  3993. this.x = Math.ceil( this.x );
  3994. this.y = Math.ceil( this.y );
  3995. this.z = Math.ceil( this.z );
  3996. return this;
  3997. }
  3998. /**
  3999. * The components of this vector are rounded to the nearest integer value
  4000. *
  4001. * @return {Vector3} A reference to this vector.
  4002. */
  4003. round() {
  4004. this.x = Math.round( this.x );
  4005. this.y = Math.round( this.y );
  4006. this.z = Math.round( this.z );
  4007. return this;
  4008. }
  4009. /**
  4010. * The components of this vector are rounded towards zero (up if negative,
  4011. * down if positive) to an integer value.
  4012. *
  4013. * @return {Vector3} A reference to this vector.
  4014. */
  4015. roundToZero() {
  4016. this.x = Math.trunc( this.x );
  4017. this.y = Math.trunc( this.y );
  4018. this.z = Math.trunc( this.z );
  4019. return this;
  4020. }
  4021. /**
  4022. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4023. *
  4024. * @return {Vector3} A reference to this vector.
  4025. */
  4026. negate() {
  4027. this.x = - this.x;
  4028. this.y = - this.y;
  4029. this.z = - this.z;
  4030. return this;
  4031. }
  4032. /**
  4033. * Calculates the dot product of the given vector with this instance.
  4034. *
  4035. * @param {Vector3} v - The vector to compute the dot product with.
  4036. * @return {number} The result of the dot product.
  4037. */
  4038. dot( v ) {
  4039. return this.x * v.x + this.y * v.y + this.z * v.z;
  4040. }
  4041. // TODO lengthSquared?
  4042. /**
  4043. * Computes the square of the Euclidean length (straight-line length) from
  4044. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4045. * compare the length squared instead as it is slightly more efficient to calculate.
  4046. *
  4047. * @return {number} The square length of this vector.
  4048. */
  4049. lengthSq() {
  4050. return this.x * this.x + this.y * this.y + this.z * this.z;
  4051. }
  4052. /**
  4053. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4054. *
  4055. * @return {number} The length of this vector.
  4056. */
  4057. length() {
  4058. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4059. }
  4060. /**
  4061. * Computes the Manhattan length of this vector.
  4062. *
  4063. * @return {number} The length of this vector.
  4064. */
  4065. manhattanLength() {
  4066. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4067. }
  4068. /**
  4069. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4070. * with the same direction as this one, but with a vector length of `1`.
  4071. *
  4072. * @return {Vector3} A reference to this vector.
  4073. */
  4074. normalize() {
  4075. return this.divideScalar( this.length() || 1 );
  4076. }
  4077. /**
  4078. * Sets this vector to a vector with the same direction as this one, but
  4079. * with the specified length.
  4080. *
  4081. * @param {number} length - The new length of this vector.
  4082. * @return {Vector3} A reference to this vector.
  4083. */
  4084. setLength( length ) {
  4085. return this.normalize().multiplyScalar( length );
  4086. }
  4087. /**
  4088. * Linearly interpolates between the given vector and this instance, where
  4089. * alpha is the percent distance along the line - alpha = 0 will be this
  4090. * vector, and alpha = 1 will be the given one.
  4091. *
  4092. * @param {Vector3} v - The vector to interpolate towards.
  4093. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4094. * @return {Vector3} A reference to this vector.
  4095. */
  4096. lerp( v, alpha ) {
  4097. this.x += ( v.x - this.x ) * alpha;
  4098. this.y += ( v.y - this.y ) * alpha;
  4099. this.z += ( v.z - this.z ) * alpha;
  4100. return this;
  4101. }
  4102. /**
  4103. * Linearly interpolates between the given vectors, where alpha is the percent
  4104. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4105. * be the second one. The result is stored in this instance.
  4106. *
  4107. * @param {Vector3} v1 - The first vector.
  4108. * @param {Vector3} v2 - The second vector.
  4109. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4110. * @return {Vector3} A reference to this vector.
  4111. */
  4112. lerpVectors( v1, v2, alpha ) {
  4113. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4114. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4115. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4116. return this;
  4117. }
  4118. /**
  4119. * Calculates the cross product of the given vector with this instance.
  4120. *
  4121. * @param {Vector3} v - The vector to compute the cross product with.
  4122. * @return {Vector3} The result of the cross product.
  4123. */
  4124. cross( v ) {
  4125. return this.crossVectors( this, v );
  4126. }
  4127. /**
  4128. * Calculates the cross product of the given vectors and stores the result
  4129. * in this instance.
  4130. *
  4131. * @param {Vector3} a - The first vector.
  4132. * @param {Vector3} b - The second vector.
  4133. * @return {Vector3} A reference to this vector.
  4134. */
  4135. crossVectors( a, b ) {
  4136. const ax = a.x, ay = a.y, az = a.z;
  4137. const bx = b.x, by = b.y, bz = b.z;
  4138. this.x = ay * bz - az * by;
  4139. this.y = az * bx - ax * bz;
  4140. this.z = ax * by - ay * bx;
  4141. return this;
  4142. }
  4143. /**
  4144. * Projects this vector onto the given one.
  4145. *
  4146. * @param {Vector3} v - The vector to project to.
  4147. * @return {Vector3} A reference to this vector.
  4148. */
  4149. projectOnVector( v ) {
  4150. const denominator = v.lengthSq();
  4151. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4152. const scalar = v.dot( this ) / denominator;
  4153. return this.copy( v ).multiplyScalar( scalar );
  4154. }
  4155. /**
  4156. * Projects this vector onto a plane by subtracting this
  4157. * vector projected onto the plane's normal from this vector.
  4158. *
  4159. * @param {Vector3} planeNormal - The plane normal.
  4160. * @return {Vector3} A reference to this vector.
  4161. */
  4162. projectOnPlane( planeNormal ) {
  4163. _vector$c.copy( this ).projectOnVector( planeNormal );
  4164. return this.sub( _vector$c );
  4165. }
  4166. /**
  4167. * Reflects this vector off a plane orthogonal to the given normal vector.
  4168. *
  4169. * @param {Vector3} normal - The (normalized) normal vector.
  4170. * @return {Vector3} A reference to this vector.
  4171. */
  4172. reflect( normal ) {
  4173. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4174. }
  4175. /**
  4176. * Returns the angle between the given vector and this instance in radians.
  4177. *
  4178. * @param {Vector3} v - The vector to compute the angle with.
  4179. * @return {number} The angle in radians.
  4180. */
  4181. angleTo( v ) {
  4182. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4183. if ( denominator === 0 ) return Math.PI / 2;
  4184. const theta = this.dot( v ) / denominator;
  4185. // clamp, to handle numerical problems
  4186. return Math.acos( clamp( theta, -1, 1 ) );
  4187. }
  4188. /**
  4189. * Computes the distance from the given vector to this instance.
  4190. *
  4191. * @param {Vector3} v - The vector to compute the distance to.
  4192. * @return {number} The distance.
  4193. */
  4194. distanceTo( v ) {
  4195. return Math.sqrt( this.distanceToSquared( v ) );
  4196. }
  4197. /**
  4198. * Computes the squared distance from the given vector to this instance.
  4199. * If you are just comparing the distance with another distance, you should compare
  4200. * the distance squared instead as it is slightly more efficient to calculate.
  4201. *
  4202. * @param {Vector3} v - The vector to compute the squared distance to.
  4203. * @return {number} The squared distance.
  4204. */
  4205. distanceToSquared( v ) {
  4206. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4207. return dx * dx + dy * dy + dz * dz;
  4208. }
  4209. /**
  4210. * Computes the Manhattan distance from the given vector to this instance.
  4211. *
  4212. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4213. * @return {number} The Manhattan distance.
  4214. */
  4215. manhattanDistanceTo( v ) {
  4216. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4217. }
  4218. /**
  4219. * Sets the vector components from the given spherical coordinates.
  4220. *
  4221. * @param {Spherical} s - The spherical coordinates.
  4222. * @return {Vector3} A reference to this vector.
  4223. */
  4224. setFromSpherical( s ) {
  4225. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4226. }
  4227. /**
  4228. * Sets the vector components from the given spherical coordinates.
  4229. *
  4230. * @param {number} radius - The radius.
  4231. * @param {number} phi - The phi angle in radians.
  4232. * @param {number} theta - The theta angle in radians.
  4233. * @return {Vector3} A reference to this vector.
  4234. */
  4235. setFromSphericalCoords( radius, phi, theta ) {
  4236. const sinPhiRadius = Math.sin( phi ) * radius;
  4237. this.x = sinPhiRadius * Math.sin( theta );
  4238. this.y = Math.cos( phi ) * radius;
  4239. this.z = sinPhiRadius * Math.cos( theta );
  4240. return this;
  4241. }
  4242. /**
  4243. * Sets the vector components from the given cylindrical coordinates.
  4244. *
  4245. * @param {Cylindrical} c - The cylindrical coordinates.
  4246. * @return {Vector3} A reference to this vector.
  4247. */
  4248. setFromCylindrical( c ) {
  4249. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4250. }
  4251. /**
  4252. * Sets the vector components from the given cylindrical coordinates.
  4253. *
  4254. * @param {number} radius - The radius.
  4255. * @param {number} theta - The theta angle in radians.
  4256. * @param {number} y - The y value.
  4257. * @return {Vector3} A reference to this vector.
  4258. */
  4259. setFromCylindricalCoords( radius, theta, y ) {
  4260. this.x = radius * Math.sin( theta );
  4261. this.y = y;
  4262. this.z = radius * Math.cos( theta );
  4263. return this;
  4264. }
  4265. /**
  4266. * Sets the vector components to the position elements of the
  4267. * given transformation matrix.
  4268. *
  4269. * @param {Matrix4} m - The 4x4 matrix.
  4270. * @return {Vector3} A reference to this vector.
  4271. */
  4272. setFromMatrixPosition( m ) {
  4273. const e = m.elements;
  4274. this.x = e[ 12 ];
  4275. this.y = e[ 13 ];
  4276. this.z = e[ 14 ];
  4277. return this;
  4278. }
  4279. /**
  4280. * Sets the vector components to the scale elements of the
  4281. * given transformation matrix.
  4282. *
  4283. * @param {Matrix4} m - The 4x4 matrix.
  4284. * @return {Vector3} A reference to this vector.
  4285. */
  4286. setFromMatrixScale( m ) {
  4287. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4288. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4289. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4290. this.x = sx;
  4291. this.y = sy;
  4292. this.z = sz;
  4293. return this;
  4294. }
  4295. /**
  4296. * Sets the vector components from the specified matrix column.
  4297. *
  4298. * @param {Matrix4} m - The 4x4 matrix.
  4299. * @param {number} index - The column index.
  4300. * @return {Vector3} A reference to this vector.
  4301. */
  4302. setFromMatrixColumn( m, index ) {
  4303. return this.fromArray( m.elements, index * 4 );
  4304. }
  4305. /**
  4306. * Sets the vector components from the specified matrix column.
  4307. *
  4308. * @param {Matrix3} m - The 3x3 matrix.
  4309. * @param {number} index - The column index.
  4310. * @return {Vector3} A reference to this vector.
  4311. */
  4312. setFromMatrix3Column( m, index ) {
  4313. return this.fromArray( m.elements, index * 3 );
  4314. }
  4315. /**
  4316. * Sets the vector components from the given Euler angles.
  4317. *
  4318. * @param {Euler} e - The Euler angles to set.
  4319. * @return {Vector3} A reference to this vector.
  4320. */
  4321. setFromEuler( e ) {
  4322. this.x = e._x;
  4323. this.y = e._y;
  4324. this.z = e._z;
  4325. return this;
  4326. }
  4327. /**
  4328. * Sets the vector components from the RGB components of the
  4329. * given color.
  4330. *
  4331. * @param {Color} c - The color to set.
  4332. * @return {Vector3} A reference to this vector.
  4333. */
  4334. setFromColor( c ) {
  4335. this.x = c.r;
  4336. this.y = c.g;
  4337. this.z = c.b;
  4338. return this;
  4339. }
  4340. /**
  4341. * Returns `true` if this vector is equal with the given one.
  4342. *
  4343. * @param {Vector3} v - The vector to test for equality.
  4344. * @return {boolean} Whether this vector is equal with the given one.
  4345. */
  4346. equals( v ) {
  4347. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4348. }
  4349. /**
  4350. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4351. * and z value to be `array[ offset + 2 ]`.
  4352. *
  4353. * @param {Array<number>} array - An array holding the vector component values.
  4354. * @param {number} [offset=0] - The offset into the array.
  4355. * @return {Vector3} A reference to this vector.
  4356. */
  4357. fromArray( array, offset = 0 ) {
  4358. this.x = array[ offset ];
  4359. this.y = array[ offset + 1 ];
  4360. this.z = array[ offset + 2 ];
  4361. return this;
  4362. }
  4363. /**
  4364. * Writes the components of this vector to the given array. If no array is provided,
  4365. * the method returns a new instance.
  4366. *
  4367. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4368. * @param {number} [offset=0] - Index of the first element in the array.
  4369. * @return {Array<number>} The vector components.
  4370. */
  4371. toArray( array = [], offset = 0 ) {
  4372. array[ offset ] = this.x;
  4373. array[ offset + 1 ] = this.y;
  4374. array[ offset + 2 ] = this.z;
  4375. return array;
  4376. }
  4377. /**
  4378. * Sets the components of this vector from the given buffer attribute.
  4379. *
  4380. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4381. * @param {number} index - The index into the attribute.
  4382. * @return {Vector3} A reference to this vector.
  4383. */
  4384. fromBufferAttribute( attribute, index ) {
  4385. this.x = attribute.getX( index );
  4386. this.y = attribute.getY( index );
  4387. this.z = attribute.getZ( index );
  4388. return this;
  4389. }
  4390. /**
  4391. * Sets each component of this vector to a pseudo-random value between `0` and
  4392. * `1`, excluding `1`.
  4393. *
  4394. * @return {Vector3} A reference to this vector.
  4395. */
  4396. random() {
  4397. this.x = Math.random();
  4398. this.y = Math.random();
  4399. this.z = Math.random();
  4400. return this;
  4401. }
  4402. /**
  4403. * Sets this vector to a uniformly random point on a unit sphere.
  4404. *
  4405. * @return {Vector3} A reference to this vector.
  4406. */
  4407. randomDirection() {
  4408. // https://mathworld.wolfram.com/SpherePointPicking.html
  4409. const theta = Math.random() * Math.PI * 2;
  4410. const u = Math.random() * 2 - 1;
  4411. const c = Math.sqrt( 1 - u * u );
  4412. this.x = c * Math.cos( theta );
  4413. this.y = u;
  4414. this.z = c * Math.sin( theta );
  4415. return this;
  4416. }
  4417. *[ Symbol.iterator ]() {
  4418. yield this.x;
  4419. yield this.y;
  4420. yield this.z;
  4421. }
  4422. }
  4423. const _vector$c = /*@__PURE__*/ new Vector3();
  4424. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4425. /**
  4426. * Represents a 3x3 matrix.
  4427. *
  4428. * A Note on Row-Major and Column-Major Ordering:
  4429. *
  4430. * The constructor and {@link Matrix3#set} method take arguments in
  4431. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4432. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4433. * This means that calling:
  4434. * ```js
  4435. * const m = new THREE.Matrix();
  4436. * m.set( 11, 12, 13,
  4437. * 21, 22, 23,
  4438. * 31, 32, 33 );
  4439. * ```
  4440. * will result in the elements array containing:
  4441. * ```js
  4442. * m.elements = [ 11, 21, 31,
  4443. * 12, 22, 32,
  4444. * 13, 23, 33 ];
  4445. * ```
  4446. * and internally all calculations are performed using column-major ordering.
  4447. * However, as the actual ordering makes no difference mathematically and
  4448. * most people are used to thinking about matrices in row-major order, the
  4449. * three.js documentation shows matrices in row-major order. Just bear in
  4450. * mind that if you are reading the source code, you'll have to take the
  4451. * transpose of any matrices outlined here to make sense of the calculations.
  4452. */
  4453. class Matrix3 {
  4454. /**
  4455. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4456. * in row-major order. If no arguments are provided, the constructor
  4457. * initializes the matrix as an identity matrix.
  4458. *
  4459. * @param {number} [n11] - 1-1 matrix element.
  4460. * @param {number} [n12] - 1-2 matrix element.
  4461. * @param {number} [n13] - 1-3 matrix element.
  4462. * @param {number} [n21] - 2-1 matrix element.
  4463. * @param {number} [n22] - 2-2 matrix element.
  4464. * @param {number} [n23] - 2-3 matrix element.
  4465. * @param {number} [n31] - 3-1 matrix element.
  4466. * @param {number} [n32] - 3-2 matrix element.
  4467. * @param {number} [n33] - 3-3 matrix element.
  4468. */
  4469. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4470. /**
  4471. * This flag can be used for type testing.
  4472. *
  4473. * @type {boolean}
  4474. * @readonly
  4475. * @default true
  4476. */
  4477. Matrix3.prototype.isMatrix3 = true;
  4478. /**
  4479. * A column-major list of matrix values.
  4480. *
  4481. * @type {Array<number>}
  4482. */
  4483. this.elements = [
  4484. 1, 0, 0,
  4485. 0, 1, 0,
  4486. 0, 0, 1
  4487. ];
  4488. if ( n11 !== undefined ) {
  4489. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4490. }
  4491. }
  4492. /**
  4493. * Sets the elements of the matrix.The arguments are supposed to be
  4494. * in row-major order.
  4495. *
  4496. * @param {number} [n11] - 1-1 matrix element.
  4497. * @param {number} [n12] - 1-2 matrix element.
  4498. * @param {number} [n13] - 1-3 matrix element.
  4499. * @param {number} [n21] - 2-1 matrix element.
  4500. * @param {number} [n22] - 2-2 matrix element.
  4501. * @param {number} [n23] - 2-3 matrix element.
  4502. * @param {number} [n31] - 3-1 matrix element.
  4503. * @param {number} [n32] - 3-2 matrix element.
  4504. * @param {number} [n33] - 3-3 matrix element.
  4505. * @return {Matrix3} A reference to this matrix.
  4506. */
  4507. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4508. const te = this.elements;
  4509. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4510. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4511. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4512. return this;
  4513. }
  4514. /**
  4515. * Sets this matrix to the 3x3 identity matrix.
  4516. *
  4517. * @return {Matrix3} A reference to this matrix.
  4518. */
  4519. identity() {
  4520. this.set(
  4521. 1, 0, 0,
  4522. 0, 1, 0,
  4523. 0, 0, 1
  4524. );
  4525. return this;
  4526. }
  4527. /**
  4528. * Copies the values of the given matrix to this instance.
  4529. *
  4530. * @param {Matrix3} m - The matrix to copy.
  4531. * @return {Matrix3} A reference to this matrix.
  4532. */
  4533. copy( m ) {
  4534. const te = this.elements;
  4535. const me = m.elements;
  4536. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4537. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4538. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4539. return this;
  4540. }
  4541. /**
  4542. * Extracts the basis of this matrix into the three axis vectors provided.
  4543. *
  4544. * @param {Vector3} xAxis - The basis's x axis.
  4545. * @param {Vector3} yAxis - The basis's y axis.
  4546. * @param {Vector3} zAxis - The basis's z axis.
  4547. * @return {Matrix3} A reference to this matrix.
  4548. */
  4549. extractBasis( xAxis, yAxis, zAxis ) {
  4550. xAxis.setFromMatrix3Column( this, 0 );
  4551. yAxis.setFromMatrix3Column( this, 1 );
  4552. zAxis.setFromMatrix3Column( this, 2 );
  4553. return this;
  4554. }
  4555. /**
  4556. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4557. *
  4558. * @param {Matrix4} m - The 4x4 matrix.
  4559. * @return {Matrix3} A reference to this matrix.
  4560. */
  4561. setFromMatrix4( m ) {
  4562. const me = m.elements;
  4563. this.set(
  4564. me[ 0 ], me[ 4 ], me[ 8 ],
  4565. me[ 1 ], me[ 5 ], me[ 9 ],
  4566. me[ 2 ], me[ 6 ], me[ 10 ]
  4567. );
  4568. return this;
  4569. }
  4570. /**
  4571. * Post-multiplies this matrix by the given 3x3 matrix.
  4572. *
  4573. * @param {Matrix3} m - The matrix to multiply with.
  4574. * @return {Matrix3} A reference to this matrix.
  4575. */
  4576. multiply( m ) {
  4577. return this.multiplyMatrices( this, m );
  4578. }
  4579. /**
  4580. * Pre-multiplies this matrix by the given 3x3 matrix.
  4581. *
  4582. * @param {Matrix3} m - The matrix to multiply with.
  4583. * @return {Matrix3} A reference to this matrix.
  4584. */
  4585. premultiply( m ) {
  4586. return this.multiplyMatrices( m, this );
  4587. }
  4588. /**
  4589. * Multiples the given 3x3 matrices and stores the result
  4590. * in this matrix.
  4591. *
  4592. * @param {Matrix3} a - The first matrix.
  4593. * @param {Matrix3} b - The second matrix.
  4594. * @return {Matrix3} A reference to this matrix.
  4595. */
  4596. multiplyMatrices( a, b ) {
  4597. const ae = a.elements;
  4598. const be = b.elements;
  4599. const te = this.elements;
  4600. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4601. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4602. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4603. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4604. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4605. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4606. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4607. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4608. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4609. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4610. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4611. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4612. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4613. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4614. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4615. return this;
  4616. }
  4617. /**
  4618. * Multiplies every component of the matrix by the given scalar.
  4619. *
  4620. * @param {number} s - The scalar.
  4621. * @return {Matrix3} A reference to this matrix.
  4622. */
  4623. multiplyScalar( s ) {
  4624. const te = this.elements;
  4625. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4626. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4627. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4628. return this;
  4629. }
  4630. /**
  4631. * Computes and returns the determinant of this matrix.
  4632. *
  4633. * @return {number} The determinant.
  4634. */
  4635. determinant() {
  4636. const te = this.elements;
  4637. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4638. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4639. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4640. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4641. }
  4642. /**
  4643. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4644. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4645. * a zero matrix instead.
  4646. *
  4647. * @return {Matrix3} A reference to this matrix.
  4648. */
  4649. invert() {
  4650. const te = this.elements,
  4651. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4652. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4653. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4654. t11 = n33 * n22 - n32 * n23,
  4655. t12 = n32 * n13 - n33 * n12,
  4656. t13 = n23 * n12 - n22 * n13,
  4657. det = n11 * t11 + n21 * t12 + n31 * t13;
  4658. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4659. const detInv = 1 / det;
  4660. te[ 0 ] = t11 * detInv;
  4661. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4662. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4663. te[ 3 ] = t12 * detInv;
  4664. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4665. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4666. te[ 6 ] = t13 * detInv;
  4667. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4668. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4669. return this;
  4670. }
  4671. /**
  4672. * Transposes this matrix in place.
  4673. *
  4674. * @return {Matrix3} A reference to this matrix.
  4675. */
  4676. transpose() {
  4677. let tmp;
  4678. const m = this.elements;
  4679. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4680. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4681. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4682. return this;
  4683. }
  4684. /**
  4685. * Computes the normal matrix which is the inverse transpose of the upper
  4686. * left 3x3 portion of the given 4x4 matrix.
  4687. *
  4688. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4689. * @return {Matrix3} A reference to this matrix.
  4690. */
  4691. getNormalMatrix( matrix4 ) {
  4692. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4693. }
  4694. /**
  4695. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4696. *
  4697. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4698. * @return {Matrix3} A reference to this matrix.
  4699. */
  4700. transposeIntoArray( r ) {
  4701. const m = this.elements;
  4702. r[ 0 ] = m[ 0 ];
  4703. r[ 1 ] = m[ 3 ];
  4704. r[ 2 ] = m[ 6 ];
  4705. r[ 3 ] = m[ 1 ];
  4706. r[ 4 ] = m[ 4 ];
  4707. r[ 5 ] = m[ 7 ];
  4708. r[ 6 ] = m[ 2 ];
  4709. r[ 7 ] = m[ 5 ];
  4710. r[ 8 ] = m[ 8 ];
  4711. return this;
  4712. }
  4713. /**
  4714. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4715. *
  4716. * @param {number} tx - Offset x.
  4717. * @param {number} ty - Offset y.
  4718. * @param {number} sx - Repeat x.
  4719. * @param {number} sy - Repeat y.
  4720. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4721. * @param {number} cx - Center x of rotation.
  4722. * @param {number} cy - Center y of rotation
  4723. * @return {Matrix3} A reference to this matrix.
  4724. */
  4725. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4726. const c = Math.cos( rotation );
  4727. const s = Math.sin( rotation );
  4728. this.set(
  4729. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4730. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4731. 0, 0, 1
  4732. );
  4733. return this;
  4734. }
  4735. /**
  4736. * Scales this matrix with the given scalar values.
  4737. *
  4738. * @param {number} sx - The amount to scale in the X axis.
  4739. * @param {number} sy - The amount to scale in the Y axis.
  4740. * @return {Matrix3} A reference to this matrix.
  4741. */
  4742. scale( sx, sy ) {
  4743. this.premultiply( _m3.makeScale( sx, sy ) );
  4744. return this;
  4745. }
  4746. /**
  4747. * Rotates this matrix by the given angle.
  4748. *
  4749. * @param {number} theta - The rotation in radians.
  4750. * @return {Matrix3} A reference to this matrix.
  4751. */
  4752. rotate( theta ) {
  4753. this.premultiply( _m3.makeRotation( - theta ) );
  4754. return this;
  4755. }
  4756. /**
  4757. * Translates this matrix by the given scalar values.
  4758. *
  4759. * @param {number} tx - The amount to translate in the X axis.
  4760. * @param {number} ty - The amount to translate in the Y axis.
  4761. * @return {Matrix3} A reference to this matrix.
  4762. */
  4763. translate( tx, ty ) {
  4764. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4765. return this;
  4766. }
  4767. // for 2D Transforms
  4768. /**
  4769. * Sets this matrix as a 2D translation transform.
  4770. *
  4771. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4772. * @param {number} y - The amount to translate in the Y axis.
  4773. * @return {Matrix3} A reference to this matrix.
  4774. */
  4775. makeTranslation( x, y ) {
  4776. if ( x.isVector2 ) {
  4777. this.set(
  4778. 1, 0, x.x,
  4779. 0, 1, x.y,
  4780. 0, 0, 1
  4781. );
  4782. } else {
  4783. this.set(
  4784. 1, 0, x,
  4785. 0, 1, y,
  4786. 0, 0, 1
  4787. );
  4788. }
  4789. return this;
  4790. }
  4791. /**
  4792. * Sets this matrix as a 2D rotational transformation.
  4793. *
  4794. * @param {number} theta - The rotation in radians.
  4795. * @return {Matrix3} A reference to this matrix.
  4796. */
  4797. makeRotation( theta ) {
  4798. // counterclockwise
  4799. const c = Math.cos( theta );
  4800. const s = Math.sin( theta );
  4801. this.set(
  4802. c, - s, 0,
  4803. s, c, 0,
  4804. 0, 0, 1
  4805. );
  4806. return this;
  4807. }
  4808. /**
  4809. * Sets this matrix as a 2D scale transform.
  4810. *
  4811. * @param {number} x - The amount to scale in the X axis.
  4812. * @param {number} y - The amount to scale in the Y axis.
  4813. * @return {Matrix3} A reference to this matrix.
  4814. */
  4815. makeScale( x, y ) {
  4816. this.set(
  4817. x, 0, 0,
  4818. 0, y, 0,
  4819. 0, 0, 1
  4820. );
  4821. return this;
  4822. }
  4823. /**
  4824. * Returns `true` if this matrix is equal with the given one.
  4825. *
  4826. * @param {Matrix3} matrix - The matrix to test for equality.
  4827. * @return {boolean} Whether this matrix is equal with the given one.
  4828. */
  4829. equals( matrix ) {
  4830. const te = this.elements;
  4831. const me = matrix.elements;
  4832. for ( let i = 0; i < 9; i ++ ) {
  4833. if ( te[ i ] !== me[ i ] ) return false;
  4834. }
  4835. return true;
  4836. }
  4837. /**
  4838. * Sets the elements of the matrix from the given array.
  4839. *
  4840. * @param {Array<number>} array - The matrix elements in column-major order.
  4841. * @param {number} [offset=0] - Index of the first element in the array.
  4842. * @return {Matrix3} A reference to this matrix.
  4843. */
  4844. fromArray( array, offset = 0 ) {
  4845. for ( let i = 0; i < 9; i ++ ) {
  4846. this.elements[ i ] = array[ i + offset ];
  4847. }
  4848. return this;
  4849. }
  4850. /**
  4851. * Writes the elements of this matrix to the given array. If no array is provided,
  4852. * the method returns a new instance.
  4853. *
  4854. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4855. * @param {number} [offset=0] - Index of the first element in the array.
  4856. * @return {Array<number>} The matrix elements in column-major order.
  4857. */
  4858. toArray( array = [], offset = 0 ) {
  4859. const te = this.elements;
  4860. array[ offset ] = te[ 0 ];
  4861. array[ offset + 1 ] = te[ 1 ];
  4862. array[ offset + 2 ] = te[ 2 ];
  4863. array[ offset + 3 ] = te[ 3 ];
  4864. array[ offset + 4 ] = te[ 4 ];
  4865. array[ offset + 5 ] = te[ 5 ];
  4866. array[ offset + 6 ] = te[ 6 ];
  4867. array[ offset + 7 ] = te[ 7 ];
  4868. array[ offset + 8 ] = te[ 8 ];
  4869. return array;
  4870. }
  4871. /**
  4872. * Returns a matrix with copied values from this instance.
  4873. *
  4874. * @return {Matrix3} A clone of this instance.
  4875. */
  4876. clone() {
  4877. return new this.constructor().fromArray( this.elements );
  4878. }
  4879. }
  4880. const _m3 = /*@__PURE__*/ new Matrix3();
  4881. function arrayNeedsUint32( array ) {
  4882. // assumes larger values usually on last
  4883. for ( let i = array.length - 1; i >= 0; -- i ) {
  4884. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  4885. }
  4886. return false;
  4887. }
  4888. const TYPED_ARRAYS = {
  4889. Int8Array: Int8Array,
  4890. Uint8Array: Uint8Array,
  4891. Uint8ClampedArray: Uint8ClampedArray,
  4892. Int16Array: Int16Array,
  4893. Uint16Array: Uint16Array,
  4894. Int32Array: Int32Array,
  4895. Uint32Array: Uint32Array,
  4896. Float32Array: Float32Array,
  4897. Float64Array: Float64Array
  4898. };
  4899. function getTypedArray( type, buffer ) {
  4900. return new TYPED_ARRAYS[ type ]( buffer );
  4901. }
  4902. function createElementNS( name ) {
  4903. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  4904. }
  4905. function createCanvasElement() {
  4906. const canvas = createElementNS( 'canvas' );
  4907. canvas.style.display = 'block';
  4908. return canvas;
  4909. }
  4910. const _cache = {};
  4911. function warnOnce( message ) {
  4912. if ( message in _cache ) return;
  4913. _cache[ message ] = true;
  4914. console.warn( message );
  4915. }
  4916. function probeAsync( gl, sync, interval ) {
  4917. return new Promise( function ( resolve, reject ) {
  4918. function probe() {
  4919. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  4920. case gl.WAIT_FAILED:
  4921. reject();
  4922. break;
  4923. case gl.TIMEOUT_EXPIRED:
  4924. setTimeout( probe, interval );
  4925. break;
  4926. default:
  4927. resolve();
  4928. }
  4929. }
  4930. setTimeout( probe, interval );
  4931. } );
  4932. }
  4933. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4934. 0.4123908, 0.3575843, 0.1804808,
  4935. 0.2126390, 0.7151687, 0.0721923,
  4936. 0.0193308, 0.1191948, 0.9505322
  4937. );
  4938. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4939. 3.2409699, -1.5373832, -0.4986108,
  4940. -0.9692436, 1.8759675, 0.0415551,
  4941. 0.0556301, -0.203977, 1.0569715
  4942. );
  4943. function createColorManagement() {
  4944. const ColorManagement = {
  4945. enabled: true,
  4946. workingColorSpace: LinearSRGBColorSpace,
  4947. /**
  4948. * Implementations of supported color spaces.
  4949. *
  4950. * Required:
  4951. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4952. * - whitePoint: reference white [ x y ]
  4953. * - transfer: transfer function (pre-defined)
  4954. * - toXYZ: Matrix3 RGB to XYZ transform
  4955. * - fromXYZ: Matrix3 XYZ to RGB transform
  4956. * - luminanceCoefficients: RGB luminance coefficients
  4957. *
  4958. * Optional:
  4959. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  4960. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  4961. *
  4962. * Reference:
  4963. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  4964. */
  4965. spaces: {},
  4966. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  4967. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  4968. return color;
  4969. }
  4970. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  4971. color.r = SRGBToLinear( color.r );
  4972. color.g = SRGBToLinear( color.g );
  4973. color.b = SRGBToLinear( color.b );
  4974. }
  4975. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  4976. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  4977. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  4978. }
  4979. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  4980. color.r = LinearToSRGB( color.r );
  4981. color.g = LinearToSRGB( color.g );
  4982. color.b = LinearToSRGB( color.b );
  4983. }
  4984. return color;
  4985. },
  4986. workingToColorSpace: function ( color, targetColorSpace ) {
  4987. return this.convert( color, this.workingColorSpace, targetColorSpace );
  4988. },
  4989. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  4990. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  4991. },
  4992. getPrimaries: function ( colorSpace ) {
  4993. return this.spaces[ colorSpace ].primaries;
  4994. },
  4995. getTransfer: function ( colorSpace ) {
  4996. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  4997. return this.spaces[ colorSpace ].transfer;
  4998. },
  4999. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5000. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5001. },
  5002. define: function ( colorSpaces ) {
  5003. Object.assign( this.spaces, colorSpaces );
  5004. },
  5005. // Internal APIs
  5006. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5007. return targetMatrix
  5008. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5009. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5010. },
  5011. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5012. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5013. },
  5014. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5015. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5016. },
  5017. // Deprecated
  5018. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5019. warnOnce( 'THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5020. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5021. },
  5022. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5023. warnOnce( 'THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5024. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5025. },
  5026. };
  5027. /******************************************************************************
  5028. * sRGB definitions
  5029. */
  5030. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5031. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5032. const D65 = [ 0.3127, 0.3290 ];
  5033. ColorManagement.define( {
  5034. [ LinearSRGBColorSpace ]: {
  5035. primaries: REC709_PRIMARIES,
  5036. whitePoint: D65,
  5037. transfer: LinearTransfer,
  5038. toXYZ: LINEAR_REC709_TO_XYZ,
  5039. fromXYZ: XYZ_TO_LINEAR_REC709,
  5040. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5041. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5042. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5043. },
  5044. [ SRGBColorSpace ]: {
  5045. primaries: REC709_PRIMARIES,
  5046. whitePoint: D65,
  5047. transfer: SRGBTransfer,
  5048. toXYZ: LINEAR_REC709_TO_XYZ,
  5049. fromXYZ: XYZ_TO_LINEAR_REC709,
  5050. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5051. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5052. },
  5053. } );
  5054. return ColorManagement;
  5055. }
  5056. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5057. function SRGBToLinear( c ) {
  5058. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5059. }
  5060. function LinearToSRGB( c ) {
  5061. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5062. }
  5063. let _canvas;
  5064. /**
  5065. * A class containing utility functions for images.
  5066. *
  5067. * @hideconstructor
  5068. */
  5069. class ImageUtils {
  5070. /**
  5071. * Returns a data URI containing a representation of the given image.
  5072. *
  5073. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5074. * @param {string} [type='image/png'] - Indicates the image format.
  5075. * @return {string} The data URI.
  5076. */
  5077. static getDataURL( image, type = 'image/png' ) {
  5078. if ( /^data:/i.test( image.src ) ) {
  5079. return image.src;
  5080. }
  5081. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5082. return image.src;
  5083. }
  5084. let canvas;
  5085. if ( image instanceof HTMLCanvasElement ) {
  5086. canvas = image;
  5087. } else {
  5088. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5089. _canvas.width = image.width;
  5090. _canvas.height = image.height;
  5091. const context = _canvas.getContext( '2d' );
  5092. if ( image instanceof ImageData ) {
  5093. context.putImageData( image, 0, 0 );
  5094. } else {
  5095. context.drawImage( image, 0, 0, image.width, image.height );
  5096. }
  5097. canvas = _canvas;
  5098. }
  5099. return canvas.toDataURL( type );
  5100. }
  5101. /**
  5102. * Converts the given sRGB image data to linear color space.
  5103. *
  5104. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5105. * @return {HTMLCanvasElement|Object} The converted image.
  5106. */
  5107. static sRGBToLinear( image ) {
  5108. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5109. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5110. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5111. const canvas = createElementNS( 'canvas' );
  5112. canvas.width = image.width;
  5113. canvas.height = image.height;
  5114. const context = canvas.getContext( '2d' );
  5115. context.drawImage( image, 0, 0, image.width, image.height );
  5116. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5117. const data = imageData.data;
  5118. for ( let i = 0; i < data.length; i ++ ) {
  5119. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5120. }
  5121. context.putImageData( imageData, 0, 0 );
  5122. return canvas;
  5123. } else if ( image.data ) {
  5124. const data = image.data.slice( 0 );
  5125. for ( let i = 0; i < data.length; i ++ ) {
  5126. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5127. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5128. } else {
  5129. // assuming float
  5130. data[ i ] = SRGBToLinear( data[ i ] );
  5131. }
  5132. }
  5133. return {
  5134. data: data,
  5135. width: image.width,
  5136. height: image.height
  5137. };
  5138. } else {
  5139. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5140. return image;
  5141. }
  5142. }
  5143. }
  5144. let _sourceId = 0;
  5145. /**
  5146. * Represents the data source of a texture.
  5147. *
  5148. * The main purpose of this class is to decouple the data definition from the texture
  5149. * definition so the same data can be used with multiple texture instances.
  5150. */
  5151. class Source {
  5152. /**
  5153. * Constructs a new video texture.
  5154. *
  5155. * @param {any} [data=null] - The data definition of a texture.
  5156. */
  5157. constructor( data = null ) {
  5158. /**
  5159. * This flag can be used for type testing.
  5160. *
  5161. * @type {boolean}
  5162. * @readonly
  5163. * @default true
  5164. */
  5165. this.isSource = true;
  5166. /**
  5167. * The ID of the source.
  5168. *
  5169. * @name Source#id
  5170. * @type {number}
  5171. * @readonly
  5172. */
  5173. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5174. /**
  5175. * The UUID of the source.
  5176. *
  5177. * @type {string}
  5178. * @readonly
  5179. */
  5180. this.uuid = generateUUID();
  5181. /**
  5182. * The data definition of a texture.
  5183. *
  5184. * @type {any}
  5185. */
  5186. this.data = data;
  5187. /**
  5188. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5189. * provides more control on how texture data should be processed. When `dataReady` is set
  5190. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5191. * the data into the GPU memory.
  5192. *
  5193. * @type {boolean}
  5194. * @default true
  5195. */
  5196. this.dataReady = true;
  5197. /**
  5198. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5199. *
  5200. * @type {number}
  5201. * @readonly
  5202. * @default 0
  5203. */
  5204. this.version = 0;
  5205. }
  5206. /**
  5207. * Returns the dimensions of the source into the given target vector.
  5208. *
  5209. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5210. * @return {(Vector2|Vector3)} The dimensions of the source.
  5211. */
  5212. getSize( target ) {
  5213. const data = this.data;
  5214. if ( data instanceof HTMLVideoElement ) {
  5215. target.set( data.videoWidth, data.videoHeight, 0 );
  5216. } else if ( data instanceof VideoFrame ) {
  5217. target.set( data.displayHeight, data.displayWidth, 0 );
  5218. } else if ( data !== null ) {
  5219. target.set( data.width, data.height, data.depth || 0 );
  5220. } else {
  5221. target.set( 0, 0, 0 );
  5222. }
  5223. return target;
  5224. }
  5225. /**
  5226. * When the property is set to `true`, the engine allocates the memory
  5227. * for the texture (if necessary) and triggers the actual texture upload
  5228. * to the GPU next time the source is used.
  5229. *
  5230. * @type {boolean}
  5231. * @default false
  5232. * @param {boolean} value
  5233. */
  5234. set needsUpdate( value ) {
  5235. if ( value === true ) this.version ++;
  5236. }
  5237. /**
  5238. * Serializes the source into JSON.
  5239. *
  5240. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5241. * @return {Object} A JSON object representing the serialized source.
  5242. * @see {@link ObjectLoader#parse}
  5243. */
  5244. toJSON( meta ) {
  5245. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5246. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5247. return meta.images[ this.uuid ];
  5248. }
  5249. const output = {
  5250. uuid: this.uuid,
  5251. url: ''
  5252. };
  5253. const data = this.data;
  5254. if ( data !== null ) {
  5255. let url;
  5256. if ( Array.isArray( data ) ) {
  5257. // cube texture
  5258. url = [];
  5259. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5260. if ( data[ i ].isDataTexture ) {
  5261. url.push( serializeImage( data[ i ].image ) );
  5262. } else {
  5263. url.push( serializeImage( data[ i ] ) );
  5264. }
  5265. }
  5266. } else {
  5267. // texture
  5268. url = serializeImage( data );
  5269. }
  5270. output.url = url;
  5271. }
  5272. if ( ! isRootObject ) {
  5273. meta.images[ this.uuid ] = output;
  5274. }
  5275. return output;
  5276. }
  5277. }
  5278. function serializeImage( image ) {
  5279. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5280. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5281. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5282. // default images
  5283. return ImageUtils.getDataURL( image );
  5284. } else {
  5285. if ( image.data ) {
  5286. // images of DataTexture
  5287. return {
  5288. data: Array.from( image.data ),
  5289. width: image.width,
  5290. height: image.height,
  5291. type: image.data.constructor.name
  5292. };
  5293. } else {
  5294. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  5295. return {};
  5296. }
  5297. }
  5298. }
  5299. let _textureId = 0;
  5300. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5301. /**
  5302. * Base class for all textures.
  5303. *
  5304. * Note: After the initial use of a texture, its dimensions, format, and type
  5305. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5306. *
  5307. * @augments EventDispatcher
  5308. */
  5309. class Texture extends EventDispatcher {
  5310. /**
  5311. * Constructs a new texture.
  5312. *
  5313. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5314. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5315. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5316. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5317. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5318. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5319. * @param {number} [format=RGBAFormat] - The texture format.
  5320. * @param {number} [type=UnsignedByteType] - The texture type.
  5321. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5322. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5323. */
  5324. 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 ) {
  5325. super();
  5326. /**
  5327. * This flag can be used for type testing.
  5328. *
  5329. * @type {boolean}
  5330. * @readonly
  5331. * @default true
  5332. */
  5333. this.isTexture = true;
  5334. /**
  5335. * The ID of the texture.
  5336. *
  5337. * @name Texture#id
  5338. * @type {number}
  5339. * @readonly
  5340. */
  5341. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5342. /**
  5343. * The UUID of the material.
  5344. *
  5345. * @type {string}
  5346. * @readonly
  5347. */
  5348. this.uuid = generateUUID();
  5349. /**
  5350. * The name of the material.
  5351. *
  5352. * @type {string}
  5353. */
  5354. this.name = '';
  5355. /**
  5356. * The data definition of a texture. A reference to the data source can be
  5357. * shared across textures. This is often useful in context of spritesheets
  5358. * where multiple textures render the same data but with different texture
  5359. * transformations.
  5360. *
  5361. * @type {Source}
  5362. */
  5363. this.source = new Source( image );
  5364. /**
  5365. * An array holding user-defined mipmaps.
  5366. *
  5367. * @type {Array<Object>}
  5368. */
  5369. this.mipmaps = [];
  5370. /**
  5371. * How the texture is applied to the object. The value `UVMapping`
  5372. * is the default, where texture or uv coordinates are used to apply the map.
  5373. *
  5374. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5375. * @default UVMapping
  5376. */
  5377. this.mapping = mapping;
  5378. /**
  5379. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5380. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5381. *
  5382. * @type {number}
  5383. * @default 0
  5384. */
  5385. this.channel = 0;
  5386. /**
  5387. * This defines how the texture is wrapped horizontally and corresponds to
  5388. * *U* in UV mapping.
  5389. *
  5390. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5391. * @default ClampToEdgeWrapping
  5392. */
  5393. this.wrapS = wrapS;
  5394. /**
  5395. * This defines how the texture is wrapped horizontally and corresponds to
  5396. * *V* in UV mapping.
  5397. *
  5398. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5399. * @default ClampToEdgeWrapping
  5400. */
  5401. this.wrapT = wrapT;
  5402. /**
  5403. * How the texture is sampled when a texel covers more than one pixel.
  5404. *
  5405. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5406. * @default LinearFilter
  5407. */
  5408. this.magFilter = magFilter;
  5409. /**
  5410. * How the texture is sampled when a texel covers less than one pixel.
  5411. *
  5412. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5413. * @default LinearMipmapLinearFilter
  5414. */
  5415. this.minFilter = minFilter;
  5416. /**
  5417. * The number of samples taken along the axis through the pixel that has the
  5418. * highest density of texels. By default, this value is `1`. A higher value
  5419. * gives a less blurry result than a basic mipmap, at the cost of more
  5420. * texture samples being used.
  5421. *
  5422. * @type {number}
  5423. * @default 0
  5424. */
  5425. this.anisotropy = anisotropy;
  5426. /**
  5427. * The format of the texture.
  5428. *
  5429. * @type {number}
  5430. * @default RGBAFormat
  5431. */
  5432. this.format = format;
  5433. /**
  5434. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5435. * defines how the texture data is going to be stored on the GPU.
  5436. *
  5437. * This property allows to overwrite the default format.
  5438. *
  5439. * @type {?string}
  5440. * @default null
  5441. */
  5442. this.internalFormat = null;
  5443. /**
  5444. * The data type of the texture.
  5445. *
  5446. * @type {number}
  5447. * @default UnsignedByteType
  5448. */
  5449. this.type = type;
  5450. /**
  5451. * How much a single repetition of the texture is offset from the beginning,
  5452. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5453. *
  5454. * @type {Vector2}
  5455. * @default (0,0)
  5456. */
  5457. this.offset = new Vector2( 0, 0 );
  5458. /**
  5459. * How many times the texture is repeated across the surface, in each
  5460. * direction U and V. If repeat is set greater than `1` in either direction,
  5461. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5462. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5463. *
  5464. * @type {Vector2}
  5465. * @default (1,1)
  5466. */
  5467. this.repeat = new Vector2( 1, 1 );
  5468. /**
  5469. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5470. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5471. *
  5472. * @type {Vector2}
  5473. * @default (0,0)
  5474. */
  5475. this.center = new Vector2( 0, 0 );
  5476. /**
  5477. * How much the texture is rotated around the center point, in radians.
  5478. * Positive values are counter-clockwise.
  5479. *
  5480. * @type {number}
  5481. * @default 0
  5482. */
  5483. this.rotation = 0;
  5484. /**
  5485. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5486. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5487. * {@link Texture#rotation}, and {@link Texture#center}.
  5488. *
  5489. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5490. *
  5491. * @type {boolean}
  5492. * @default true
  5493. */
  5494. this.matrixAutoUpdate = true;
  5495. /**
  5496. * The uv-transformation matrix of the texture.
  5497. *
  5498. * @type {Matrix3}
  5499. */
  5500. this.matrix = new Matrix3();
  5501. /**
  5502. * Whether to generate mipmaps (if possible) for a texture.
  5503. *
  5504. * Set this to `false` if you are creating mipmaps manually.
  5505. *
  5506. * @type {boolean}
  5507. * @default true
  5508. */
  5509. this.generateMipmaps = true;
  5510. /**
  5511. * If set to `true`, the alpha channel, if present, is multiplied into the
  5512. * color channels when the texture is uploaded to the GPU.
  5513. *
  5514. * Note that this property has no effect when using `ImageBitmap`. You need to
  5515. * configure premultiply alpha on bitmap creation instead.
  5516. *
  5517. * @type {boolean}
  5518. * @default false
  5519. */
  5520. this.premultiplyAlpha = false;
  5521. /**
  5522. * If set to `true`, the texture is flipped along the vertical axis when
  5523. * uploaded to the GPU.
  5524. *
  5525. * Note that this property has no effect when using `ImageBitmap`. You need to
  5526. * configure the flip on bitmap creation instead.
  5527. *
  5528. * @type {boolean}
  5529. * @default true
  5530. */
  5531. this.flipY = true;
  5532. /**
  5533. * Specifies the alignment requirements for the start of each pixel row in memory.
  5534. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5535. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5536. *
  5537. * @type {number}
  5538. * @default 4
  5539. */
  5540. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5541. /**
  5542. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5543. *
  5544. * @type {string}
  5545. * @default NoColorSpace
  5546. */
  5547. this.colorSpace = colorSpace;
  5548. /**
  5549. * An object that can be used to store custom data about the texture. It
  5550. * should not hold references to functions as these will not be cloned.
  5551. *
  5552. * @type {Object}
  5553. */
  5554. this.userData = {};
  5555. /**
  5556. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5557. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5558. *
  5559. * @type {Array<Object>}
  5560. */
  5561. this.updateRanges = [];
  5562. /**
  5563. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5564. *
  5565. * @type {number}
  5566. * @readonly
  5567. * @default 0
  5568. */
  5569. this.version = 0;
  5570. /**
  5571. * A callback function, called when the texture is updated (e.g., when
  5572. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5573. *
  5574. * @type {?Function}
  5575. * @default null
  5576. */
  5577. this.onUpdate = null;
  5578. /**
  5579. * An optional back reference to the textures render target.
  5580. *
  5581. * @type {?(RenderTarget|WebGLRenderTarget)}
  5582. * @default null
  5583. */
  5584. this.renderTarget = null;
  5585. /**
  5586. * Indicates whether a texture belongs to a render target or not.
  5587. *
  5588. * @type {boolean}
  5589. * @readonly
  5590. * @default false
  5591. */
  5592. this.isRenderTargetTexture = false;
  5593. /**
  5594. * Indicates if a texture should be handled like a texture array.
  5595. *
  5596. * @type {boolean}
  5597. * @readonly
  5598. * @default false
  5599. */
  5600. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5601. /**
  5602. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5603. * (only relevant for render target textures).
  5604. *
  5605. * @type {number}
  5606. * @readonly
  5607. * @default 0
  5608. */
  5609. this.pmremVersion = 0;
  5610. }
  5611. /**
  5612. * The width of the texture in pixels.
  5613. */
  5614. get width() {
  5615. return this.source.getSize( _tempVec3 ).x;
  5616. }
  5617. /**
  5618. * The height of the texture in pixels.
  5619. */
  5620. get height() {
  5621. return this.source.getSize( _tempVec3 ).y;
  5622. }
  5623. /**
  5624. * The depth of the texture in pixels.
  5625. */
  5626. get depth() {
  5627. return this.source.getSize( _tempVec3 ).z;
  5628. }
  5629. /**
  5630. * The image object holding the texture data.
  5631. *
  5632. * @type {?Object}
  5633. */
  5634. get image() {
  5635. return this.source.data;
  5636. }
  5637. set image( value = null ) {
  5638. this.source.data = value;
  5639. }
  5640. /**
  5641. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5642. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5643. */
  5644. updateMatrix() {
  5645. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5646. }
  5647. /**
  5648. * Adds a range of data in the data texture to be updated on the GPU.
  5649. *
  5650. * @param {number} start - Position at which to start update.
  5651. * @param {number} count - The number of components to update.
  5652. */
  5653. addUpdateRange( start, count ) {
  5654. this.updateRanges.push( { start, count } );
  5655. }
  5656. /**
  5657. * Clears the update ranges.
  5658. */
  5659. clearUpdateRanges() {
  5660. this.updateRanges.length = 0;
  5661. }
  5662. /**
  5663. * Returns a new texture with copied values from this instance.
  5664. *
  5665. * @return {Texture} A clone of this instance.
  5666. */
  5667. clone() {
  5668. return new this.constructor().copy( this );
  5669. }
  5670. /**
  5671. * Copies the values of the given texture to this instance.
  5672. *
  5673. * @param {Texture} source - The texture to copy.
  5674. * @return {Texture} A reference to this instance.
  5675. */
  5676. copy( source ) {
  5677. this.name = source.name;
  5678. this.source = source.source;
  5679. this.mipmaps = source.mipmaps.slice( 0 );
  5680. this.mapping = source.mapping;
  5681. this.channel = source.channel;
  5682. this.wrapS = source.wrapS;
  5683. this.wrapT = source.wrapT;
  5684. this.magFilter = source.magFilter;
  5685. this.minFilter = source.minFilter;
  5686. this.anisotropy = source.anisotropy;
  5687. this.format = source.format;
  5688. this.internalFormat = source.internalFormat;
  5689. this.type = source.type;
  5690. this.offset.copy( source.offset );
  5691. this.repeat.copy( source.repeat );
  5692. this.center.copy( source.center );
  5693. this.rotation = source.rotation;
  5694. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5695. this.matrix.copy( source.matrix );
  5696. this.generateMipmaps = source.generateMipmaps;
  5697. this.premultiplyAlpha = source.premultiplyAlpha;
  5698. this.flipY = source.flipY;
  5699. this.unpackAlignment = source.unpackAlignment;
  5700. this.colorSpace = source.colorSpace;
  5701. this.renderTarget = source.renderTarget;
  5702. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5703. this.isArrayTexture = source.isArrayTexture;
  5704. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5705. this.needsUpdate = true;
  5706. return this;
  5707. }
  5708. /**
  5709. * Sets this texture's properties based on `values`.
  5710. * @param {Object} values - A container with texture parameters.
  5711. */
  5712. setValues( values ) {
  5713. for ( const key in values ) {
  5714. const newValue = values[ key ];
  5715. if ( newValue === undefined ) {
  5716. console.warn( `THREE.Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5717. continue;
  5718. }
  5719. const currentValue = this[ key ];
  5720. if ( currentValue === undefined ) {
  5721. console.warn( `THREE.Texture.setValues(): property '${ key }' does not exist.` );
  5722. continue;
  5723. }
  5724. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5725. currentValue.copy( newValue );
  5726. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5727. currentValue.copy( newValue );
  5728. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5729. currentValue.copy( newValue );
  5730. } else {
  5731. this[ key ] = newValue;
  5732. }
  5733. }
  5734. }
  5735. /**
  5736. * Serializes the texture into JSON.
  5737. *
  5738. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5739. * @return {Object} A JSON object representing the serialized texture.
  5740. * @see {@link ObjectLoader#parse}
  5741. */
  5742. toJSON( meta ) {
  5743. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5744. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5745. return meta.textures[ this.uuid ];
  5746. }
  5747. const output = {
  5748. metadata: {
  5749. version: 4.7,
  5750. type: 'Texture',
  5751. generator: 'Texture.toJSON'
  5752. },
  5753. uuid: this.uuid,
  5754. name: this.name,
  5755. image: this.source.toJSON( meta ).uuid,
  5756. mapping: this.mapping,
  5757. channel: this.channel,
  5758. repeat: [ this.repeat.x, this.repeat.y ],
  5759. offset: [ this.offset.x, this.offset.y ],
  5760. center: [ this.center.x, this.center.y ],
  5761. rotation: this.rotation,
  5762. wrap: [ this.wrapS, this.wrapT ],
  5763. format: this.format,
  5764. internalFormat: this.internalFormat,
  5765. type: this.type,
  5766. colorSpace: this.colorSpace,
  5767. minFilter: this.minFilter,
  5768. magFilter: this.magFilter,
  5769. anisotropy: this.anisotropy,
  5770. flipY: this.flipY,
  5771. generateMipmaps: this.generateMipmaps,
  5772. premultiplyAlpha: this.premultiplyAlpha,
  5773. unpackAlignment: this.unpackAlignment
  5774. };
  5775. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5776. if ( ! isRootObject ) {
  5777. meta.textures[ this.uuid ] = output;
  5778. }
  5779. return output;
  5780. }
  5781. /**
  5782. * Frees the GPU-related resources allocated by this instance. Call this
  5783. * method whenever this instance is no longer used in your app.
  5784. *
  5785. * @fires Texture#dispose
  5786. */
  5787. dispose() {
  5788. /**
  5789. * Fires when the texture has been disposed of.
  5790. *
  5791. * @event Texture#dispose
  5792. * @type {Object}
  5793. */
  5794. this.dispatchEvent( { type: 'dispose' } );
  5795. }
  5796. /**
  5797. * Transforms the given uv vector with the textures uv transformation matrix.
  5798. *
  5799. * @param {Vector2} uv - The uv vector.
  5800. * @return {Vector2} The transformed uv vector.
  5801. */
  5802. transformUv( uv ) {
  5803. if ( this.mapping !== UVMapping ) return uv;
  5804. uv.applyMatrix3( this.matrix );
  5805. if ( uv.x < 0 || uv.x > 1 ) {
  5806. switch ( this.wrapS ) {
  5807. case RepeatWrapping:
  5808. uv.x = uv.x - Math.floor( uv.x );
  5809. break;
  5810. case ClampToEdgeWrapping:
  5811. uv.x = uv.x < 0 ? 0 : 1;
  5812. break;
  5813. case MirroredRepeatWrapping:
  5814. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5815. uv.x = Math.ceil( uv.x ) - uv.x;
  5816. } else {
  5817. uv.x = uv.x - Math.floor( uv.x );
  5818. }
  5819. break;
  5820. }
  5821. }
  5822. if ( uv.y < 0 || uv.y > 1 ) {
  5823. switch ( this.wrapT ) {
  5824. case RepeatWrapping:
  5825. uv.y = uv.y - Math.floor( uv.y );
  5826. break;
  5827. case ClampToEdgeWrapping:
  5828. uv.y = uv.y < 0 ? 0 : 1;
  5829. break;
  5830. case MirroredRepeatWrapping:
  5831. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5832. uv.y = Math.ceil( uv.y ) - uv.y;
  5833. } else {
  5834. uv.y = uv.y - Math.floor( uv.y );
  5835. }
  5836. break;
  5837. }
  5838. }
  5839. if ( this.flipY ) {
  5840. uv.y = 1 - uv.y;
  5841. }
  5842. return uv;
  5843. }
  5844. /**
  5845. * Setting this property to `true` indicates the engine the texture
  5846. * must be updated in the next render. This triggers a texture upload
  5847. * to the GPU and ensures correct texture parameter configuration.
  5848. *
  5849. * @type {boolean}
  5850. * @default false
  5851. * @param {boolean} value
  5852. */
  5853. set needsUpdate( value ) {
  5854. if ( value === true ) {
  5855. this.version ++;
  5856. this.source.needsUpdate = true;
  5857. }
  5858. }
  5859. /**
  5860. * Setting this property to `true` indicates the engine the PMREM
  5861. * must be regenerated.
  5862. *
  5863. * @type {boolean}
  5864. * @default false
  5865. * @param {boolean} value
  5866. */
  5867. set needsPMREMUpdate( value ) {
  5868. if ( value === true ) {
  5869. this.pmremVersion ++;
  5870. }
  5871. }
  5872. }
  5873. /**
  5874. * The default image for all textures.
  5875. *
  5876. * @static
  5877. * @type {?Image}
  5878. * @default null
  5879. */
  5880. Texture.DEFAULT_IMAGE = null;
  5881. /**
  5882. * The default mapping for all textures.
  5883. *
  5884. * @static
  5885. * @type {number}
  5886. * @default UVMapping
  5887. */
  5888. Texture.DEFAULT_MAPPING = UVMapping;
  5889. /**
  5890. * The default anisotropy value for all textures.
  5891. *
  5892. * @static
  5893. * @type {number}
  5894. * @default 1
  5895. */
  5896. Texture.DEFAULT_ANISOTROPY = 1;
  5897. /**
  5898. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5899. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5900. *
  5901. * - A point in 4D space.
  5902. * - A direction and length in 4D space. In three.js the length will
  5903. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5904. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5905. * - Any arbitrary ordered quadruplet of numbers.
  5906. *
  5907. * There are other things a 4D vector can be used to represent, however these
  5908. * are the most common uses in *three.js*.
  5909. *
  5910. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5911. * the corresponding order.
  5912. * ```js
  5913. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5914. *
  5915. * //no arguments; will be initialised to (0, 0, 0, 1)
  5916. * const b = new THREE.Vector4( );
  5917. *
  5918. * const d = a.dot( b );
  5919. * ```
  5920. */
  5921. class Vector4 {
  5922. /**
  5923. * Constructs a new 4D vector.
  5924. *
  5925. * @param {number} [x=0] - The x value of this vector.
  5926. * @param {number} [y=0] - The y value of this vector.
  5927. * @param {number} [z=0] - The z value of this vector.
  5928. * @param {number} [w=1] - The w value of this vector.
  5929. */
  5930. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5931. /**
  5932. * This flag can be used for type testing.
  5933. *
  5934. * @type {boolean}
  5935. * @readonly
  5936. * @default true
  5937. */
  5938. Vector4.prototype.isVector4 = true;
  5939. /**
  5940. * The x value of this vector.
  5941. *
  5942. * @type {number}
  5943. */
  5944. this.x = x;
  5945. /**
  5946. * The y value of this vector.
  5947. *
  5948. * @type {number}
  5949. */
  5950. this.y = y;
  5951. /**
  5952. * The z value of this vector.
  5953. *
  5954. * @type {number}
  5955. */
  5956. this.z = z;
  5957. /**
  5958. * The w value of this vector.
  5959. *
  5960. * @type {number}
  5961. */
  5962. this.w = w;
  5963. }
  5964. /**
  5965. * Alias for {@link Vector4#z}.
  5966. *
  5967. * @type {number}
  5968. */
  5969. get width() {
  5970. return this.z;
  5971. }
  5972. set width( value ) {
  5973. this.z = value;
  5974. }
  5975. /**
  5976. * Alias for {@link Vector4#w}.
  5977. *
  5978. * @type {number}
  5979. */
  5980. get height() {
  5981. return this.w;
  5982. }
  5983. set height( value ) {
  5984. this.w = value;
  5985. }
  5986. /**
  5987. * Sets the vector components.
  5988. *
  5989. * @param {number} x - The value of the x component.
  5990. * @param {number} y - The value of the y component.
  5991. * @param {number} z - The value of the z component.
  5992. * @param {number} w - The value of the w component.
  5993. * @return {Vector4} A reference to this vector.
  5994. */
  5995. set( x, y, z, w ) {
  5996. this.x = x;
  5997. this.y = y;
  5998. this.z = z;
  5999. this.w = w;
  6000. return this;
  6001. }
  6002. /**
  6003. * Sets the vector components to the same value.
  6004. *
  6005. * @param {number} scalar - The value to set for all vector components.
  6006. * @return {Vector4} A reference to this vector.
  6007. */
  6008. setScalar( scalar ) {
  6009. this.x = scalar;
  6010. this.y = scalar;
  6011. this.z = scalar;
  6012. this.w = scalar;
  6013. return this;
  6014. }
  6015. /**
  6016. * Sets the vector's x component to the given value
  6017. *
  6018. * @param {number} x - The value to set.
  6019. * @return {Vector4} A reference to this vector.
  6020. */
  6021. setX( x ) {
  6022. this.x = x;
  6023. return this;
  6024. }
  6025. /**
  6026. * Sets the vector's y component to the given value
  6027. *
  6028. * @param {number} y - The value to set.
  6029. * @return {Vector4} A reference to this vector.
  6030. */
  6031. setY( y ) {
  6032. this.y = y;
  6033. return this;
  6034. }
  6035. /**
  6036. * Sets the vector's z component to the given value
  6037. *
  6038. * @param {number} z - The value to set.
  6039. * @return {Vector4} A reference to this vector.
  6040. */
  6041. setZ( z ) {
  6042. this.z = z;
  6043. return this;
  6044. }
  6045. /**
  6046. * Sets the vector's w component to the given value
  6047. *
  6048. * @param {number} w - The value to set.
  6049. * @return {Vector4} A reference to this vector.
  6050. */
  6051. setW( w ) {
  6052. this.w = w;
  6053. return this;
  6054. }
  6055. /**
  6056. * Allows to set a vector component with an index.
  6057. *
  6058. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6059. * `2` equals to z, `3` equals to w.
  6060. * @param {number} value - The value to set.
  6061. * @return {Vector4} A reference to this vector.
  6062. */
  6063. setComponent( index, value ) {
  6064. switch ( index ) {
  6065. case 0: this.x = value; break;
  6066. case 1: this.y = value; break;
  6067. case 2: this.z = value; break;
  6068. case 3: this.w = value; break;
  6069. default: throw new Error( 'index is out of range: ' + index );
  6070. }
  6071. return this;
  6072. }
  6073. /**
  6074. * Returns the value of the vector component which matches the given index.
  6075. *
  6076. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6077. * `2` equals to z, `3` equals to w.
  6078. * @return {number} A vector component value.
  6079. */
  6080. getComponent( index ) {
  6081. switch ( index ) {
  6082. case 0: return this.x;
  6083. case 1: return this.y;
  6084. case 2: return this.z;
  6085. case 3: return this.w;
  6086. default: throw new Error( 'index is out of range: ' + index );
  6087. }
  6088. }
  6089. /**
  6090. * Returns a new vector with copied values from this instance.
  6091. *
  6092. * @return {Vector4} A clone of this instance.
  6093. */
  6094. clone() {
  6095. return new this.constructor( this.x, this.y, this.z, this.w );
  6096. }
  6097. /**
  6098. * Copies the values of the given vector to this instance.
  6099. *
  6100. * @param {Vector3|Vector4} v - The vector to copy.
  6101. * @return {Vector4} A reference to this vector.
  6102. */
  6103. copy( v ) {
  6104. this.x = v.x;
  6105. this.y = v.y;
  6106. this.z = v.z;
  6107. this.w = ( v.w !== undefined ) ? v.w : 1;
  6108. return this;
  6109. }
  6110. /**
  6111. * Adds the given vector to this instance.
  6112. *
  6113. * @param {Vector4} v - The vector to add.
  6114. * @return {Vector4} A reference to this vector.
  6115. */
  6116. add( v ) {
  6117. this.x += v.x;
  6118. this.y += v.y;
  6119. this.z += v.z;
  6120. this.w += v.w;
  6121. return this;
  6122. }
  6123. /**
  6124. * Adds the given scalar value to all components of this instance.
  6125. *
  6126. * @param {number} s - The scalar to add.
  6127. * @return {Vector4} A reference to this vector.
  6128. */
  6129. addScalar( s ) {
  6130. this.x += s;
  6131. this.y += s;
  6132. this.z += s;
  6133. this.w += s;
  6134. return this;
  6135. }
  6136. /**
  6137. * Adds the given vectors and stores the result in this instance.
  6138. *
  6139. * @param {Vector4} a - The first vector.
  6140. * @param {Vector4} b - The second vector.
  6141. * @return {Vector4} A reference to this vector.
  6142. */
  6143. addVectors( a, b ) {
  6144. this.x = a.x + b.x;
  6145. this.y = a.y + b.y;
  6146. this.z = a.z + b.z;
  6147. this.w = a.w + b.w;
  6148. return this;
  6149. }
  6150. /**
  6151. * Adds the given vector scaled by the given factor to this instance.
  6152. *
  6153. * @param {Vector4} v - The vector.
  6154. * @param {number} s - The factor that scales `v`.
  6155. * @return {Vector4} A reference to this vector.
  6156. */
  6157. addScaledVector( v, s ) {
  6158. this.x += v.x * s;
  6159. this.y += v.y * s;
  6160. this.z += v.z * s;
  6161. this.w += v.w * s;
  6162. return this;
  6163. }
  6164. /**
  6165. * Subtracts the given vector from this instance.
  6166. *
  6167. * @param {Vector4} v - The vector to subtract.
  6168. * @return {Vector4} A reference to this vector.
  6169. */
  6170. sub( v ) {
  6171. this.x -= v.x;
  6172. this.y -= v.y;
  6173. this.z -= v.z;
  6174. this.w -= v.w;
  6175. return this;
  6176. }
  6177. /**
  6178. * Subtracts the given scalar value from all components of this instance.
  6179. *
  6180. * @param {number} s - The scalar to subtract.
  6181. * @return {Vector4} A reference to this vector.
  6182. */
  6183. subScalar( s ) {
  6184. this.x -= s;
  6185. this.y -= s;
  6186. this.z -= s;
  6187. this.w -= s;
  6188. return this;
  6189. }
  6190. /**
  6191. * Subtracts the given vectors and stores the result in this instance.
  6192. *
  6193. * @param {Vector4} a - The first vector.
  6194. * @param {Vector4} b - The second vector.
  6195. * @return {Vector4} A reference to this vector.
  6196. */
  6197. subVectors( a, b ) {
  6198. this.x = a.x - b.x;
  6199. this.y = a.y - b.y;
  6200. this.z = a.z - b.z;
  6201. this.w = a.w - b.w;
  6202. return this;
  6203. }
  6204. /**
  6205. * Multiplies the given vector with this instance.
  6206. *
  6207. * @param {Vector4} v - The vector to multiply.
  6208. * @return {Vector4} A reference to this vector.
  6209. */
  6210. multiply( v ) {
  6211. this.x *= v.x;
  6212. this.y *= v.y;
  6213. this.z *= v.z;
  6214. this.w *= v.w;
  6215. return this;
  6216. }
  6217. /**
  6218. * Multiplies the given scalar value with all components of this instance.
  6219. *
  6220. * @param {number} scalar - The scalar to multiply.
  6221. * @return {Vector4} A reference to this vector.
  6222. */
  6223. multiplyScalar( scalar ) {
  6224. this.x *= scalar;
  6225. this.y *= scalar;
  6226. this.z *= scalar;
  6227. this.w *= scalar;
  6228. return this;
  6229. }
  6230. /**
  6231. * Multiplies this vector with the given 4x4 matrix.
  6232. *
  6233. * @param {Matrix4} m - The 4x4 matrix.
  6234. * @return {Vector4} A reference to this vector.
  6235. */
  6236. applyMatrix4( m ) {
  6237. const x = this.x, y = this.y, z = this.z, w = this.w;
  6238. const e = m.elements;
  6239. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6240. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6241. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6242. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6243. return this;
  6244. }
  6245. /**
  6246. * Divides this instance by the given vector.
  6247. *
  6248. * @param {Vector4} v - The vector to divide.
  6249. * @return {Vector4} A reference to this vector.
  6250. */
  6251. divide( v ) {
  6252. this.x /= v.x;
  6253. this.y /= v.y;
  6254. this.z /= v.z;
  6255. this.w /= v.w;
  6256. return this;
  6257. }
  6258. /**
  6259. * Divides this vector by the given scalar.
  6260. *
  6261. * @param {number} scalar - The scalar to divide.
  6262. * @return {Vector4} A reference to this vector.
  6263. */
  6264. divideScalar( scalar ) {
  6265. return this.multiplyScalar( 1 / scalar );
  6266. }
  6267. /**
  6268. * Sets the x, y and z components of this
  6269. * vector to the quaternion's axis and w to the angle.
  6270. *
  6271. * @param {Quaternion} q - The Quaternion to set.
  6272. * @return {Vector4} A reference to this vector.
  6273. */
  6274. setAxisAngleFromQuaternion( q ) {
  6275. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6276. // q is assumed to be normalized
  6277. this.w = 2 * Math.acos( q.w );
  6278. const s = Math.sqrt( 1 - q.w * q.w );
  6279. if ( s < 0.0001 ) {
  6280. this.x = 1;
  6281. this.y = 0;
  6282. this.z = 0;
  6283. } else {
  6284. this.x = q.x / s;
  6285. this.y = q.y / s;
  6286. this.z = q.z / s;
  6287. }
  6288. return this;
  6289. }
  6290. /**
  6291. * Sets the x, y and z components of this
  6292. * vector to the axis of rotation and w to the angle.
  6293. *
  6294. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6295. * @return {Vector4} A reference to this vector.
  6296. */
  6297. setAxisAngleFromRotationMatrix( m ) {
  6298. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6299. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6300. let angle, x, y, z; // variables for result
  6301. const epsilon = 0.01, // margin to allow for rounding errors
  6302. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6303. te = m.elements,
  6304. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6305. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6306. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6307. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6308. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6309. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6310. // singularity found
  6311. // first check for identity matrix which must have +1 for all terms
  6312. // in leading diagonal and zero in other terms
  6313. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6314. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6315. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6316. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6317. // this singularity is identity matrix so angle = 0
  6318. this.set( 1, 0, 0, 0 );
  6319. return this; // zero angle, arbitrary axis
  6320. }
  6321. // otherwise this singularity is angle = 180
  6322. angle = Math.PI;
  6323. const xx = ( m11 + 1 ) / 2;
  6324. const yy = ( m22 + 1 ) / 2;
  6325. const zz = ( m33 + 1 ) / 2;
  6326. const xy = ( m12 + m21 ) / 4;
  6327. const xz = ( m13 + m31 ) / 4;
  6328. const yz = ( m23 + m32 ) / 4;
  6329. if ( ( xx > yy ) && ( xx > zz ) ) {
  6330. // m11 is the largest diagonal term
  6331. if ( xx < epsilon ) {
  6332. x = 0;
  6333. y = 0.707106781;
  6334. z = 0.707106781;
  6335. } else {
  6336. x = Math.sqrt( xx );
  6337. y = xy / x;
  6338. z = xz / x;
  6339. }
  6340. } else if ( yy > zz ) {
  6341. // m22 is the largest diagonal term
  6342. if ( yy < epsilon ) {
  6343. x = 0.707106781;
  6344. y = 0;
  6345. z = 0.707106781;
  6346. } else {
  6347. y = Math.sqrt( yy );
  6348. x = xy / y;
  6349. z = yz / y;
  6350. }
  6351. } else {
  6352. // m33 is the largest diagonal term so base result on this
  6353. if ( zz < epsilon ) {
  6354. x = 0.707106781;
  6355. y = 0.707106781;
  6356. z = 0;
  6357. } else {
  6358. z = Math.sqrt( zz );
  6359. x = xz / z;
  6360. y = yz / z;
  6361. }
  6362. }
  6363. this.set( x, y, z, angle );
  6364. return this; // return 180 deg rotation
  6365. }
  6366. // as we have reached here there are no singularities so we can handle normally
  6367. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6368. ( m13 - m31 ) * ( m13 - m31 ) +
  6369. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6370. if ( Math.abs( s ) < 0.001 ) s = 1;
  6371. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6372. // caught by singularity test above, but I've left it in just in case
  6373. this.x = ( m32 - m23 ) / s;
  6374. this.y = ( m13 - m31 ) / s;
  6375. this.z = ( m21 - m12 ) / s;
  6376. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6377. return this;
  6378. }
  6379. /**
  6380. * Sets the vector components to the position elements of the
  6381. * given transformation matrix.
  6382. *
  6383. * @param {Matrix4} m - The 4x4 matrix.
  6384. * @return {Vector4} A reference to this vector.
  6385. */
  6386. setFromMatrixPosition( m ) {
  6387. const e = m.elements;
  6388. this.x = e[ 12 ];
  6389. this.y = e[ 13 ];
  6390. this.z = e[ 14 ];
  6391. this.w = e[ 15 ];
  6392. return this;
  6393. }
  6394. /**
  6395. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6396. * value, replace that value with the corresponding min value.
  6397. *
  6398. * @param {Vector4} v - The vector.
  6399. * @return {Vector4} A reference to this vector.
  6400. */
  6401. min( v ) {
  6402. this.x = Math.min( this.x, v.x );
  6403. this.y = Math.min( this.y, v.y );
  6404. this.z = Math.min( this.z, v.z );
  6405. this.w = Math.min( this.w, v.w );
  6406. return this;
  6407. }
  6408. /**
  6409. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6410. * value, replace that value with the corresponding max value.
  6411. *
  6412. * @param {Vector4} v - The vector.
  6413. * @return {Vector4} A reference to this vector.
  6414. */
  6415. max( v ) {
  6416. this.x = Math.max( this.x, v.x );
  6417. this.y = Math.max( this.y, v.y );
  6418. this.z = Math.max( this.z, v.z );
  6419. this.w = Math.max( this.w, v.w );
  6420. return this;
  6421. }
  6422. /**
  6423. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6424. * value, it is replaced by the corresponding value.
  6425. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6426. * it is replaced by the corresponding value.
  6427. *
  6428. * @param {Vector4} min - The minimum x, y and z values.
  6429. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6430. * @return {Vector4} A reference to this vector.
  6431. */
  6432. clamp( min, max ) {
  6433. // assumes min < max, componentwise
  6434. this.x = clamp( this.x, min.x, max.x );
  6435. this.y = clamp( this.y, min.y, max.y );
  6436. this.z = clamp( this.z, min.z, max.z );
  6437. this.w = clamp( this.w, min.w, max.w );
  6438. return this;
  6439. }
  6440. /**
  6441. * If this vector's x, y, z or w values are greater than the max value, they are
  6442. * replaced by the max value.
  6443. * If this vector's x, y, z or w values are less than the min value, they are
  6444. * replaced by the min value.
  6445. *
  6446. * @param {number} minVal - The minimum value the components will be clamped to.
  6447. * @param {number} maxVal - The maximum value the components will be clamped to.
  6448. * @return {Vector4} A reference to this vector.
  6449. */
  6450. clampScalar( minVal, maxVal ) {
  6451. this.x = clamp( this.x, minVal, maxVal );
  6452. this.y = clamp( this.y, minVal, maxVal );
  6453. this.z = clamp( this.z, minVal, maxVal );
  6454. this.w = clamp( this.w, minVal, maxVal );
  6455. return this;
  6456. }
  6457. /**
  6458. * If this vector's length is greater than the max value, it is replaced by
  6459. * the max value.
  6460. * If this vector's length is less than the min value, it is replaced by the
  6461. * min value.
  6462. *
  6463. * @param {number} min - The minimum value the vector length will be clamped to.
  6464. * @param {number} max - The maximum value the vector length will be clamped to.
  6465. * @return {Vector4} A reference to this vector.
  6466. */
  6467. clampLength( min, max ) {
  6468. const length = this.length();
  6469. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6470. }
  6471. /**
  6472. * The components of this vector are rounded down to the nearest integer value.
  6473. *
  6474. * @return {Vector4} A reference to this vector.
  6475. */
  6476. floor() {
  6477. this.x = Math.floor( this.x );
  6478. this.y = Math.floor( this.y );
  6479. this.z = Math.floor( this.z );
  6480. this.w = Math.floor( this.w );
  6481. return this;
  6482. }
  6483. /**
  6484. * The components of this vector are rounded up to the nearest integer value.
  6485. *
  6486. * @return {Vector4} A reference to this vector.
  6487. */
  6488. ceil() {
  6489. this.x = Math.ceil( this.x );
  6490. this.y = Math.ceil( this.y );
  6491. this.z = Math.ceil( this.z );
  6492. this.w = Math.ceil( this.w );
  6493. return this;
  6494. }
  6495. /**
  6496. * The components of this vector are rounded to the nearest integer value
  6497. *
  6498. * @return {Vector4} A reference to this vector.
  6499. */
  6500. round() {
  6501. this.x = Math.round( this.x );
  6502. this.y = Math.round( this.y );
  6503. this.z = Math.round( this.z );
  6504. this.w = Math.round( this.w );
  6505. return this;
  6506. }
  6507. /**
  6508. * The components of this vector are rounded towards zero (up if negative,
  6509. * down if positive) to an integer value.
  6510. *
  6511. * @return {Vector4} A reference to this vector.
  6512. */
  6513. roundToZero() {
  6514. this.x = Math.trunc( this.x );
  6515. this.y = Math.trunc( this.y );
  6516. this.z = Math.trunc( this.z );
  6517. this.w = Math.trunc( this.w );
  6518. return this;
  6519. }
  6520. /**
  6521. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6522. *
  6523. * @return {Vector4} A reference to this vector.
  6524. */
  6525. negate() {
  6526. this.x = - this.x;
  6527. this.y = - this.y;
  6528. this.z = - this.z;
  6529. this.w = - this.w;
  6530. return this;
  6531. }
  6532. /**
  6533. * Calculates the dot product of the given vector with this instance.
  6534. *
  6535. * @param {Vector4} v - The vector to compute the dot product with.
  6536. * @return {number} The result of the dot product.
  6537. */
  6538. dot( v ) {
  6539. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6540. }
  6541. /**
  6542. * Computes the square of the Euclidean length (straight-line length) from
  6543. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6544. * compare the length squared instead as it is slightly more efficient to calculate.
  6545. *
  6546. * @return {number} The square length of this vector.
  6547. */
  6548. lengthSq() {
  6549. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6550. }
  6551. /**
  6552. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6553. *
  6554. * @return {number} The length of this vector.
  6555. */
  6556. length() {
  6557. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6558. }
  6559. /**
  6560. * Computes the Manhattan length of this vector.
  6561. *
  6562. * @return {number} The length of this vector.
  6563. */
  6564. manhattanLength() {
  6565. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6566. }
  6567. /**
  6568. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6569. * with the same direction as this one, but with a vector length of `1`.
  6570. *
  6571. * @return {Vector4} A reference to this vector.
  6572. */
  6573. normalize() {
  6574. return this.divideScalar( this.length() || 1 );
  6575. }
  6576. /**
  6577. * Sets this vector to a vector with the same direction as this one, but
  6578. * with the specified length.
  6579. *
  6580. * @param {number} length - The new length of this vector.
  6581. * @return {Vector4} A reference to this vector.
  6582. */
  6583. setLength( length ) {
  6584. return this.normalize().multiplyScalar( length );
  6585. }
  6586. /**
  6587. * Linearly interpolates between the given vector and this instance, where
  6588. * alpha is the percent distance along the line - alpha = 0 will be this
  6589. * vector, and alpha = 1 will be the given one.
  6590. *
  6591. * @param {Vector4} v - The vector to interpolate towards.
  6592. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6593. * @return {Vector4} A reference to this vector.
  6594. */
  6595. lerp( v, alpha ) {
  6596. this.x += ( v.x - this.x ) * alpha;
  6597. this.y += ( v.y - this.y ) * alpha;
  6598. this.z += ( v.z - this.z ) * alpha;
  6599. this.w += ( v.w - this.w ) * alpha;
  6600. return this;
  6601. }
  6602. /**
  6603. * Linearly interpolates between the given vectors, where alpha is the percent
  6604. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6605. * be the second one. The result is stored in this instance.
  6606. *
  6607. * @param {Vector4} v1 - The first vector.
  6608. * @param {Vector4} v2 - The second vector.
  6609. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6610. * @return {Vector4} A reference to this vector.
  6611. */
  6612. lerpVectors( v1, v2, alpha ) {
  6613. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6614. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6615. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6616. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6617. return this;
  6618. }
  6619. /**
  6620. * Returns `true` if this vector is equal with the given one.
  6621. *
  6622. * @param {Vector4} v - The vector to test for equality.
  6623. * @return {boolean} Whether this vector is equal with the given one.
  6624. */
  6625. equals( v ) {
  6626. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6627. }
  6628. /**
  6629. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6630. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6631. *
  6632. * @param {Array<number>} array - An array holding the vector component values.
  6633. * @param {number} [offset=0] - The offset into the array.
  6634. * @return {Vector4} A reference to this vector.
  6635. */
  6636. fromArray( array, offset = 0 ) {
  6637. this.x = array[ offset ];
  6638. this.y = array[ offset + 1 ];
  6639. this.z = array[ offset + 2 ];
  6640. this.w = array[ offset + 3 ];
  6641. return this;
  6642. }
  6643. /**
  6644. * Writes the components of this vector to the given array. If no array is provided,
  6645. * the method returns a new instance.
  6646. *
  6647. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6648. * @param {number} [offset=0] - Index of the first element in the array.
  6649. * @return {Array<number>} The vector components.
  6650. */
  6651. toArray( array = [], offset = 0 ) {
  6652. array[ offset ] = this.x;
  6653. array[ offset + 1 ] = this.y;
  6654. array[ offset + 2 ] = this.z;
  6655. array[ offset + 3 ] = this.w;
  6656. return array;
  6657. }
  6658. /**
  6659. * Sets the components of this vector from the given buffer attribute.
  6660. *
  6661. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6662. * @param {number} index - The index into the attribute.
  6663. * @return {Vector4} A reference to this vector.
  6664. */
  6665. fromBufferAttribute( attribute, index ) {
  6666. this.x = attribute.getX( index );
  6667. this.y = attribute.getY( index );
  6668. this.z = attribute.getZ( index );
  6669. this.w = attribute.getW( index );
  6670. return this;
  6671. }
  6672. /**
  6673. * Sets each component of this vector to a pseudo-random value between `0` and
  6674. * `1`, excluding `1`.
  6675. *
  6676. * @return {Vector4} A reference to this vector.
  6677. */
  6678. random() {
  6679. this.x = Math.random();
  6680. this.y = Math.random();
  6681. this.z = Math.random();
  6682. this.w = Math.random();
  6683. return this;
  6684. }
  6685. *[ Symbol.iterator ]() {
  6686. yield this.x;
  6687. yield this.y;
  6688. yield this.z;
  6689. yield this.w;
  6690. }
  6691. }
  6692. /**
  6693. * A render target is a buffer where the video card draws pixels for a scene
  6694. * that is being rendered in the background. It is used in different effects,
  6695. * such as applying postprocessing to a rendered image before displaying it
  6696. * on the screen.
  6697. *
  6698. * @augments EventDispatcher
  6699. */
  6700. class RenderTarget extends EventDispatcher {
  6701. /**
  6702. * Render target options.
  6703. *
  6704. * @typedef {Object} RenderTarget~Options
  6705. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6706. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6707. * @property {number} [minFilter=LinearFilter] - The min filter.
  6708. * @property {number} [format=RGBAFormat] - The texture format.
  6709. * @property {number} [type=UnsignedByteType] - The texture type.
  6710. * @property {?string} [internalFormat=null] - The texture's internal format.
  6711. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6712. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6713. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6714. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6715. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6716. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6717. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6718. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6719. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6720. * @property {number} [samples=0] - The MSAA samples count.
  6721. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6722. * @property {number} [depth=1] - The texture depth.
  6723. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6724. */
  6725. /**
  6726. * Constructs a new render target.
  6727. *
  6728. * @param {number} [width=1] - The width of the render target.
  6729. * @param {number} [height=1] - The height of the render target.
  6730. * @param {RenderTarget~Options} [options] - The configuration object.
  6731. */
  6732. constructor( width = 1, height = 1, options = {} ) {
  6733. super();
  6734. options = Object.assign( {
  6735. generateMipmaps: false,
  6736. internalFormat: null,
  6737. minFilter: LinearFilter,
  6738. depthBuffer: true,
  6739. stencilBuffer: false,
  6740. resolveDepthBuffer: true,
  6741. resolveStencilBuffer: true,
  6742. depthTexture: null,
  6743. samples: 0,
  6744. count: 1,
  6745. depth: 1,
  6746. multiview: false
  6747. }, options );
  6748. /**
  6749. * This flag can be used for type testing.
  6750. *
  6751. * @type {boolean}
  6752. * @readonly
  6753. * @default true
  6754. */
  6755. this.isRenderTarget = true;
  6756. /**
  6757. * The width of the render target.
  6758. *
  6759. * @type {number}
  6760. * @default 1
  6761. */
  6762. this.width = width;
  6763. /**
  6764. * The height of the render target.
  6765. *
  6766. * @type {number}
  6767. * @default 1
  6768. */
  6769. this.height = height;
  6770. /**
  6771. * The depth of the render target.
  6772. *
  6773. * @type {number}
  6774. * @default 1
  6775. */
  6776. this.depth = options.depth;
  6777. /**
  6778. * A rectangular area inside the render target's viewport. Fragments that are
  6779. * outside the area will be discarded.
  6780. *
  6781. * @type {Vector4}
  6782. * @default (0,0,width,height)
  6783. */
  6784. this.scissor = new Vector4( 0, 0, width, height );
  6785. /**
  6786. * Indicates whether the scissor test should be enabled when rendering into
  6787. * this render target or not.
  6788. *
  6789. * @type {boolean}
  6790. * @default false
  6791. */
  6792. this.scissorTest = false;
  6793. /**
  6794. * A rectangular area representing the render target's viewport.
  6795. *
  6796. * @type {Vector4}
  6797. * @default (0,0,width,height)
  6798. */
  6799. this.viewport = new Vector4( 0, 0, width, height );
  6800. const image = { width: width, height: height, depth: options.depth };
  6801. const texture = new Texture( image );
  6802. /**
  6803. * An array of textures. Each color attachment is represented as a separate texture.
  6804. * Has at least a single entry for the default color attachment.
  6805. *
  6806. * @type {Array<Texture>}
  6807. */
  6808. this.textures = [];
  6809. const count = options.count;
  6810. for ( let i = 0; i < count; i ++ ) {
  6811. this.textures[ i ] = texture.clone();
  6812. this.textures[ i ].isRenderTargetTexture = true;
  6813. this.textures[ i ].renderTarget = this;
  6814. }
  6815. this._setTextureOptions( options );
  6816. /**
  6817. * Whether to allocate a depth buffer or not.
  6818. *
  6819. * @type {boolean}
  6820. * @default true
  6821. */
  6822. this.depthBuffer = options.depthBuffer;
  6823. /**
  6824. * Whether to allocate a stencil buffer or not.
  6825. *
  6826. * @type {boolean}
  6827. * @default false
  6828. */
  6829. this.stencilBuffer = options.stencilBuffer;
  6830. /**
  6831. * Whether to resolve the depth buffer or not.
  6832. *
  6833. * @type {boolean}
  6834. * @default true
  6835. */
  6836. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6837. /**
  6838. * Whether to resolve the stencil buffer or not.
  6839. *
  6840. * @type {boolean}
  6841. * @default true
  6842. */
  6843. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6844. this._depthTexture = null;
  6845. this.depthTexture = options.depthTexture;
  6846. /**
  6847. * The number of MSAA samples.
  6848. *
  6849. * A value of `0` disables MSAA.
  6850. *
  6851. * @type {number}
  6852. * @default 0
  6853. */
  6854. this.samples = options.samples;
  6855. /**
  6856. * Whether to this target is used in multiview rendering.
  6857. *
  6858. * @type {boolean}
  6859. * @default false
  6860. */
  6861. this.multiview = options.multiview;
  6862. }
  6863. _setTextureOptions( options = {} ) {
  6864. const values = {
  6865. minFilter: LinearFilter,
  6866. generateMipmaps: false,
  6867. flipY: false,
  6868. internalFormat: null
  6869. };
  6870. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6871. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6872. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6873. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6874. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6875. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6876. if ( options.format !== undefined ) values.format = options.format;
  6877. if ( options.type !== undefined ) values.type = options.type;
  6878. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6879. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6880. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6881. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6882. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6883. for ( let i = 0; i < this.textures.length; i ++ ) {
  6884. const texture = this.textures[ i ];
  6885. texture.setValues( values );
  6886. }
  6887. }
  6888. /**
  6889. * The texture representing the default color attachment.
  6890. *
  6891. * @type {Texture}
  6892. */
  6893. get texture() {
  6894. return this.textures[ 0 ];
  6895. }
  6896. set texture( value ) {
  6897. this.textures[ 0 ] = value;
  6898. }
  6899. set depthTexture( current ) {
  6900. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6901. if ( current !== null ) current.renderTarget = this;
  6902. this._depthTexture = current;
  6903. }
  6904. /**
  6905. * Instead of saving the depth in a renderbuffer, a texture
  6906. * can be used instead which is useful for further processing
  6907. * e.g. in context of post-processing.
  6908. *
  6909. * @type {?DepthTexture}
  6910. * @default null
  6911. */
  6912. get depthTexture() {
  6913. return this._depthTexture;
  6914. }
  6915. /**
  6916. * Sets the size of this render target.
  6917. *
  6918. * @param {number} width - The width.
  6919. * @param {number} height - The height.
  6920. * @param {number} [depth=1] - The depth.
  6921. */
  6922. setSize( width, height, depth = 1 ) {
  6923. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6924. this.width = width;
  6925. this.height = height;
  6926. this.depth = depth;
  6927. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6928. this.textures[ i ].image.width = width;
  6929. this.textures[ i ].image.height = height;
  6930. this.textures[ i ].image.depth = depth;
  6931. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6932. }
  6933. this.dispose();
  6934. }
  6935. this.viewport.set( 0, 0, width, height );
  6936. this.scissor.set( 0, 0, width, height );
  6937. }
  6938. /**
  6939. * Returns a new render target with copied values from this instance.
  6940. *
  6941. * @return {RenderTarget} A clone of this instance.
  6942. */
  6943. clone() {
  6944. return new this.constructor().copy( this );
  6945. }
  6946. /**
  6947. * Copies the settings of the given render target. This is a structural copy so
  6948. * no resources are shared between render targets after the copy. That includes
  6949. * all MRT textures and the depth texture.
  6950. *
  6951. * @param {RenderTarget} source - The render target to copy.
  6952. * @return {RenderTarget} A reference to this instance.
  6953. */
  6954. copy( source ) {
  6955. this.width = source.width;
  6956. this.height = source.height;
  6957. this.depth = source.depth;
  6958. this.scissor.copy( source.scissor );
  6959. this.scissorTest = source.scissorTest;
  6960. this.viewport.copy( source.viewport );
  6961. this.textures.length = 0;
  6962. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  6963. this.textures[ i ] = source.textures[ i ].clone();
  6964. this.textures[ i ].isRenderTargetTexture = true;
  6965. this.textures[ i ].renderTarget = this;
  6966. // ensure image object is not shared, see #20328
  6967. const image = Object.assign( {}, source.textures[ i ].image );
  6968. this.textures[ i ].source = new Source( image );
  6969. }
  6970. this.depthBuffer = source.depthBuffer;
  6971. this.stencilBuffer = source.stencilBuffer;
  6972. this.resolveDepthBuffer = source.resolveDepthBuffer;
  6973. this.resolveStencilBuffer = source.resolveStencilBuffer;
  6974. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  6975. this.samples = source.samples;
  6976. return this;
  6977. }
  6978. /**
  6979. * Frees the GPU-related resources allocated by this instance. Call this
  6980. * method whenever this instance is no longer used in your app.
  6981. *
  6982. * @fires RenderTarget#dispose
  6983. */
  6984. dispose() {
  6985. this.dispatchEvent( { type: 'dispose' } );
  6986. }
  6987. }
  6988. /**
  6989. * A render target used in context of {@link WebGLRenderer}.
  6990. *
  6991. * @augments RenderTarget
  6992. */
  6993. class WebGLRenderTarget extends RenderTarget {
  6994. /**
  6995. * Constructs a new 3D render target.
  6996. *
  6997. * @param {number} [width=1] - The width of the render target.
  6998. * @param {number} [height=1] - The height of the render target.
  6999. * @param {RenderTarget~Options} [options] - The configuration object.
  7000. */
  7001. constructor( width = 1, height = 1, options = {} ) {
  7002. super( width, height, options );
  7003. /**
  7004. * This flag can be used for type testing.
  7005. *
  7006. * @type {boolean}
  7007. * @readonly
  7008. * @default true
  7009. */
  7010. this.isWebGLRenderTarget = true;
  7011. }
  7012. }
  7013. /**
  7014. * Creates an array of textures directly from raw buffer data.
  7015. *
  7016. * @augments Texture
  7017. */
  7018. class DataArrayTexture extends Texture {
  7019. /**
  7020. * Constructs a new data array texture.
  7021. *
  7022. * @param {?TypedArray} [data=null] - The buffer data.
  7023. * @param {number} [width=1] - The width of the texture.
  7024. * @param {number} [height=1] - The height of the texture.
  7025. * @param {number} [depth=1] - The depth of the texture.
  7026. */
  7027. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7028. super( null );
  7029. /**
  7030. * This flag can be used for type testing.
  7031. *
  7032. * @type {boolean}
  7033. * @readonly
  7034. * @default true
  7035. */
  7036. this.isDataArrayTexture = true;
  7037. /**
  7038. * The image definition of a data texture.
  7039. *
  7040. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7041. */
  7042. this.image = { data, width, height, depth };
  7043. /**
  7044. * How the texture is sampled when a texel covers more than one pixel.
  7045. *
  7046. * Overwritten and set to `NearestFilter` by default.
  7047. *
  7048. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7049. * @default NearestFilter
  7050. */
  7051. this.magFilter = NearestFilter;
  7052. /**
  7053. * How the texture is sampled when a texel covers less than one pixel.
  7054. *
  7055. * Overwritten and set to `NearestFilter` by default.
  7056. *
  7057. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7058. * @default NearestFilter
  7059. */
  7060. this.minFilter = NearestFilter;
  7061. /**
  7062. * This defines how the texture is wrapped in the depth and corresponds to
  7063. * *W* in UVW mapping.
  7064. *
  7065. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7066. * @default ClampToEdgeWrapping
  7067. */
  7068. this.wrapR = ClampToEdgeWrapping;
  7069. /**
  7070. * Whether to generate mipmaps (if possible) for a texture.
  7071. *
  7072. * Overwritten and set to `false` by default.
  7073. *
  7074. * @type {boolean}
  7075. * @default false
  7076. */
  7077. this.generateMipmaps = false;
  7078. /**
  7079. * If set to `true`, the texture is flipped along the vertical axis when
  7080. * uploaded to the GPU.
  7081. *
  7082. * Overwritten and set to `false` by default.
  7083. *
  7084. * @type {boolean}
  7085. * @default false
  7086. */
  7087. this.flipY = false;
  7088. /**
  7089. * Specifies the alignment requirements for the start of each pixel row in memory.
  7090. *
  7091. * Overwritten and set to `1` by default.
  7092. *
  7093. * @type {boolean}
  7094. * @default 1
  7095. */
  7096. this.unpackAlignment = 1;
  7097. /**
  7098. * A set of all layers which need to be updated in the texture.
  7099. *
  7100. * @type {Set<number>}
  7101. */
  7102. this.layerUpdates = new Set();
  7103. }
  7104. /**
  7105. * Describes that a specific layer of the texture needs to be updated.
  7106. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7107. * entire data texture array is sent to the GPU. Marking specific
  7108. * layers will only transmit subsets of all mipmaps associated with a
  7109. * specific depth in the array which is often much more performant.
  7110. *
  7111. * @param {number} layerIndex - The layer index that should be updated.
  7112. */
  7113. addLayerUpdate( layerIndex ) {
  7114. this.layerUpdates.add( layerIndex );
  7115. }
  7116. /**
  7117. * Resets the layer updates registry.
  7118. */
  7119. clearLayerUpdates() {
  7120. this.layerUpdates.clear();
  7121. }
  7122. }
  7123. /**
  7124. * An array render target used in context of {@link WebGLRenderer}.
  7125. *
  7126. * @augments WebGLRenderTarget
  7127. */
  7128. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7129. /**
  7130. * Constructs a new array render target.
  7131. *
  7132. * @param {number} [width=1] - The width of the render target.
  7133. * @param {number} [height=1] - The height of the render target.
  7134. * @param {number} [depth=1] - The height of the render target.
  7135. * @param {RenderTarget~Options} [options] - The configuration object.
  7136. */
  7137. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7138. super( width, height, options );
  7139. /**
  7140. * This flag can be used for type testing.
  7141. *
  7142. * @type {boolean}
  7143. * @readonly
  7144. * @default true
  7145. */
  7146. this.isWebGLArrayRenderTarget = true;
  7147. this.depth = depth;
  7148. /**
  7149. * Overwritten with a different texture type.
  7150. *
  7151. * @type {DataArrayTexture}
  7152. */
  7153. this.texture = new DataArrayTexture( null, width, height, depth );
  7154. this._setTextureOptions( options );
  7155. this.texture.isRenderTargetTexture = true;
  7156. }
  7157. }
  7158. /**
  7159. * Creates a three-dimensional texture from raw data, with parameters to
  7160. * divide it into width, height, and depth.
  7161. *
  7162. * @augments Texture
  7163. */
  7164. class Data3DTexture extends Texture {
  7165. /**
  7166. * Constructs a new data array texture.
  7167. *
  7168. * @param {?TypedArray} [data=null] - The buffer data.
  7169. * @param {number} [width=1] - The width of the texture.
  7170. * @param {number} [height=1] - The height of the texture.
  7171. * @param {number} [depth=1] - The depth of the texture.
  7172. */
  7173. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7174. // We're going to add .setXXX() methods for setting properties later.
  7175. // Users can still set in Data3DTexture directly.
  7176. //
  7177. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7178. // texture.anisotropy = 16;
  7179. //
  7180. // See #14839
  7181. super( null );
  7182. /**
  7183. * This flag can be used for type testing.
  7184. *
  7185. * @type {boolean}
  7186. * @readonly
  7187. * @default true
  7188. */
  7189. this.isData3DTexture = true;
  7190. /**
  7191. * The image definition of a data texture.
  7192. *
  7193. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7194. */
  7195. this.image = { data, width, height, depth };
  7196. /**
  7197. * How the texture is sampled when a texel covers more than one pixel.
  7198. *
  7199. * Overwritten and set to `NearestFilter` by default.
  7200. *
  7201. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7202. * @default NearestFilter
  7203. */
  7204. this.magFilter = NearestFilter;
  7205. /**
  7206. * How the texture is sampled when a texel covers less than one pixel.
  7207. *
  7208. * Overwritten and set to `NearestFilter` by default.
  7209. *
  7210. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7211. * @default NearestFilter
  7212. */
  7213. this.minFilter = NearestFilter;
  7214. /**
  7215. * This defines how the texture is wrapped in the depth and corresponds to
  7216. * *W* in UVW mapping.
  7217. *
  7218. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7219. * @default ClampToEdgeWrapping
  7220. */
  7221. this.wrapR = ClampToEdgeWrapping;
  7222. /**
  7223. * Whether to generate mipmaps (if possible) for a texture.
  7224. *
  7225. * Overwritten and set to `false` by default.
  7226. *
  7227. * @type {boolean}
  7228. * @default false
  7229. */
  7230. this.generateMipmaps = false;
  7231. /**
  7232. * If set to `true`, the texture is flipped along the vertical axis when
  7233. * uploaded to the GPU.
  7234. *
  7235. * Overwritten and set to `false` by default.
  7236. *
  7237. * @type {boolean}
  7238. * @default false
  7239. */
  7240. this.flipY = false;
  7241. /**
  7242. * Specifies the alignment requirements for the start of each pixel row in memory.
  7243. *
  7244. * Overwritten and set to `1` by default.
  7245. *
  7246. * @type {boolean}
  7247. * @default 1
  7248. */
  7249. this.unpackAlignment = 1;
  7250. }
  7251. }
  7252. /**
  7253. * A 3D render target used in context of {@link WebGLRenderer}.
  7254. *
  7255. * @augments WebGLRenderTarget
  7256. */
  7257. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7258. /**
  7259. * Constructs a new 3D render target.
  7260. *
  7261. * @param {number} [width=1] - The width of the render target.
  7262. * @param {number} [height=1] - The height of the render target.
  7263. * @param {number} [depth=1] - The height of the render target.
  7264. * @param {RenderTarget~Options} [options] - The configuration object.
  7265. */
  7266. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7267. super( width, height, options );
  7268. /**
  7269. * This flag can be used for type testing.
  7270. *
  7271. * @type {boolean}
  7272. * @readonly
  7273. * @default true
  7274. */
  7275. this.isWebGL3DRenderTarget = true;
  7276. this.depth = depth;
  7277. /**
  7278. * Overwritten with a different texture type.
  7279. *
  7280. * @type {Data3DTexture}
  7281. */
  7282. this.texture = new Data3DTexture( null, width, height, depth );
  7283. this._setTextureOptions( options );
  7284. this.texture.isRenderTargetTexture = true;
  7285. }
  7286. }
  7287. /**
  7288. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7289. */
  7290. class Box3 {
  7291. /**
  7292. * Constructs a new bounding box.
  7293. *
  7294. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7295. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7296. */
  7297. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7298. /**
  7299. * This flag can be used for type testing.
  7300. *
  7301. * @type {boolean}
  7302. * @readonly
  7303. * @default true
  7304. */
  7305. this.isBox3 = true;
  7306. /**
  7307. * The lower boundary of the box.
  7308. *
  7309. * @type {Vector3}
  7310. */
  7311. this.min = min;
  7312. /**
  7313. * The upper boundary of the box.
  7314. *
  7315. * @type {Vector3}
  7316. */
  7317. this.max = max;
  7318. }
  7319. /**
  7320. * Sets the lower and upper boundaries of this box.
  7321. * Please note that this method only copies the values from the given objects.
  7322. *
  7323. * @param {Vector3} min - The lower boundary of the box.
  7324. * @param {Vector3} max - The upper boundary of the box.
  7325. * @return {Box3} A reference to this bounding box.
  7326. */
  7327. set( min, max ) {
  7328. this.min.copy( min );
  7329. this.max.copy( max );
  7330. return this;
  7331. }
  7332. /**
  7333. * Sets the upper and lower bounds of this box so it encloses the position data
  7334. * in the given array.
  7335. *
  7336. * @param {Array<number>} array - An array holding 3D position data.
  7337. * @return {Box3} A reference to this bounding box.
  7338. */
  7339. setFromArray( array ) {
  7340. this.makeEmpty();
  7341. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7342. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7343. }
  7344. return this;
  7345. }
  7346. /**
  7347. * Sets the upper and lower bounds of this box so it encloses the position data
  7348. * in the given buffer attribute.
  7349. *
  7350. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7351. * @return {Box3} A reference to this bounding box.
  7352. */
  7353. setFromBufferAttribute( attribute ) {
  7354. this.makeEmpty();
  7355. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7356. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7357. }
  7358. return this;
  7359. }
  7360. /**
  7361. * Sets the upper and lower bounds of this box so it encloses the position data
  7362. * in the given array.
  7363. *
  7364. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7365. * @return {Box3} A reference to this bounding box.
  7366. */
  7367. setFromPoints( points ) {
  7368. this.makeEmpty();
  7369. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7370. this.expandByPoint( points[ i ] );
  7371. }
  7372. return this;
  7373. }
  7374. /**
  7375. * Centers this box on the given center vector and sets this box's width, height and
  7376. * depth to the given size values.
  7377. *
  7378. * @param {Vector3} center - The center of the box.
  7379. * @param {Vector3} size - The x, y and z dimensions of the box.
  7380. * @return {Box3} A reference to this bounding box.
  7381. */
  7382. setFromCenterAndSize( center, size ) {
  7383. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7384. this.min.copy( center ).sub( halfSize );
  7385. this.max.copy( center ).add( halfSize );
  7386. return this;
  7387. }
  7388. /**
  7389. * Computes the world-axis-aligned bounding box for the given 3D object
  7390. * (including its children), accounting for the object's, and children's,
  7391. * world transforms. The function may result in a larger box than strictly necessary.
  7392. *
  7393. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7394. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7395. * world-axis-aligned bounding box at the expense of more computation.
  7396. * @return {Box3} A reference to this bounding box.
  7397. */
  7398. setFromObject( object, precise = false ) {
  7399. this.makeEmpty();
  7400. return this.expandByObject( object, precise );
  7401. }
  7402. /**
  7403. * Returns a new box with copied values from this instance.
  7404. *
  7405. * @return {Box3} A clone of this instance.
  7406. */
  7407. clone() {
  7408. return new this.constructor().copy( this );
  7409. }
  7410. /**
  7411. * Copies the values of the given box to this instance.
  7412. *
  7413. * @param {Box3} box - The box to copy.
  7414. * @return {Box3} A reference to this bounding box.
  7415. */
  7416. copy( box ) {
  7417. this.min.copy( box.min );
  7418. this.max.copy( box.max );
  7419. return this;
  7420. }
  7421. /**
  7422. * Makes this box empty which means in encloses a zero space in 3D.
  7423. *
  7424. * @return {Box3} A reference to this bounding box.
  7425. */
  7426. makeEmpty() {
  7427. this.min.x = this.min.y = this.min.z = + Infinity;
  7428. this.max.x = this.max.y = this.max.z = - Infinity;
  7429. return this;
  7430. }
  7431. /**
  7432. * Returns true if this box includes zero points within its bounds.
  7433. * Note that a box with equal lower and upper bounds still includes one
  7434. * point, the one both bounds share.
  7435. *
  7436. * @return {boolean} Whether this box is empty or not.
  7437. */
  7438. isEmpty() {
  7439. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7440. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7441. }
  7442. /**
  7443. * Returns the center point of this box.
  7444. *
  7445. * @param {Vector3} target - The target vector that is used to store the method's result.
  7446. * @return {Vector3} The center point.
  7447. */
  7448. getCenter( target ) {
  7449. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7450. }
  7451. /**
  7452. * Returns the dimensions of this box.
  7453. *
  7454. * @param {Vector3} target - The target vector that is used to store the method's result.
  7455. * @return {Vector3} The size.
  7456. */
  7457. getSize( target ) {
  7458. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7459. }
  7460. /**
  7461. * Expands the boundaries of this box to include the given point.
  7462. *
  7463. * @param {Vector3} point - The point that should be included by the bounding box.
  7464. * @return {Box3} A reference to this bounding box.
  7465. */
  7466. expandByPoint( point ) {
  7467. this.min.min( point );
  7468. this.max.max( point );
  7469. return this;
  7470. }
  7471. /**
  7472. * Expands this box equilaterally by the given vector. The width of this
  7473. * box will be expanded by the x component of the vector in both
  7474. * directions. The height of this box will be expanded by the y component of
  7475. * the vector in both directions. The depth of this box will be
  7476. * expanded by the z component of the vector in both directions.
  7477. *
  7478. * @param {Vector3} vector - The vector that should expand the bounding box.
  7479. * @return {Box3} A reference to this bounding box.
  7480. */
  7481. expandByVector( vector ) {
  7482. this.min.sub( vector );
  7483. this.max.add( vector );
  7484. return this;
  7485. }
  7486. /**
  7487. * Expands each dimension of the box by the given scalar. If negative, the
  7488. * dimensions of the box will be contracted.
  7489. *
  7490. * @param {number} scalar - The scalar value that should expand the bounding box.
  7491. * @return {Box3} A reference to this bounding box.
  7492. */
  7493. expandByScalar( scalar ) {
  7494. this.min.addScalar( - scalar );
  7495. this.max.addScalar( scalar );
  7496. return this;
  7497. }
  7498. /**
  7499. * Expands the boundaries of this box to include the given 3D object and
  7500. * its children, accounting for the object's, and children's, world
  7501. * transforms. The function may result in a larger box than strictly
  7502. * necessary (unless the precise parameter is set to true).
  7503. *
  7504. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7505. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7506. * as little as necessary at the expense of more computation.
  7507. * @return {Box3} A reference to this bounding box.
  7508. */
  7509. expandByObject( object, precise = false ) {
  7510. // Computes the world-axis-aligned bounding box of an object (including its children),
  7511. // accounting for both the object's, and children's, world transforms
  7512. object.updateWorldMatrix( false, false );
  7513. const geometry = object.geometry;
  7514. if ( geometry !== undefined ) {
  7515. const positionAttribute = geometry.getAttribute( 'position' );
  7516. // precise AABB computation based on vertex data requires at least a position attribute.
  7517. // instancing isn't supported so far and uses the normal (conservative) code path.
  7518. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7519. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7520. if ( object.isMesh === true ) {
  7521. object.getVertexPosition( i, _vector$b );
  7522. } else {
  7523. _vector$b.fromBufferAttribute( positionAttribute, i );
  7524. }
  7525. _vector$b.applyMatrix4( object.matrixWorld );
  7526. this.expandByPoint( _vector$b );
  7527. }
  7528. } else {
  7529. if ( object.boundingBox !== undefined ) {
  7530. // object-level bounding box
  7531. if ( object.boundingBox === null ) {
  7532. object.computeBoundingBox();
  7533. }
  7534. _box$4.copy( object.boundingBox );
  7535. } else {
  7536. // geometry-level bounding box
  7537. if ( geometry.boundingBox === null ) {
  7538. geometry.computeBoundingBox();
  7539. }
  7540. _box$4.copy( geometry.boundingBox );
  7541. }
  7542. _box$4.applyMatrix4( object.matrixWorld );
  7543. this.union( _box$4 );
  7544. }
  7545. }
  7546. const children = object.children;
  7547. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7548. this.expandByObject( children[ i ], precise );
  7549. }
  7550. return this;
  7551. }
  7552. /**
  7553. * Returns `true` if the given point lies within or on the boundaries of this box.
  7554. *
  7555. * @param {Vector3} point - The point to test.
  7556. * @return {boolean} Whether the bounding box contains the given point or not.
  7557. */
  7558. containsPoint( point ) {
  7559. return point.x >= this.min.x && point.x <= this.max.x &&
  7560. point.y >= this.min.y && point.y <= this.max.y &&
  7561. point.z >= this.min.z && point.z <= this.max.z;
  7562. }
  7563. /**
  7564. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7565. * If this box and the given one are identical, this function also returns `true`.
  7566. *
  7567. * @param {Box3} box - The bounding box to test.
  7568. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7569. */
  7570. containsBox( box ) {
  7571. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7572. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7573. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7574. }
  7575. /**
  7576. * Returns a point as a proportion of this box's width, height and depth.
  7577. *
  7578. * @param {Vector3} point - A point in 3D space.
  7579. * @param {Vector3} target - The target vector that is used to store the method's result.
  7580. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7581. */
  7582. getParameter( point, target ) {
  7583. // This can potentially have a divide by zero if the box
  7584. // has a size dimension of 0.
  7585. return target.set(
  7586. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7587. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7588. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7589. );
  7590. }
  7591. /**
  7592. * Returns `true` if the given bounding box intersects with this bounding box.
  7593. *
  7594. * @param {Box3} box - The bounding box to test.
  7595. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7596. */
  7597. intersectsBox( box ) {
  7598. // using 6 splitting planes to rule out intersections.
  7599. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7600. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7601. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7602. }
  7603. /**
  7604. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7605. *
  7606. * @param {Sphere} sphere - The bounding sphere to test.
  7607. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7608. */
  7609. intersectsSphere( sphere ) {
  7610. // Find the point on the AABB closest to the sphere center.
  7611. this.clampPoint( sphere.center, _vector$b );
  7612. // If that point is inside the sphere, the AABB and sphere intersect.
  7613. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7614. }
  7615. /**
  7616. * Returns `true` if the given plane intersects with this bounding box.
  7617. *
  7618. * @param {Plane} plane - The plane to test.
  7619. * @return {boolean} Whether the given plane intersects with this bounding box.
  7620. */
  7621. intersectsPlane( plane ) {
  7622. // We compute the minimum and maximum dot product values. If those values
  7623. // are on the same side (back or front) of the plane, then there is no intersection.
  7624. let min, max;
  7625. if ( plane.normal.x > 0 ) {
  7626. min = plane.normal.x * this.min.x;
  7627. max = plane.normal.x * this.max.x;
  7628. } else {
  7629. min = plane.normal.x * this.max.x;
  7630. max = plane.normal.x * this.min.x;
  7631. }
  7632. if ( plane.normal.y > 0 ) {
  7633. min += plane.normal.y * this.min.y;
  7634. max += plane.normal.y * this.max.y;
  7635. } else {
  7636. min += plane.normal.y * this.max.y;
  7637. max += plane.normal.y * this.min.y;
  7638. }
  7639. if ( plane.normal.z > 0 ) {
  7640. min += plane.normal.z * this.min.z;
  7641. max += plane.normal.z * this.max.z;
  7642. } else {
  7643. min += plane.normal.z * this.max.z;
  7644. max += plane.normal.z * this.min.z;
  7645. }
  7646. return ( min <= - plane.constant && max >= - plane.constant );
  7647. }
  7648. /**
  7649. * Returns `true` if the given triangle intersects with this bounding box.
  7650. *
  7651. * @param {Triangle} triangle - The triangle to test.
  7652. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7653. */
  7654. intersectsTriangle( triangle ) {
  7655. if ( this.isEmpty() ) {
  7656. return false;
  7657. }
  7658. // compute box center and extents
  7659. this.getCenter( _center );
  7660. _extents.subVectors( this.max, _center );
  7661. // translate triangle to aabb origin
  7662. _v0$2.subVectors( triangle.a, _center );
  7663. _v1$7.subVectors( triangle.b, _center );
  7664. _v2$4.subVectors( triangle.c, _center );
  7665. // compute edge vectors for triangle
  7666. _f0.subVectors( _v1$7, _v0$2 );
  7667. _f1.subVectors( _v2$4, _v1$7 );
  7668. _f2.subVectors( _v0$2, _v2$4 );
  7669. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7670. // 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
  7671. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7672. let axes = [
  7673. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7674. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7675. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7676. ];
  7677. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7678. return false;
  7679. }
  7680. // test 3 face normals from the aabb
  7681. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7682. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  7683. return false;
  7684. }
  7685. // finally testing the face normal of the triangle
  7686. // use already existing triangle edge vectors here
  7687. _triangleNormal.crossVectors( _f0, _f1 );
  7688. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7689. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  7690. }
  7691. /**
  7692. * Clamps the given point within the bounds of this box.
  7693. *
  7694. * @param {Vector3} point - The point to clamp.
  7695. * @param {Vector3} target - The target vector that is used to store the method's result.
  7696. * @return {Vector3} The clamped point.
  7697. */
  7698. clampPoint( point, target ) {
  7699. return target.copy( point ).clamp( this.min, this.max );
  7700. }
  7701. /**
  7702. * Returns the euclidean distance from any edge of this box to the specified point. If
  7703. * the given point lies inside of this box, the distance will be `0`.
  7704. *
  7705. * @param {Vector3} point - The point to compute the distance to.
  7706. * @return {number} The euclidean distance.
  7707. */
  7708. distanceToPoint( point ) {
  7709. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7710. }
  7711. /**
  7712. * Returns a bounding sphere that encloses this bounding box.
  7713. *
  7714. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7715. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7716. */
  7717. getBoundingSphere( target ) {
  7718. if ( this.isEmpty() ) {
  7719. target.makeEmpty();
  7720. } else {
  7721. this.getCenter( target.center );
  7722. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7723. }
  7724. return target;
  7725. }
  7726. /**
  7727. * Computes the intersection of this bounding box and the given one, setting the upper
  7728. * bound of this box to the lesser of the two boxes' upper bounds and the
  7729. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7730. * there's no overlap, makes this box empty.
  7731. *
  7732. * @param {Box3} box - The bounding box to intersect with.
  7733. * @return {Box3} A reference to this bounding box.
  7734. */
  7735. intersect( box ) {
  7736. this.min.max( box.min );
  7737. this.max.min( box.max );
  7738. // 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.
  7739. if ( this.isEmpty() ) this.makeEmpty();
  7740. return this;
  7741. }
  7742. /**
  7743. * Computes the union of this box and another and the given one, setting the upper
  7744. * bound of this box to the greater of the two boxes' upper bounds and the
  7745. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7746. *
  7747. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7748. * @return {Box3} A reference to this bounding box.
  7749. */
  7750. union( box ) {
  7751. this.min.min( box.min );
  7752. this.max.max( box.max );
  7753. return this;
  7754. }
  7755. /**
  7756. * Transforms this bounding box by the given 4x4 transformation matrix.
  7757. *
  7758. * @param {Matrix4} matrix - The transformation matrix.
  7759. * @return {Box3} A reference to this bounding box.
  7760. */
  7761. applyMatrix4( matrix ) {
  7762. // transform of empty box is an empty box.
  7763. if ( this.isEmpty() ) return this;
  7764. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7765. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7766. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7767. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7768. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7769. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7770. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7771. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7772. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7773. this.setFromPoints( _points );
  7774. return this;
  7775. }
  7776. /**
  7777. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7778. * effectively moving it in 3D space.
  7779. *
  7780. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7781. * @return {Box3} A reference to this bounding box.
  7782. */
  7783. translate( offset ) {
  7784. this.min.add( offset );
  7785. this.max.add( offset );
  7786. return this;
  7787. }
  7788. /**
  7789. * Returns `true` if this bounding box is equal with the given one.
  7790. *
  7791. * @param {Box3} box - The box to test for equality.
  7792. * @return {boolean} Whether this bounding box is equal with the given one.
  7793. */
  7794. equals( box ) {
  7795. return box.min.equals( this.min ) && box.max.equals( this.max );
  7796. }
  7797. /**
  7798. * Returns a serialized structure of the bounding box.
  7799. *
  7800. * @return {Object} Serialized structure with fields representing the object state.
  7801. */
  7802. toJSON() {
  7803. return {
  7804. min: this.min.toArray(),
  7805. max: this.max.toArray()
  7806. };
  7807. }
  7808. /**
  7809. * Returns a serialized structure of the bounding box.
  7810. *
  7811. * @param {Object} json - The serialized json to set the box from.
  7812. * @return {Box3} A reference to this bounding box.
  7813. */
  7814. fromJSON( json ) {
  7815. this.min.fromArray( json.min );
  7816. this.max.fromArray( json.max );
  7817. return this;
  7818. }
  7819. }
  7820. const _points = [
  7821. /*@__PURE__*/ new Vector3(),
  7822. /*@__PURE__*/ new Vector3(),
  7823. /*@__PURE__*/ new Vector3(),
  7824. /*@__PURE__*/ new Vector3(),
  7825. /*@__PURE__*/ new Vector3(),
  7826. /*@__PURE__*/ new Vector3(),
  7827. /*@__PURE__*/ new Vector3(),
  7828. /*@__PURE__*/ new Vector3()
  7829. ];
  7830. const _vector$b = /*@__PURE__*/ new Vector3();
  7831. const _box$4 = /*@__PURE__*/ new Box3();
  7832. // triangle centered vertices
  7833. const _v0$2 = /*@__PURE__*/ new Vector3();
  7834. const _v1$7 = /*@__PURE__*/ new Vector3();
  7835. const _v2$4 = /*@__PURE__*/ new Vector3();
  7836. // triangle edge vectors
  7837. const _f0 = /*@__PURE__*/ new Vector3();
  7838. const _f1 = /*@__PURE__*/ new Vector3();
  7839. const _f2 = /*@__PURE__*/ new Vector3();
  7840. const _center = /*@__PURE__*/ new Vector3();
  7841. const _extents = /*@__PURE__*/ new Vector3();
  7842. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7843. const _testAxis = /*@__PURE__*/ new Vector3();
  7844. function satForAxes( axes, v0, v1, v2, extents ) {
  7845. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7846. _testAxis.fromArray( axes, i );
  7847. // project the aabb onto the separating axis
  7848. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7849. // project all 3 vertices of the triangle onto the separating axis
  7850. const p0 = v0.dot( _testAxis );
  7851. const p1 = v1.dot( _testAxis );
  7852. const p2 = v2.dot( _testAxis );
  7853. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7854. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7855. // points of the projected triangle are outside the projected half-length of the aabb
  7856. // the axis is separating and we can exit
  7857. return false;
  7858. }
  7859. }
  7860. return true;
  7861. }
  7862. const _box$3 = /*@__PURE__*/ new Box3();
  7863. const _v1$6 = /*@__PURE__*/ new Vector3();
  7864. const _v2$3 = /*@__PURE__*/ new Vector3();
  7865. /**
  7866. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7867. * used as a Bounding Sphere for 3D objects.
  7868. */
  7869. class Sphere {
  7870. /**
  7871. * Constructs a new sphere.
  7872. *
  7873. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7874. * @param {number} [radius=-1] - The radius of the sphere.
  7875. */
  7876. constructor( center = new Vector3(), radius = -1 ) {
  7877. /**
  7878. * This flag can be used for type testing.
  7879. *
  7880. * @type {boolean}
  7881. * @readonly
  7882. * @default true
  7883. */
  7884. this.isSphere = true;
  7885. /**
  7886. * The center of the sphere
  7887. *
  7888. * @type {Vector3}
  7889. */
  7890. this.center = center;
  7891. /**
  7892. * The radius of the sphere.
  7893. *
  7894. * @type {number}
  7895. */
  7896. this.radius = radius;
  7897. }
  7898. /**
  7899. * Sets the sphere's components by copying the given values.
  7900. *
  7901. * @param {Vector3} center - The center.
  7902. * @param {number} radius - The radius.
  7903. * @return {Sphere} A reference to this sphere.
  7904. */
  7905. set( center, radius ) {
  7906. this.center.copy( center );
  7907. this.radius = radius;
  7908. return this;
  7909. }
  7910. /**
  7911. * Computes the minimum bounding sphere for list of points.
  7912. * If the optional center point is given, it is used as the sphere's
  7913. * center. Otherwise, the center of the axis-aligned bounding box
  7914. * encompassing the points is calculated.
  7915. *
  7916. * @param {Array<Vector3>} points - A list of points in 3D space.
  7917. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7918. * @return {Sphere} A reference to this sphere.
  7919. */
  7920. setFromPoints( points, optionalCenter ) {
  7921. const center = this.center;
  7922. if ( optionalCenter !== undefined ) {
  7923. center.copy( optionalCenter );
  7924. } else {
  7925. _box$3.setFromPoints( points ).getCenter( center );
  7926. }
  7927. let maxRadiusSq = 0;
  7928. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7929. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7930. }
  7931. this.radius = Math.sqrt( maxRadiusSq );
  7932. return this;
  7933. }
  7934. /**
  7935. * Copies the values of the given sphere to this instance.
  7936. *
  7937. * @param {Sphere} sphere - The sphere to copy.
  7938. * @return {Sphere} A reference to this sphere.
  7939. */
  7940. copy( sphere ) {
  7941. this.center.copy( sphere.center );
  7942. this.radius = sphere.radius;
  7943. return this;
  7944. }
  7945. /**
  7946. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7947. *
  7948. * Spheres with a radius of `0` contain only their center point and are not
  7949. * considered to be empty.
  7950. *
  7951. * @return {boolean} Whether this sphere is empty or not.
  7952. */
  7953. isEmpty() {
  7954. return ( this.radius < 0 );
  7955. }
  7956. /**
  7957. * Makes this sphere empty which means in encloses a zero space in 3D.
  7958. *
  7959. * @return {Sphere} A reference to this sphere.
  7960. */
  7961. makeEmpty() {
  7962. this.center.set( 0, 0, 0 );
  7963. this.radius = -1;
  7964. return this;
  7965. }
  7966. /**
  7967. * Returns `true` if this sphere contains the given point inclusive of
  7968. * the surface of the sphere.
  7969. *
  7970. * @param {Vector3} point - The point to check.
  7971. * @return {boolean} Whether this sphere contains the given point or not.
  7972. */
  7973. containsPoint( point ) {
  7974. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  7975. }
  7976. /**
  7977. * Returns the closest distance from the boundary of the sphere to the
  7978. * given point. If the sphere contains the point, the distance will
  7979. * be negative.
  7980. *
  7981. * @param {Vector3} point - The point to compute the distance to.
  7982. * @return {number} The distance to the point.
  7983. */
  7984. distanceToPoint( point ) {
  7985. return ( point.distanceTo( this.center ) - this.radius );
  7986. }
  7987. /**
  7988. * Returns `true` if this sphere intersects with the given one.
  7989. *
  7990. * @param {Sphere} sphere - The sphere to test.
  7991. * @return {boolean} Whether this sphere intersects with the given one or not.
  7992. */
  7993. intersectsSphere( sphere ) {
  7994. const radiusSum = this.radius + sphere.radius;
  7995. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  7996. }
  7997. /**
  7998. * Returns `true` if this sphere intersects with the given box.
  7999. *
  8000. * @param {Box3} box - The box to test.
  8001. * @return {boolean} Whether this sphere intersects with the given box or not.
  8002. */
  8003. intersectsBox( box ) {
  8004. return box.intersectsSphere( this );
  8005. }
  8006. /**
  8007. * Returns `true` if this sphere intersects with the given plane.
  8008. *
  8009. * @param {Plane} plane - The plane to test.
  8010. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8011. */
  8012. intersectsPlane( plane ) {
  8013. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8014. }
  8015. /**
  8016. * Clamps a point within the sphere. If the point is outside the sphere, it
  8017. * will clamp it to the closest point on the edge of the sphere. Points
  8018. * already inside the sphere will not be affected.
  8019. *
  8020. * @param {Vector3} point - The plane to clamp.
  8021. * @param {Vector3} target - The target vector that is used to store the method's result.
  8022. * @return {Vector3} The clamped point.
  8023. */
  8024. clampPoint( point, target ) {
  8025. const deltaLengthSq = this.center.distanceToSquared( point );
  8026. target.copy( point );
  8027. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8028. target.sub( this.center ).normalize();
  8029. target.multiplyScalar( this.radius ).add( this.center );
  8030. }
  8031. return target;
  8032. }
  8033. /**
  8034. * Returns a bounding box that encloses this sphere.
  8035. *
  8036. * @param {Box3} target - The target box that is used to store the method's result.
  8037. * @return {Box3} The bounding box that encloses this sphere.
  8038. */
  8039. getBoundingBox( target ) {
  8040. if ( this.isEmpty() ) {
  8041. // Empty sphere produces empty bounding box
  8042. target.makeEmpty();
  8043. return target;
  8044. }
  8045. target.set( this.center, this.center );
  8046. target.expandByScalar( this.radius );
  8047. return target;
  8048. }
  8049. /**
  8050. * Transforms this sphere with the given 4x4 transformation matrix.
  8051. *
  8052. * @param {Matrix4} matrix - The transformation matrix.
  8053. * @return {Sphere} A reference to this sphere.
  8054. */
  8055. applyMatrix4( matrix ) {
  8056. this.center.applyMatrix4( matrix );
  8057. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8058. return this;
  8059. }
  8060. /**
  8061. * Translates the sphere's center by the given offset.
  8062. *
  8063. * @param {Vector3} offset - The offset.
  8064. * @return {Sphere} A reference to this sphere.
  8065. */
  8066. translate( offset ) {
  8067. this.center.add( offset );
  8068. return this;
  8069. }
  8070. /**
  8071. * Expands the boundaries of this sphere to include the given point.
  8072. *
  8073. * @param {Vector3} point - The point to include.
  8074. * @return {Sphere} A reference to this sphere.
  8075. */
  8076. expandByPoint( point ) {
  8077. if ( this.isEmpty() ) {
  8078. this.center.copy( point );
  8079. this.radius = 0;
  8080. return this;
  8081. }
  8082. _v1$6.subVectors( point, this.center );
  8083. const lengthSq = _v1$6.lengthSq();
  8084. if ( lengthSq > ( this.radius * this.radius ) ) {
  8085. // calculate the minimal sphere
  8086. const length = Math.sqrt( lengthSq );
  8087. const delta = ( length - this.radius ) * 0.5;
  8088. this.center.addScaledVector( _v1$6, delta / length );
  8089. this.radius += delta;
  8090. }
  8091. return this;
  8092. }
  8093. /**
  8094. * Expands this sphere to enclose both the original sphere and the given sphere.
  8095. *
  8096. * @param {Sphere} sphere - The sphere to include.
  8097. * @return {Sphere} A reference to this sphere.
  8098. */
  8099. union( sphere ) {
  8100. if ( sphere.isEmpty() ) {
  8101. return this;
  8102. }
  8103. if ( this.isEmpty() ) {
  8104. this.copy( sphere );
  8105. return this;
  8106. }
  8107. if ( this.center.equals( sphere.center ) === true ) {
  8108. this.radius = Math.max( this.radius, sphere.radius );
  8109. } else {
  8110. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8111. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8112. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8113. }
  8114. return this;
  8115. }
  8116. /**
  8117. * Returns `true` if this sphere is equal with the given one.
  8118. *
  8119. * @param {Sphere} sphere - The sphere to test for equality.
  8120. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8121. */
  8122. equals( sphere ) {
  8123. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8124. }
  8125. /**
  8126. * Returns a new sphere with copied values from this instance.
  8127. *
  8128. * @return {Sphere} A clone of this instance.
  8129. */
  8130. clone() {
  8131. return new this.constructor().copy( this );
  8132. }
  8133. /**
  8134. * Returns a serialized structure of the bounding sphere.
  8135. *
  8136. * @return {Object} Serialized structure with fields representing the object state.
  8137. */
  8138. toJSON() {
  8139. return {
  8140. radius: this.radius,
  8141. center: this.center.toArray()
  8142. };
  8143. }
  8144. /**
  8145. * Returns a serialized structure of the bounding sphere.
  8146. *
  8147. * @param {Object} json - The serialized json to set the sphere from.
  8148. * @return {Box3} A reference to this bounding sphere.
  8149. */
  8150. fromJSON( json ) {
  8151. this.radius = json.radius;
  8152. this.center.fromArray( json.center );
  8153. return this;
  8154. }
  8155. }
  8156. const _vector$a = /*@__PURE__*/ new Vector3();
  8157. const _segCenter = /*@__PURE__*/ new Vector3();
  8158. const _segDir = /*@__PURE__*/ new Vector3();
  8159. const _diff = /*@__PURE__*/ new Vector3();
  8160. const _edge1 = /*@__PURE__*/ new Vector3();
  8161. const _edge2 = /*@__PURE__*/ new Vector3();
  8162. const _normal$1 = /*@__PURE__*/ new Vector3();
  8163. /**
  8164. * A ray that emits from an origin in a certain direction. The class is used by
  8165. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8166. * mouse picking (working out what objects in the 3D space the mouse is over)
  8167. * amongst other things.
  8168. */
  8169. class Ray {
  8170. /**
  8171. * Constructs a new ray.
  8172. *
  8173. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8174. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8175. */
  8176. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8177. /**
  8178. * The origin of the ray.
  8179. *
  8180. * @type {Vector3}
  8181. */
  8182. this.origin = origin;
  8183. /**
  8184. * The (normalized) direction of the ray.
  8185. *
  8186. * @type {Vector3}
  8187. */
  8188. this.direction = direction;
  8189. }
  8190. /**
  8191. * Sets the ray's components by copying the given values.
  8192. *
  8193. * @param {Vector3} origin - The origin.
  8194. * @param {Vector3} direction - The direction.
  8195. * @return {Ray} A reference to this ray.
  8196. */
  8197. set( origin, direction ) {
  8198. this.origin.copy( origin );
  8199. this.direction.copy( direction );
  8200. return this;
  8201. }
  8202. /**
  8203. * Copies the values of the given ray to this instance.
  8204. *
  8205. * @param {Ray} ray - The ray to copy.
  8206. * @return {Ray} A reference to this ray.
  8207. */
  8208. copy( ray ) {
  8209. this.origin.copy( ray.origin );
  8210. this.direction.copy( ray.direction );
  8211. return this;
  8212. }
  8213. /**
  8214. * Returns a vector that is located at a given distance along this ray.
  8215. *
  8216. * @param {number} t - The distance along the ray to retrieve a position for.
  8217. * @param {Vector3} target - The target vector that is used to store the method's result.
  8218. * @return {Vector3} A position on the ray.
  8219. */
  8220. at( t, target ) {
  8221. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8222. }
  8223. /**
  8224. * Adjusts the direction of the ray to point at the given vector in world space.
  8225. *
  8226. * @param {Vector3} v - The target position.
  8227. * @return {Ray} A reference to this ray.
  8228. */
  8229. lookAt( v ) {
  8230. this.direction.copy( v ).sub( this.origin ).normalize();
  8231. return this;
  8232. }
  8233. /**
  8234. * Shift the origin of this ray along its direction by the given distance.
  8235. *
  8236. * @param {number} t - The distance along the ray to interpolate.
  8237. * @return {Ray} A reference to this ray.
  8238. */
  8239. recast( t ) {
  8240. this.origin.copy( this.at( t, _vector$a ) );
  8241. return this;
  8242. }
  8243. /**
  8244. * Returns the point along this ray that is closest to the given point.
  8245. *
  8246. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8247. * @param {Vector3} target - The target vector that is used to store the method's result.
  8248. * @return {Vector3} The closest point on this ray.
  8249. */
  8250. closestPointToPoint( point, target ) {
  8251. target.subVectors( point, this.origin );
  8252. const directionDistance = target.dot( this.direction );
  8253. if ( directionDistance < 0 ) {
  8254. return target.copy( this.origin );
  8255. }
  8256. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8257. }
  8258. /**
  8259. * Returns the distance of the closest approach between this ray and the given point.
  8260. *
  8261. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8262. * @return {number} The distance.
  8263. */
  8264. distanceToPoint( point ) {
  8265. return Math.sqrt( this.distanceSqToPoint( point ) );
  8266. }
  8267. /**
  8268. * Returns the squared distance of the closest approach between this ray and the given point.
  8269. *
  8270. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8271. * @return {number} The squared distance.
  8272. */
  8273. distanceSqToPoint( point ) {
  8274. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8275. // point behind the ray
  8276. if ( directionDistance < 0 ) {
  8277. return this.origin.distanceToSquared( point );
  8278. }
  8279. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8280. return _vector$a.distanceToSquared( point );
  8281. }
  8282. /**
  8283. * Returns the squared distance between this ray and the given line segment.
  8284. *
  8285. * @param {Vector3} v0 - The start point of the line segment.
  8286. * @param {Vector3} v1 - The end point of the line segment.
  8287. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8288. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8289. * @return {number} The squared distance.
  8290. */
  8291. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8292. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8293. // It returns the min distance between the ray and the segment
  8294. // defined by v0 and v1
  8295. // It can also set two optional targets :
  8296. // - The closest point on the ray
  8297. // - The closest point on the segment
  8298. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8299. _segDir.copy( v1 ).sub( v0 ).normalize();
  8300. _diff.copy( this.origin ).sub( _segCenter );
  8301. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8302. const a01 = - this.direction.dot( _segDir );
  8303. const b0 = _diff.dot( this.direction );
  8304. const b1 = - _diff.dot( _segDir );
  8305. const c = _diff.lengthSq();
  8306. const det = Math.abs( 1 - a01 * a01 );
  8307. let s0, s1, sqrDist, extDet;
  8308. if ( det > 0 ) {
  8309. // The ray and segment are not parallel.
  8310. s0 = a01 * b1 - b0;
  8311. s1 = a01 * b0 - b1;
  8312. extDet = segExtent * det;
  8313. if ( s0 >= 0 ) {
  8314. if ( s1 >= - extDet ) {
  8315. if ( s1 <= extDet ) {
  8316. // region 0
  8317. // Minimum at interior points of ray and segment.
  8318. const invDet = 1 / det;
  8319. s0 *= invDet;
  8320. s1 *= invDet;
  8321. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8322. } else {
  8323. // region 1
  8324. s1 = segExtent;
  8325. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8326. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8327. }
  8328. } else {
  8329. // region 5
  8330. s1 = - segExtent;
  8331. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8332. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8333. }
  8334. } else {
  8335. if ( s1 <= - extDet ) {
  8336. // region 4
  8337. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8338. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8339. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8340. } else if ( s1 <= extDet ) {
  8341. // region 3
  8342. s0 = 0;
  8343. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8344. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8345. } else {
  8346. // region 2
  8347. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8348. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8349. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8350. }
  8351. }
  8352. } else {
  8353. // Ray and segment are parallel.
  8354. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8355. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8356. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8357. }
  8358. if ( optionalPointOnRay ) {
  8359. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8360. }
  8361. if ( optionalPointOnSegment ) {
  8362. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8363. }
  8364. return sqrDist;
  8365. }
  8366. /**
  8367. * Intersects this ray with the given sphere, returning the intersection
  8368. * point or `null` if there is no intersection.
  8369. *
  8370. * @param {Sphere} sphere - The sphere to intersect.
  8371. * @param {Vector3} target - The target vector that is used to store the method's result.
  8372. * @return {?Vector3} The intersection point.
  8373. */
  8374. intersectSphere( sphere, target ) {
  8375. _vector$a.subVectors( sphere.center, this.origin );
  8376. const tca = _vector$a.dot( this.direction );
  8377. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8378. const radius2 = sphere.radius * sphere.radius;
  8379. if ( d2 > radius2 ) return null;
  8380. const thc = Math.sqrt( radius2 - d2 );
  8381. // t0 = first intersect point - entrance on front of sphere
  8382. const t0 = tca - thc;
  8383. // t1 = second intersect point - exit point on back of sphere
  8384. const t1 = tca + thc;
  8385. // test to see if t1 is behind the ray - if so, return null
  8386. if ( t1 < 0 ) return null;
  8387. // test to see if t0 is behind the ray:
  8388. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8389. // in order to always return an intersect point that is in front of the ray.
  8390. if ( t0 < 0 ) return this.at( t1, target );
  8391. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8392. return this.at( t0, target );
  8393. }
  8394. /**
  8395. * Returns `true` if this ray intersects with the given sphere.
  8396. *
  8397. * @param {Sphere} sphere - The sphere to intersect.
  8398. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8399. */
  8400. intersectsSphere( sphere ) {
  8401. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8402. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8403. }
  8404. /**
  8405. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8406. * does not intersect with the plane.
  8407. *
  8408. * @param {Plane} plane - The plane to compute the distance to.
  8409. * @return {?number} Whether this ray intersects with the given sphere or not.
  8410. */
  8411. distanceToPlane( plane ) {
  8412. const denominator = plane.normal.dot( this.direction );
  8413. if ( denominator === 0 ) {
  8414. // line is coplanar, return origin
  8415. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8416. return 0;
  8417. }
  8418. // Null is preferable to undefined since undefined means.... it is undefined
  8419. return null;
  8420. }
  8421. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8422. // Return if the ray never intersects the plane
  8423. return t >= 0 ? t : null;
  8424. }
  8425. /**
  8426. * Intersects this ray with the given plane, returning the intersection
  8427. * point or `null` if there is no intersection.
  8428. *
  8429. * @param {Plane} plane - The plane to intersect.
  8430. * @param {Vector3} target - The target vector that is used to store the method's result.
  8431. * @return {?Vector3} The intersection point.
  8432. */
  8433. intersectPlane( plane, target ) {
  8434. const t = this.distanceToPlane( plane );
  8435. if ( t === null ) {
  8436. return null;
  8437. }
  8438. return this.at( t, target );
  8439. }
  8440. /**
  8441. * Returns `true` if this ray intersects with the given plane.
  8442. *
  8443. * @param {Plane} plane - The plane to intersect.
  8444. * @return {boolean} Whether this ray intersects with the given plane or not.
  8445. */
  8446. intersectsPlane( plane ) {
  8447. // check if the ray lies on the plane first
  8448. const distToPoint = plane.distanceToPoint( this.origin );
  8449. if ( distToPoint === 0 ) {
  8450. return true;
  8451. }
  8452. const denominator = plane.normal.dot( this.direction );
  8453. if ( denominator * distToPoint < 0 ) {
  8454. return true;
  8455. }
  8456. // ray origin is behind the plane (and is pointing behind it)
  8457. return false;
  8458. }
  8459. /**
  8460. * Intersects this ray with the given bounding box, returning the intersection
  8461. * point or `null` if there is no intersection.
  8462. *
  8463. * @param {Box3} box - The box to intersect.
  8464. * @param {Vector3} target - The target vector that is used to store the method's result.
  8465. * @return {?Vector3} The intersection point.
  8466. */
  8467. intersectBox( box, target ) {
  8468. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8469. const invdirx = 1 / this.direction.x,
  8470. invdiry = 1 / this.direction.y,
  8471. invdirz = 1 / this.direction.z;
  8472. const origin = this.origin;
  8473. if ( invdirx >= 0 ) {
  8474. tmin = ( box.min.x - origin.x ) * invdirx;
  8475. tmax = ( box.max.x - origin.x ) * invdirx;
  8476. } else {
  8477. tmin = ( box.max.x - origin.x ) * invdirx;
  8478. tmax = ( box.min.x - origin.x ) * invdirx;
  8479. }
  8480. if ( invdiry >= 0 ) {
  8481. tymin = ( box.min.y - origin.y ) * invdiry;
  8482. tymax = ( box.max.y - origin.y ) * invdiry;
  8483. } else {
  8484. tymin = ( box.max.y - origin.y ) * invdiry;
  8485. tymax = ( box.min.y - origin.y ) * invdiry;
  8486. }
  8487. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8488. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8489. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8490. if ( invdirz >= 0 ) {
  8491. tzmin = ( box.min.z - origin.z ) * invdirz;
  8492. tzmax = ( box.max.z - origin.z ) * invdirz;
  8493. } else {
  8494. tzmin = ( box.max.z - origin.z ) * invdirz;
  8495. tzmax = ( box.min.z - origin.z ) * invdirz;
  8496. }
  8497. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8498. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8499. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8500. //return point closest to the ray (positive side)
  8501. if ( tmax < 0 ) return null;
  8502. return this.at( tmin >= 0 ? tmin : tmax, target );
  8503. }
  8504. /**
  8505. * Returns `true` if this ray intersects with the given box.
  8506. *
  8507. * @param {Box3} box - The box to intersect.
  8508. * @return {boolean} Whether this ray intersects with the given box or not.
  8509. */
  8510. intersectsBox( box ) {
  8511. return this.intersectBox( box, _vector$a ) !== null;
  8512. }
  8513. /**
  8514. * Intersects this ray with the given triangle, returning the intersection
  8515. * point or `null` if there is no intersection.
  8516. *
  8517. * @param {Vector3} a - The first vertex of the triangle.
  8518. * @param {Vector3} b - The second vertex of the triangle.
  8519. * @param {Vector3} c - The third vertex of the triangle.
  8520. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8521. * @param {Vector3} target - The target vector that is used to store the method's result.
  8522. * @return {?Vector3} The intersection point.
  8523. */
  8524. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8525. // Compute the offset origin, edges, and normal.
  8526. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8527. _edge1.subVectors( b, a );
  8528. _edge2.subVectors( c, a );
  8529. _normal$1.crossVectors( _edge1, _edge2 );
  8530. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8531. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8532. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8533. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8534. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8535. let DdN = this.direction.dot( _normal$1 );
  8536. let sign;
  8537. if ( DdN > 0 ) {
  8538. if ( backfaceCulling ) return null;
  8539. sign = 1;
  8540. } else if ( DdN < 0 ) {
  8541. sign = -1;
  8542. DdN = - DdN;
  8543. } else {
  8544. return null;
  8545. }
  8546. _diff.subVectors( this.origin, a );
  8547. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8548. // b1 < 0, no intersection
  8549. if ( DdQxE2 < 0 ) {
  8550. return null;
  8551. }
  8552. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8553. // b2 < 0, no intersection
  8554. if ( DdE1xQ < 0 ) {
  8555. return null;
  8556. }
  8557. // b1+b2 > 1, no intersection
  8558. if ( DdQxE2 + DdE1xQ > DdN ) {
  8559. return null;
  8560. }
  8561. // Line intersects triangle, check if ray does.
  8562. const QdN = - sign * _diff.dot( _normal$1 );
  8563. // t < 0, no intersection
  8564. if ( QdN < 0 ) {
  8565. return null;
  8566. }
  8567. // Ray intersects triangle.
  8568. return this.at( QdN / DdN, target );
  8569. }
  8570. /**
  8571. * Transforms this ray with the given 4x4 transformation matrix.
  8572. *
  8573. * @param {Matrix4} matrix4 - The transformation matrix.
  8574. * @return {Ray} A reference to this ray.
  8575. */
  8576. applyMatrix4( matrix4 ) {
  8577. this.origin.applyMatrix4( matrix4 );
  8578. this.direction.transformDirection( matrix4 );
  8579. return this;
  8580. }
  8581. /**
  8582. * Returns `true` if this ray is equal with the given one.
  8583. *
  8584. * @param {Ray} ray - The ray to test for equality.
  8585. * @return {boolean} Whether this ray is equal with the given one.
  8586. */
  8587. equals( ray ) {
  8588. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8589. }
  8590. /**
  8591. * Returns a new ray with copied values from this instance.
  8592. *
  8593. * @return {Ray} A clone of this instance.
  8594. */
  8595. clone() {
  8596. return new this.constructor().copy( this );
  8597. }
  8598. }
  8599. /**
  8600. * Represents a 4x4 matrix.
  8601. *
  8602. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8603. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial]{@link https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices}
  8604. *
  8605. * This allows a 3D vector representing a point in 3D space to undergo
  8606. * transformations such as translation, rotation, shear, scale, reflection,
  8607. * orthogonal or perspective projection and so on, by being multiplied by the
  8608. * matrix. This is known as `applying` the matrix to the vector.
  8609. *
  8610. * A Note on Row-Major and Column-Major Ordering:
  8611. *
  8612. * The constructor and {@link Matrix3#set} method take arguments in
  8613. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8614. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8615. * This means that calling:
  8616. * ```js
  8617. * const m = new THREE.Matrix4();
  8618. * m.set( 11, 12, 13, 14,
  8619. * 21, 22, 23, 24,
  8620. * 31, 32, 33, 34,
  8621. * 41, 42, 43, 44 );
  8622. * ```
  8623. * will result in the elements array containing:
  8624. * ```js
  8625. * m.elements = [ 11, 21, 31, 41,
  8626. * 12, 22, 32, 42,
  8627. * 13, 23, 33, 43,
  8628. * 14, 24, 34, 44 ];
  8629. * ```
  8630. * and internally all calculations are performed using column-major ordering.
  8631. * However, as the actual ordering makes no difference mathematically and
  8632. * most people are used to thinking about matrices in row-major order, the
  8633. * three.js documentation shows matrices in row-major order. Just bear in
  8634. * mind that if you are reading the source code, you'll have to take the
  8635. * transpose of any matrices outlined here to make sense of the calculations.
  8636. */
  8637. class Matrix4 {
  8638. /**
  8639. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8640. * in row-major order. If no arguments are provided, the constructor
  8641. * initializes the matrix as an identity matrix.
  8642. *
  8643. * @param {number} [n11] - 1-1 matrix element.
  8644. * @param {number} [n12] - 1-2 matrix element.
  8645. * @param {number} [n13] - 1-3 matrix element.
  8646. * @param {number} [n14] - 1-4 matrix element.
  8647. * @param {number} [n21] - 2-1 matrix element.
  8648. * @param {number} [n22] - 2-2 matrix element.
  8649. * @param {number} [n23] - 2-3 matrix element.
  8650. * @param {number} [n24] - 2-4 matrix element.
  8651. * @param {number} [n31] - 3-1 matrix element.
  8652. * @param {number} [n32] - 3-2 matrix element.
  8653. * @param {number} [n33] - 3-3 matrix element.
  8654. * @param {number} [n34] - 3-4 matrix element.
  8655. * @param {number} [n41] - 4-1 matrix element.
  8656. * @param {number} [n42] - 4-2 matrix element.
  8657. * @param {number} [n43] - 4-3 matrix element.
  8658. * @param {number} [n44] - 4-4 matrix element.
  8659. */
  8660. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8661. /**
  8662. * This flag can be used for type testing.
  8663. *
  8664. * @type {boolean}
  8665. * @readonly
  8666. * @default true
  8667. */
  8668. Matrix4.prototype.isMatrix4 = true;
  8669. /**
  8670. * A column-major list of matrix values.
  8671. *
  8672. * @type {Array<number>}
  8673. */
  8674. this.elements = [
  8675. 1, 0, 0, 0,
  8676. 0, 1, 0, 0,
  8677. 0, 0, 1, 0,
  8678. 0, 0, 0, 1
  8679. ];
  8680. if ( n11 !== undefined ) {
  8681. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8682. }
  8683. }
  8684. /**
  8685. * Sets the elements of the matrix.The arguments are supposed to be
  8686. * in row-major order.
  8687. *
  8688. * @param {number} [n11] - 1-1 matrix element.
  8689. * @param {number} [n12] - 1-2 matrix element.
  8690. * @param {number} [n13] - 1-3 matrix element.
  8691. * @param {number} [n14] - 1-4 matrix element.
  8692. * @param {number} [n21] - 2-1 matrix element.
  8693. * @param {number} [n22] - 2-2 matrix element.
  8694. * @param {number} [n23] - 2-3 matrix element.
  8695. * @param {number} [n24] - 2-4 matrix element.
  8696. * @param {number} [n31] - 3-1 matrix element.
  8697. * @param {number} [n32] - 3-2 matrix element.
  8698. * @param {number} [n33] - 3-3 matrix element.
  8699. * @param {number} [n34] - 3-4 matrix element.
  8700. * @param {number} [n41] - 4-1 matrix element.
  8701. * @param {number} [n42] - 4-2 matrix element.
  8702. * @param {number} [n43] - 4-3 matrix element.
  8703. * @param {number} [n44] - 4-4 matrix element.
  8704. * @return {Matrix4} A reference to this matrix.
  8705. */
  8706. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8707. const te = this.elements;
  8708. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8709. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8710. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8711. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8712. return this;
  8713. }
  8714. /**
  8715. * Sets this matrix to the 4x4 identity matrix.
  8716. *
  8717. * @return {Matrix4} A reference to this matrix.
  8718. */
  8719. identity() {
  8720. this.set(
  8721. 1, 0, 0, 0,
  8722. 0, 1, 0, 0,
  8723. 0, 0, 1, 0,
  8724. 0, 0, 0, 1
  8725. );
  8726. return this;
  8727. }
  8728. /**
  8729. * Returns a matrix with copied values from this instance.
  8730. *
  8731. * @return {Matrix4} A clone of this instance.
  8732. */
  8733. clone() {
  8734. return new Matrix4().fromArray( this.elements );
  8735. }
  8736. /**
  8737. * Copies the values of the given matrix to this instance.
  8738. *
  8739. * @param {Matrix4} m - The matrix to copy.
  8740. * @return {Matrix4} A reference to this matrix.
  8741. */
  8742. copy( m ) {
  8743. const te = this.elements;
  8744. const me = m.elements;
  8745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8746. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8747. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8748. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8749. return this;
  8750. }
  8751. /**
  8752. * Copies the translation component of the given matrix
  8753. * into this matrix's translation component.
  8754. *
  8755. * @param {Matrix4} m - The matrix to copy the translation component.
  8756. * @return {Matrix4} A reference to this matrix.
  8757. */
  8758. copyPosition( m ) {
  8759. const te = this.elements, me = m.elements;
  8760. te[ 12 ] = me[ 12 ];
  8761. te[ 13 ] = me[ 13 ];
  8762. te[ 14 ] = me[ 14 ];
  8763. return this;
  8764. }
  8765. /**
  8766. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8767. *
  8768. * @param {Matrix3} m - The 3x3 matrix.
  8769. * @return {Matrix4} A reference to this matrix.
  8770. */
  8771. setFromMatrix3( m ) {
  8772. const me = m.elements;
  8773. this.set(
  8774. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8775. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8776. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8777. 0, 0, 0, 1
  8778. );
  8779. return this;
  8780. }
  8781. /**
  8782. * Extracts the basis of this matrix into the three axis vectors provided.
  8783. *
  8784. * @param {Vector3} xAxis - The basis's x axis.
  8785. * @param {Vector3} yAxis - The basis's y axis.
  8786. * @param {Vector3} zAxis - The basis's z axis.
  8787. * @return {Matrix4} A reference to this matrix.
  8788. */
  8789. extractBasis( xAxis, yAxis, zAxis ) {
  8790. xAxis.setFromMatrixColumn( this, 0 );
  8791. yAxis.setFromMatrixColumn( this, 1 );
  8792. zAxis.setFromMatrixColumn( this, 2 );
  8793. return this;
  8794. }
  8795. /**
  8796. * Sets the given basis vectors to this matrix.
  8797. *
  8798. * @param {Vector3} xAxis - The basis's x axis.
  8799. * @param {Vector3} yAxis - The basis's y axis.
  8800. * @param {Vector3} zAxis - The basis's z axis.
  8801. * @return {Matrix4} A reference to this matrix.
  8802. */
  8803. makeBasis( xAxis, yAxis, zAxis ) {
  8804. this.set(
  8805. xAxis.x, yAxis.x, zAxis.x, 0,
  8806. xAxis.y, yAxis.y, zAxis.y, 0,
  8807. xAxis.z, yAxis.z, zAxis.z, 0,
  8808. 0, 0, 0, 1
  8809. );
  8810. return this;
  8811. }
  8812. /**
  8813. * Extracts the rotation component of the given matrix
  8814. * into this matrix's rotation component.
  8815. *
  8816. * Note: This method does not support reflection matrices.
  8817. *
  8818. * @param {Matrix4} m - The matrix.
  8819. * @return {Matrix4} A reference to this matrix.
  8820. */
  8821. extractRotation( m ) {
  8822. const te = this.elements;
  8823. const me = m.elements;
  8824. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8825. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8826. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8827. te[ 0 ] = me[ 0 ] * scaleX;
  8828. te[ 1 ] = me[ 1 ] * scaleX;
  8829. te[ 2 ] = me[ 2 ] * scaleX;
  8830. te[ 3 ] = 0;
  8831. te[ 4 ] = me[ 4 ] * scaleY;
  8832. te[ 5 ] = me[ 5 ] * scaleY;
  8833. te[ 6 ] = me[ 6 ] * scaleY;
  8834. te[ 7 ] = 0;
  8835. te[ 8 ] = me[ 8 ] * scaleZ;
  8836. te[ 9 ] = me[ 9 ] * scaleZ;
  8837. te[ 10 ] = me[ 10 ] * scaleZ;
  8838. te[ 11 ] = 0;
  8839. te[ 12 ] = 0;
  8840. te[ 13 ] = 0;
  8841. te[ 14 ] = 0;
  8842. te[ 15 ] = 1;
  8843. return this;
  8844. }
  8845. /**
  8846. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8847. * the rotation specified by the given Euler angles. The rest of
  8848. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8849. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8850. * for a complete list.
  8851. *
  8852. * @param {Euler} euler - The Euler angles.
  8853. * @return {Matrix4} A reference to this matrix.
  8854. */
  8855. makeRotationFromEuler( euler ) {
  8856. const te = this.elements;
  8857. const x = euler.x, y = euler.y, z = euler.z;
  8858. const a = Math.cos( x ), b = Math.sin( x );
  8859. const c = Math.cos( y ), d = Math.sin( y );
  8860. const e = Math.cos( z ), f = Math.sin( z );
  8861. if ( euler.order === 'XYZ' ) {
  8862. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8863. te[ 0 ] = c * e;
  8864. te[ 4 ] = - c * f;
  8865. te[ 8 ] = d;
  8866. te[ 1 ] = af + be * d;
  8867. te[ 5 ] = ae - bf * d;
  8868. te[ 9 ] = - b * c;
  8869. te[ 2 ] = bf - ae * d;
  8870. te[ 6 ] = be + af * d;
  8871. te[ 10 ] = a * c;
  8872. } else if ( euler.order === 'YXZ' ) {
  8873. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8874. te[ 0 ] = ce + df * b;
  8875. te[ 4 ] = de * b - cf;
  8876. te[ 8 ] = a * d;
  8877. te[ 1 ] = a * f;
  8878. te[ 5 ] = a * e;
  8879. te[ 9 ] = - b;
  8880. te[ 2 ] = cf * b - de;
  8881. te[ 6 ] = df + ce * b;
  8882. te[ 10 ] = a * c;
  8883. } else if ( euler.order === 'ZXY' ) {
  8884. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8885. te[ 0 ] = ce - df * b;
  8886. te[ 4 ] = - a * f;
  8887. te[ 8 ] = de + cf * b;
  8888. te[ 1 ] = cf + de * b;
  8889. te[ 5 ] = a * e;
  8890. te[ 9 ] = df - ce * b;
  8891. te[ 2 ] = - a * d;
  8892. te[ 6 ] = b;
  8893. te[ 10 ] = a * c;
  8894. } else if ( euler.order === 'ZYX' ) {
  8895. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8896. te[ 0 ] = c * e;
  8897. te[ 4 ] = be * d - af;
  8898. te[ 8 ] = ae * d + bf;
  8899. te[ 1 ] = c * f;
  8900. te[ 5 ] = bf * d + ae;
  8901. te[ 9 ] = af * d - be;
  8902. te[ 2 ] = - d;
  8903. te[ 6 ] = b * c;
  8904. te[ 10 ] = a * c;
  8905. } else if ( euler.order === 'YZX' ) {
  8906. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8907. te[ 0 ] = c * e;
  8908. te[ 4 ] = bd - ac * f;
  8909. te[ 8 ] = bc * f + ad;
  8910. te[ 1 ] = f;
  8911. te[ 5 ] = a * e;
  8912. te[ 9 ] = - b * e;
  8913. te[ 2 ] = - d * e;
  8914. te[ 6 ] = ad * f + bc;
  8915. te[ 10 ] = ac - bd * f;
  8916. } else if ( euler.order === 'XZY' ) {
  8917. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8918. te[ 0 ] = c * e;
  8919. te[ 4 ] = - f;
  8920. te[ 8 ] = d * e;
  8921. te[ 1 ] = ac * f + bd;
  8922. te[ 5 ] = a * e;
  8923. te[ 9 ] = ad * f - bc;
  8924. te[ 2 ] = bc * f - ad;
  8925. te[ 6 ] = b * e;
  8926. te[ 10 ] = bd * f + ac;
  8927. }
  8928. // bottom row
  8929. te[ 3 ] = 0;
  8930. te[ 7 ] = 0;
  8931. te[ 11 ] = 0;
  8932. // last column
  8933. te[ 12 ] = 0;
  8934. te[ 13 ] = 0;
  8935. te[ 14 ] = 0;
  8936. te[ 15 ] = 1;
  8937. return this;
  8938. }
  8939. /**
  8940. * Sets the rotation component of this matrix to the rotation specified by
  8941. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8942. * The rest of the matrix is set to the identity.
  8943. *
  8944. * @param {Quaternion} q - The Quaternion.
  8945. * @return {Matrix4} A reference to this matrix.
  8946. */
  8947. makeRotationFromQuaternion( q ) {
  8948. return this.compose( _zero, q, _one );
  8949. }
  8950. /**
  8951. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8952. * `target`, and oriented by the up-direction.
  8953. *
  8954. * @param {Vector3} eye - The eye vector.
  8955. * @param {Vector3} target - The target vector.
  8956. * @param {Vector3} up - The up vector.
  8957. * @return {Matrix4} A reference to this matrix.
  8958. */
  8959. lookAt( eye, target, up ) {
  8960. const te = this.elements;
  8961. _z.subVectors( eye, target );
  8962. if ( _z.lengthSq() === 0 ) {
  8963. // eye and target are in the same position
  8964. _z.z = 1;
  8965. }
  8966. _z.normalize();
  8967. _x.crossVectors( up, _z );
  8968. if ( _x.lengthSq() === 0 ) {
  8969. // up and z are parallel
  8970. if ( Math.abs( up.z ) === 1 ) {
  8971. _z.x += 0.0001;
  8972. } else {
  8973. _z.z += 0.0001;
  8974. }
  8975. _z.normalize();
  8976. _x.crossVectors( up, _z );
  8977. }
  8978. _x.normalize();
  8979. _y.crossVectors( _z, _x );
  8980. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  8981. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  8982. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  8983. return this;
  8984. }
  8985. /**
  8986. * Post-multiplies this matrix by the given 4x4 matrix.
  8987. *
  8988. * @param {Matrix4} m - The matrix to multiply with.
  8989. * @return {Matrix4} A reference to this matrix.
  8990. */
  8991. multiply( m ) {
  8992. return this.multiplyMatrices( this, m );
  8993. }
  8994. /**
  8995. * Pre-multiplies this matrix by the given 4x4 matrix.
  8996. *
  8997. * @param {Matrix4} m - The matrix to multiply with.
  8998. * @return {Matrix4} A reference to this matrix.
  8999. */
  9000. premultiply( m ) {
  9001. return this.multiplyMatrices( m, this );
  9002. }
  9003. /**
  9004. * Multiples the given 4x4 matrices and stores the result
  9005. * in this matrix.
  9006. *
  9007. * @param {Matrix4} a - The first matrix.
  9008. * @param {Matrix4} b - The second matrix.
  9009. * @return {Matrix4} A reference to this matrix.
  9010. */
  9011. multiplyMatrices( a, b ) {
  9012. const ae = a.elements;
  9013. const be = b.elements;
  9014. const te = this.elements;
  9015. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9016. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9017. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9018. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9019. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9020. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9021. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9022. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9023. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9024. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9025. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9026. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9027. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9028. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9029. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9030. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9031. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9032. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9033. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9034. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9035. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9036. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9037. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9038. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9039. return this;
  9040. }
  9041. /**
  9042. * Multiplies every component of the matrix by the given scalar.
  9043. *
  9044. * @param {number} s - The scalar.
  9045. * @return {Matrix4} A reference to this matrix.
  9046. */
  9047. multiplyScalar( s ) {
  9048. const te = this.elements;
  9049. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9050. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9051. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9052. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9053. return this;
  9054. }
  9055. /**
  9056. * Computes and returns the determinant of this matrix.
  9057. *
  9058. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9059. *
  9060. * @return {number} The determinant.
  9061. */
  9062. determinant() {
  9063. const te = this.elements;
  9064. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9065. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9066. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9067. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9068. //TODO: make this more efficient
  9069. return (
  9070. n41 * (
  9071. + n14 * n23 * n32
  9072. - n13 * n24 * n32
  9073. - n14 * n22 * n33
  9074. + n12 * n24 * n33
  9075. + n13 * n22 * n34
  9076. - n12 * n23 * n34
  9077. ) +
  9078. n42 * (
  9079. + n11 * n23 * n34
  9080. - n11 * n24 * n33
  9081. + n14 * n21 * n33
  9082. - n13 * n21 * n34
  9083. + n13 * n24 * n31
  9084. - n14 * n23 * n31
  9085. ) +
  9086. n43 * (
  9087. + n11 * n24 * n32
  9088. - n11 * n22 * n34
  9089. - n14 * n21 * n32
  9090. + n12 * n21 * n34
  9091. + n14 * n22 * n31
  9092. - n12 * n24 * n31
  9093. ) +
  9094. n44 * (
  9095. - n13 * n22 * n31
  9096. - n11 * n23 * n32
  9097. + n11 * n22 * n33
  9098. + n13 * n21 * n32
  9099. - n12 * n21 * n33
  9100. + n12 * n23 * n31
  9101. )
  9102. );
  9103. }
  9104. /**
  9105. * Transposes this matrix in place.
  9106. *
  9107. * @return {Matrix4} A reference to this matrix.
  9108. */
  9109. transpose() {
  9110. const te = this.elements;
  9111. let tmp;
  9112. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9113. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9114. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9115. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9116. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9117. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9118. return this;
  9119. }
  9120. /**
  9121. * Sets the position component for this matrix from the given vector,
  9122. * without affecting the rest of the matrix.
  9123. *
  9124. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9125. * @param {number} y - The y component of the vector.
  9126. * @param {number} z - The z component of the vector.
  9127. * @return {Matrix4} A reference to this matrix.
  9128. */
  9129. setPosition( x, y, z ) {
  9130. const te = this.elements;
  9131. if ( x.isVector3 ) {
  9132. te[ 12 ] = x.x;
  9133. te[ 13 ] = x.y;
  9134. te[ 14 ] = x.z;
  9135. } else {
  9136. te[ 12 ] = x;
  9137. te[ 13 ] = y;
  9138. te[ 14 ] = z;
  9139. }
  9140. return this;
  9141. }
  9142. /**
  9143. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9144. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9145. * a zero matrix instead.
  9146. *
  9147. * @return {Matrix4} A reference to this matrix.
  9148. */
  9149. invert() {
  9150. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9151. const te = this.elements,
  9152. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9153. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9154. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9155. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9156. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9157. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9158. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9159. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9160. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9161. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9162. const detInv = 1 / det;
  9163. te[ 0 ] = t11 * detInv;
  9164. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9165. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9166. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9167. te[ 4 ] = t12 * detInv;
  9168. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9169. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9170. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9171. te[ 8 ] = t13 * detInv;
  9172. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9173. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9174. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9175. te[ 12 ] = t14 * detInv;
  9176. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9177. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9178. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9179. return this;
  9180. }
  9181. /**
  9182. * Multiplies the columns of this matrix by the given vector.
  9183. *
  9184. * @param {Vector3} v - The scale vector.
  9185. * @return {Matrix4} A reference to this matrix.
  9186. */
  9187. scale( v ) {
  9188. const te = this.elements;
  9189. const x = v.x, y = v.y, z = v.z;
  9190. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9191. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9192. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9193. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9194. return this;
  9195. }
  9196. /**
  9197. * Gets the maximum scale value of the three axes.
  9198. *
  9199. * @return {number} The maximum scale.
  9200. */
  9201. getMaxScaleOnAxis() {
  9202. const te = this.elements;
  9203. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9204. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9205. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9206. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9207. }
  9208. /**
  9209. * Sets this matrix as a translation transform from the given vector.
  9210. *
  9211. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9212. * @param {number} y - The amount to translate in the Y axis.
  9213. * @param {number} z - The amount to translate in the z axis.
  9214. * @return {Matrix4} A reference to this matrix.
  9215. */
  9216. makeTranslation( x, y, z ) {
  9217. if ( x.isVector3 ) {
  9218. this.set(
  9219. 1, 0, 0, x.x,
  9220. 0, 1, 0, x.y,
  9221. 0, 0, 1, x.z,
  9222. 0, 0, 0, 1
  9223. );
  9224. } else {
  9225. this.set(
  9226. 1, 0, 0, x,
  9227. 0, 1, 0, y,
  9228. 0, 0, 1, z,
  9229. 0, 0, 0, 1
  9230. );
  9231. }
  9232. return this;
  9233. }
  9234. /**
  9235. * Sets this matrix as a rotational transformation around the X axis by
  9236. * the given angle.
  9237. *
  9238. * @param {number} theta - The rotation in radians.
  9239. * @return {Matrix4} A reference to this matrix.
  9240. */
  9241. makeRotationX( theta ) {
  9242. const c = Math.cos( theta ), s = Math.sin( theta );
  9243. this.set(
  9244. 1, 0, 0, 0,
  9245. 0, c, - s, 0,
  9246. 0, s, c, 0,
  9247. 0, 0, 0, 1
  9248. );
  9249. return this;
  9250. }
  9251. /**
  9252. * Sets this matrix as a rotational transformation around the Y axis by
  9253. * the given angle.
  9254. *
  9255. * @param {number} theta - The rotation in radians.
  9256. * @return {Matrix4} A reference to this matrix.
  9257. */
  9258. makeRotationY( theta ) {
  9259. const c = Math.cos( theta ), s = Math.sin( theta );
  9260. this.set(
  9261. c, 0, s, 0,
  9262. 0, 1, 0, 0,
  9263. - s, 0, c, 0,
  9264. 0, 0, 0, 1
  9265. );
  9266. return this;
  9267. }
  9268. /**
  9269. * Sets this matrix as a rotational transformation around the Z axis by
  9270. * the given angle.
  9271. *
  9272. * @param {number} theta - The rotation in radians.
  9273. * @return {Matrix4} A reference to this matrix.
  9274. */
  9275. makeRotationZ( theta ) {
  9276. const c = Math.cos( theta ), s = Math.sin( theta );
  9277. this.set(
  9278. c, - s, 0, 0,
  9279. s, c, 0, 0,
  9280. 0, 0, 1, 0,
  9281. 0, 0, 0, 1
  9282. );
  9283. return this;
  9284. }
  9285. /**
  9286. * Sets this matrix as a rotational transformation around the given axis by
  9287. * the given angle.
  9288. *
  9289. * This is a somewhat controversial but mathematically sound alternative to
  9290. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9291. *
  9292. * @param {Vector3} axis - The normalized rotation axis.
  9293. * @param {number} angle - The rotation in radians.
  9294. * @return {Matrix4} A reference to this matrix.
  9295. */
  9296. makeRotationAxis( axis, angle ) {
  9297. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9298. const c = Math.cos( angle );
  9299. const s = Math.sin( angle );
  9300. const t = 1 - c;
  9301. const x = axis.x, y = axis.y, z = axis.z;
  9302. const tx = t * x, ty = t * y;
  9303. this.set(
  9304. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9305. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9306. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9307. 0, 0, 0, 1
  9308. );
  9309. return this;
  9310. }
  9311. /**
  9312. * Sets this matrix as a scale transformation.
  9313. *
  9314. * @param {number} x - The amount to scale in the X axis.
  9315. * @param {number} y - The amount to scale in the Y axis.
  9316. * @param {number} z - The amount to scale in the Z axis.
  9317. * @return {Matrix4} A reference to this matrix.
  9318. */
  9319. makeScale( x, y, z ) {
  9320. this.set(
  9321. x, 0, 0, 0,
  9322. 0, y, 0, 0,
  9323. 0, 0, z, 0,
  9324. 0, 0, 0, 1
  9325. );
  9326. return this;
  9327. }
  9328. /**
  9329. * Sets this matrix as a shear transformation.
  9330. *
  9331. * @param {number} xy - The amount to shear X by Y.
  9332. * @param {number} xz - The amount to shear X by Z.
  9333. * @param {number} yx - The amount to shear Y by X.
  9334. * @param {number} yz - The amount to shear Y by Z.
  9335. * @param {number} zx - The amount to shear Z by X.
  9336. * @param {number} zy - The amount to shear Z by Y.
  9337. * @return {Matrix4} A reference to this matrix.
  9338. */
  9339. makeShear( xy, xz, yx, yz, zx, zy ) {
  9340. this.set(
  9341. 1, yx, zx, 0,
  9342. xy, 1, zy, 0,
  9343. xz, yz, 1, 0,
  9344. 0, 0, 0, 1
  9345. );
  9346. return this;
  9347. }
  9348. /**
  9349. * Sets this matrix to the transformation composed of the given position,
  9350. * rotation (Quaternion) and scale.
  9351. *
  9352. * @param {Vector3} position - The position vector.
  9353. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9354. * @param {Vector3} scale - The scale vector.
  9355. * @return {Matrix4} A reference to this matrix.
  9356. */
  9357. compose( position, quaternion, scale ) {
  9358. const te = this.elements;
  9359. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9360. const x2 = x + x, y2 = y + y, z2 = z + z;
  9361. const xx = x * x2, xy = x * y2, xz = x * z2;
  9362. const yy = y * y2, yz = y * z2, zz = z * z2;
  9363. const wx = w * x2, wy = w * y2, wz = w * z2;
  9364. const sx = scale.x, sy = scale.y, sz = scale.z;
  9365. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9366. te[ 1 ] = ( xy + wz ) * sx;
  9367. te[ 2 ] = ( xz - wy ) * sx;
  9368. te[ 3 ] = 0;
  9369. te[ 4 ] = ( xy - wz ) * sy;
  9370. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9371. te[ 6 ] = ( yz + wx ) * sy;
  9372. te[ 7 ] = 0;
  9373. te[ 8 ] = ( xz + wy ) * sz;
  9374. te[ 9 ] = ( yz - wx ) * sz;
  9375. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9376. te[ 11 ] = 0;
  9377. te[ 12 ] = position.x;
  9378. te[ 13 ] = position.y;
  9379. te[ 14 ] = position.z;
  9380. te[ 15 ] = 1;
  9381. return this;
  9382. }
  9383. /**
  9384. * Decomposes this matrix into its position, rotation and scale components
  9385. * and provides the result in the given objects.
  9386. *
  9387. * Note: Not all matrices are decomposable in this way. For example, if an
  9388. * object has a non-uniformly scaled parent, then the object's world matrix
  9389. * may not be decomposable, and this method may not be appropriate.
  9390. *
  9391. * @param {Vector3} position - The position vector.
  9392. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9393. * @param {Vector3} scale - The scale vector.
  9394. * @return {Matrix4} A reference to this matrix.
  9395. */
  9396. decompose( position, quaternion, scale ) {
  9397. const te = this.elements;
  9398. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9399. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9400. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9401. // if determine is negative, we need to invert one scale
  9402. const det = this.determinant();
  9403. if ( det < 0 ) sx = - sx;
  9404. position.x = te[ 12 ];
  9405. position.y = te[ 13 ];
  9406. position.z = te[ 14 ];
  9407. // scale the rotation part
  9408. _m1$2.copy( this );
  9409. const invSX = 1 / sx;
  9410. const invSY = 1 / sy;
  9411. const invSZ = 1 / sz;
  9412. _m1$2.elements[ 0 ] *= invSX;
  9413. _m1$2.elements[ 1 ] *= invSX;
  9414. _m1$2.elements[ 2 ] *= invSX;
  9415. _m1$2.elements[ 4 ] *= invSY;
  9416. _m1$2.elements[ 5 ] *= invSY;
  9417. _m1$2.elements[ 6 ] *= invSY;
  9418. _m1$2.elements[ 8 ] *= invSZ;
  9419. _m1$2.elements[ 9 ] *= invSZ;
  9420. _m1$2.elements[ 10 ] *= invSZ;
  9421. quaternion.setFromRotationMatrix( _m1$2 );
  9422. scale.x = sx;
  9423. scale.y = sy;
  9424. scale.z = sz;
  9425. return this;
  9426. }
  9427. /**
  9428. * Creates a perspective projection matrix. This is used internally by
  9429. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9430. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9431. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9432. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9433. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9434. * @param {number} near - The distance from the camera to the near plane.
  9435. * @param {number} far - The distance from the camera to the far plane.
  9436. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9437. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9438. * @return {Matrix4} A reference to this matrix.
  9439. */
  9440. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9441. const te = this.elements;
  9442. const x = 2 * near / ( right - left );
  9443. const y = 2 * near / ( top - bottom );
  9444. const a = ( right + left ) / ( right - left );
  9445. const b = ( top + bottom ) / ( top - bottom );
  9446. let c, d;
  9447. if ( reversedDepth ) {
  9448. c = near / ( far - near );
  9449. d = ( far * near ) / ( far - near );
  9450. } else {
  9451. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9452. c = - ( far + near ) / ( far - near );
  9453. d = ( -2 * far * near ) / ( far - near );
  9454. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9455. c = - far / ( far - near );
  9456. d = ( - far * near ) / ( far - near );
  9457. } else {
  9458. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9459. }
  9460. }
  9461. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9462. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9463. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9464. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9465. return this;
  9466. }
  9467. /**
  9468. * Creates a orthographic projection matrix. This is used internally by
  9469. * {@link OrthographicCamera#updateProjectionMatrix}.
  9470. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9471. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9472. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9473. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9474. * @param {number} near - The distance from the camera to the near plane.
  9475. * @param {number} far - The distance from the camera to the far plane.
  9476. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9477. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9478. * @return {Matrix4} A reference to this matrix.
  9479. */
  9480. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9481. const te = this.elements;
  9482. const x = 2 / ( right - left );
  9483. const y = 2 / ( top - bottom );
  9484. const a = - ( right + left ) / ( right - left );
  9485. const b = - ( top + bottom ) / ( top - bottom );
  9486. let c, d;
  9487. if ( reversedDepth ) {
  9488. c = 1 / ( far - near );
  9489. d = far / ( far - near );
  9490. } else {
  9491. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9492. c = -2 / ( far - near );
  9493. d = - ( far + near ) / ( far - near );
  9494. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9495. c = -1 / ( far - near );
  9496. d = - near / ( far - near );
  9497. } else {
  9498. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9499. }
  9500. }
  9501. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9502. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9503. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9504. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9505. return this;
  9506. }
  9507. /**
  9508. * Returns `true` if this matrix is equal with the given one.
  9509. *
  9510. * @param {Matrix4} matrix - The matrix to test for equality.
  9511. * @return {boolean} Whether this matrix is equal with the given one.
  9512. */
  9513. equals( matrix ) {
  9514. const te = this.elements;
  9515. const me = matrix.elements;
  9516. for ( let i = 0; i < 16; i ++ ) {
  9517. if ( te[ i ] !== me[ i ] ) return false;
  9518. }
  9519. return true;
  9520. }
  9521. /**
  9522. * Sets the elements of the matrix from the given array.
  9523. *
  9524. * @param {Array<number>} array - The matrix elements in column-major order.
  9525. * @param {number} [offset=0] - Index of the first element in the array.
  9526. * @return {Matrix4} A reference to this matrix.
  9527. */
  9528. fromArray( array, offset = 0 ) {
  9529. for ( let i = 0; i < 16; i ++ ) {
  9530. this.elements[ i ] = array[ i + offset ];
  9531. }
  9532. return this;
  9533. }
  9534. /**
  9535. * Writes the elements of this matrix to the given array. If no array is provided,
  9536. * the method returns a new instance.
  9537. *
  9538. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9539. * @param {number} [offset=0] - Index of the first element in the array.
  9540. * @return {Array<number>} The matrix elements in column-major order.
  9541. */
  9542. toArray( array = [], offset = 0 ) {
  9543. const te = this.elements;
  9544. array[ offset ] = te[ 0 ];
  9545. array[ offset + 1 ] = te[ 1 ];
  9546. array[ offset + 2 ] = te[ 2 ];
  9547. array[ offset + 3 ] = te[ 3 ];
  9548. array[ offset + 4 ] = te[ 4 ];
  9549. array[ offset + 5 ] = te[ 5 ];
  9550. array[ offset + 6 ] = te[ 6 ];
  9551. array[ offset + 7 ] = te[ 7 ];
  9552. array[ offset + 8 ] = te[ 8 ];
  9553. array[ offset + 9 ] = te[ 9 ];
  9554. array[ offset + 10 ] = te[ 10 ];
  9555. array[ offset + 11 ] = te[ 11 ];
  9556. array[ offset + 12 ] = te[ 12 ];
  9557. array[ offset + 13 ] = te[ 13 ];
  9558. array[ offset + 14 ] = te[ 14 ];
  9559. array[ offset + 15 ] = te[ 15 ];
  9560. return array;
  9561. }
  9562. }
  9563. const _v1$5 = /*@__PURE__*/ new Vector3();
  9564. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9565. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9566. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9567. const _x = /*@__PURE__*/ new Vector3();
  9568. const _y = /*@__PURE__*/ new Vector3();
  9569. const _z = /*@__PURE__*/ new Vector3();
  9570. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9571. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9572. /**
  9573. * A class representing Euler angles.
  9574. *
  9575. * Euler angles describe a rotational transformation by rotating an object on
  9576. * its various axes in specified amounts per axis, and a specified axis
  9577. * order.
  9578. *
  9579. * Iterating through an instance will yield its components (x, y, z,
  9580. * order) in the corresponding order.
  9581. *
  9582. * ```js
  9583. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9584. * const b = new THREE.Vector3( 1, 0, 1 );
  9585. * b.applyEuler(a);
  9586. * ```
  9587. */
  9588. class Euler {
  9589. /**
  9590. * Constructs a new euler instance.
  9591. *
  9592. * @param {number} [x=0] - The angle of the x axis in radians.
  9593. * @param {number} [y=0] - The angle of the y axis in radians.
  9594. * @param {number} [z=0] - The angle of the z axis in radians.
  9595. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9596. */
  9597. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9598. /**
  9599. * This flag can be used for type testing.
  9600. *
  9601. * @type {boolean}
  9602. * @readonly
  9603. * @default true
  9604. */
  9605. this.isEuler = true;
  9606. this._x = x;
  9607. this._y = y;
  9608. this._z = z;
  9609. this._order = order;
  9610. }
  9611. /**
  9612. * The angle of the x axis in radians.
  9613. *
  9614. * @type {number}
  9615. * @default 0
  9616. */
  9617. get x() {
  9618. return this._x;
  9619. }
  9620. set x( value ) {
  9621. this._x = value;
  9622. this._onChangeCallback();
  9623. }
  9624. /**
  9625. * The angle of the y axis in radians.
  9626. *
  9627. * @type {number}
  9628. * @default 0
  9629. */
  9630. get y() {
  9631. return this._y;
  9632. }
  9633. set y( value ) {
  9634. this._y = value;
  9635. this._onChangeCallback();
  9636. }
  9637. /**
  9638. * The angle of the z axis in radians.
  9639. *
  9640. * @type {number}
  9641. * @default 0
  9642. */
  9643. get z() {
  9644. return this._z;
  9645. }
  9646. set z( value ) {
  9647. this._z = value;
  9648. this._onChangeCallback();
  9649. }
  9650. /**
  9651. * A string representing the order that the rotations are applied.
  9652. *
  9653. * @type {string}
  9654. * @default 'XYZ'
  9655. */
  9656. get order() {
  9657. return this._order;
  9658. }
  9659. set order( value ) {
  9660. this._order = value;
  9661. this._onChangeCallback();
  9662. }
  9663. /**
  9664. * Sets the Euler components.
  9665. *
  9666. * @param {number} x - The angle of the x axis in radians.
  9667. * @param {number} y - The angle of the y axis in radians.
  9668. * @param {number} z - The angle of the z axis in radians.
  9669. * @param {string} [order] - A string representing the order that the rotations are applied.
  9670. * @return {Euler} A reference to this Euler instance.
  9671. */
  9672. set( x, y, z, order = this._order ) {
  9673. this._x = x;
  9674. this._y = y;
  9675. this._z = z;
  9676. this._order = order;
  9677. this._onChangeCallback();
  9678. return this;
  9679. }
  9680. /**
  9681. * Returns a new Euler instance with copied values from this instance.
  9682. *
  9683. * @return {Euler} A clone of this instance.
  9684. */
  9685. clone() {
  9686. return new this.constructor( this._x, this._y, this._z, this._order );
  9687. }
  9688. /**
  9689. * Copies the values of the given Euler instance to this instance.
  9690. *
  9691. * @param {Euler} euler - The Euler instance to copy.
  9692. * @return {Euler} A reference to this Euler instance.
  9693. */
  9694. copy( euler ) {
  9695. this._x = euler._x;
  9696. this._y = euler._y;
  9697. this._z = euler._z;
  9698. this._order = euler._order;
  9699. this._onChangeCallback();
  9700. return this;
  9701. }
  9702. /**
  9703. * Sets the angles of this Euler instance from a pure rotation matrix.
  9704. *
  9705. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9706. * @param {string} [order] - A string representing the order that the rotations are applied.
  9707. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9708. * @return {Euler} A reference to this Euler instance.
  9709. */
  9710. setFromRotationMatrix( m, order = this._order, update = true ) {
  9711. const te = m.elements;
  9712. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9713. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9714. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9715. switch ( order ) {
  9716. case 'XYZ':
  9717. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9718. if ( Math.abs( m13 ) < 0.9999999 ) {
  9719. this._x = Math.atan2( - m23, m33 );
  9720. this._z = Math.atan2( - m12, m11 );
  9721. } else {
  9722. this._x = Math.atan2( m32, m22 );
  9723. this._z = 0;
  9724. }
  9725. break;
  9726. case 'YXZ':
  9727. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9728. if ( Math.abs( m23 ) < 0.9999999 ) {
  9729. this._y = Math.atan2( m13, m33 );
  9730. this._z = Math.atan2( m21, m22 );
  9731. } else {
  9732. this._y = Math.atan2( - m31, m11 );
  9733. this._z = 0;
  9734. }
  9735. break;
  9736. case 'ZXY':
  9737. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9738. if ( Math.abs( m32 ) < 0.9999999 ) {
  9739. this._y = Math.atan2( - m31, m33 );
  9740. this._z = Math.atan2( - m12, m22 );
  9741. } else {
  9742. this._y = 0;
  9743. this._z = Math.atan2( m21, m11 );
  9744. }
  9745. break;
  9746. case 'ZYX':
  9747. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9748. if ( Math.abs( m31 ) < 0.9999999 ) {
  9749. this._x = Math.atan2( m32, m33 );
  9750. this._z = Math.atan2( m21, m11 );
  9751. } else {
  9752. this._x = 0;
  9753. this._z = Math.atan2( - m12, m22 );
  9754. }
  9755. break;
  9756. case 'YZX':
  9757. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9758. if ( Math.abs( m21 ) < 0.9999999 ) {
  9759. this._x = Math.atan2( - m23, m22 );
  9760. this._y = Math.atan2( - m31, m11 );
  9761. } else {
  9762. this._x = 0;
  9763. this._y = Math.atan2( m13, m33 );
  9764. }
  9765. break;
  9766. case 'XZY':
  9767. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9768. if ( Math.abs( m12 ) < 0.9999999 ) {
  9769. this._x = Math.atan2( m32, m22 );
  9770. this._y = Math.atan2( m13, m11 );
  9771. } else {
  9772. this._x = Math.atan2( - m23, m33 );
  9773. this._y = 0;
  9774. }
  9775. break;
  9776. default:
  9777. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9778. }
  9779. this._order = order;
  9780. if ( update === true ) this._onChangeCallback();
  9781. return this;
  9782. }
  9783. /**
  9784. * Sets the angles of this Euler instance from a normalized quaternion.
  9785. *
  9786. * @param {Quaternion} q - A normalized Quaternion.
  9787. * @param {string} [order] - A string representing the order that the rotations are applied.
  9788. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9789. * @return {Euler} A reference to this Euler instance.
  9790. */
  9791. setFromQuaternion( q, order, update ) {
  9792. _matrix$2.makeRotationFromQuaternion( q );
  9793. return this.setFromRotationMatrix( _matrix$2, order, update );
  9794. }
  9795. /**
  9796. * Sets the angles of this Euler instance from the given vector.
  9797. *
  9798. * @param {Vector3} v - The vector.
  9799. * @param {string} [order] - A string representing the order that the rotations are applied.
  9800. * @return {Euler} A reference to this Euler instance.
  9801. */
  9802. setFromVector3( v, order = this._order ) {
  9803. return this.set( v.x, v.y, v.z, order );
  9804. }
  9805. /**
  9806. * Resets the euler angle with a new order by creating a quaternion from this
  9807. * euler angle and then setting this euler angle with the quaternion and the
  9808. * new order.
  9809. *
  9810. * Warning: This discards revolution information.
  9811. *
  9812. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9813. * @return {Euler} A reference to this Euler instance.
  9814. */
  9815. reorder( newOrder ) {
  9816. _quaternion$3.setFromEuler( this );
  9817. return this.setFromQuaternion( _quaternion$3, newOrder );
  9818. }
  9819. /**
  9820. * Returns `true` if this Euler instance is equal with the given one.
  9821. *
  9822. * @param {Euler} euler - The Euler instance to test for equality.
  9823. * @return {boolean} Whether this Euler instance is equal with the given one.
  9824. */
  9825. equals( euler ) {
  9826. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9827. }
  9828. /**
  9829. * Sets this Euler instance's components to values from the given array. The first three
  9830. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9831. * defines the Euler order.
  9832. *
  9833. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9834. * @return {Euler} A reference to this Euler instance.
  9835. */
  9836. fromArray( array ) {
  9837. this._x = array[ 0 ];
  9838. this._y = array[ 1 ];
  9839. this._z = array[ 2 ];
  9840. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9841. this._onChangeCallback();
  9842. return this;
  9843. }
  9844. /**
  9845. * Writes the components of this Euler instance to the given array. If no array is provided,
  9846. * the method returns a new instance.
  9847. *
  9848. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9849. * @param {number} [offset=0] - Index of the first element in the array.
  9850. * @return {Array<number,number,number,string>} The Euler components.
  9851. */
  9852. toArray( array = [], offset = 0 ) {
  9853. array[ offset ] = this._x;
  9854. array[ offset + 1 ] = this._y;
  9855. array[ offset + 2 ] = this._z;
  9856. array[ offset + 3 ] = this._order;
  9857. return array;
  9858. }
  9859. _onChange( callback ) {
  9860. this._onChangeCallback = callback;
  9861. return this;
  9862. }
  9863. _onChangeCallback() {}
  9864. *[ Symbol.iterator ]() {
  9865. yield this._x;
  9866. yield this._y;
  9867. yield this._z;
  9868. yield this._order;
  9869. }
  9870. }
  9871. /**
  9872. * The default Euler angle order.
  9873. *
  9874. * @static
  9875. * @type {string}
  9876. * @default 'XYZ'
  9877. */
  9878. Euler.DEFAULT_ORDER = 'XYZ';
  9879. /**
  9880. * A layers object assigns an 3D object to 1 or more of 32
  9881. * layers numbered `0` to `31` - internally the layers are stored as a
  9882. * bit mask], and by default all 3D objects are a member of layer `0`.
  9883. *
  9884. * This can be used to control visibility - an object must share a layer with
  9885. * a camera to be visible when that camera's view is
  9886. * rendered.
  9887. *
  9888. * All classes that inherit from {@link Object3D} have an `layers` property which
  9889. * is an instance of this class.
  9890. */
  9891. class Layers {
  9892. /**
  9893. * Constructs a new layers instance, with membership
  9894. * initially set to layer `0`.
  9895. */
  9896. constructor() {
  9897. /**
  9898. * A bit mask storing which of the 32 layers this layers object is currently
  9899. * a member of.
  9900. *
  9901. * @type {number}
  9902. */
  9903. this.mask = 1 | 0;
  9904. }
  9905. /**
  9906. * Sets membership to the given layer, and remove membership all other layers.
  9907. *
  9908. * @param {number} layer - The layer to set.
  9909. */
  9910. set( layer ) {
  9911. this.mask = ( 1 << layer | 0 ) >>> 0;
  9912. }
  9913. /**
  9914. * Adds membership of the given layer.
  9915. *
  9916. * @param {number} layer - The layer to enable.
  9917. */
  9918. enable( layer ) {
  9919. this.mask |= 1 << layer | 0;
  9920. }
  9921. /**
  9922. * Adds membership to all layers.
  9923. */
  9924. enableAll() {
  9925. this.mask = 0xffffffff | 0;
  9926. }
  9927. /**
  9928. * Toggles the membership of the given layer.
  9929. *
  9930. * @param {number} layer - The layer to toggle.
  9931. */
  9932. toggle( layer ) {
  9933. this.mask ^= 1 << layer | 0;
  9934. }
  9935. /**
  9936. * Removes membership of the given layer.
  9937. *
  9938. * @param {number} layer - The layer to enable.
  9939. */
  9940. disable( layer ) {
  9941. this.mask &= ~ ( 1 << layer | 0 );
  9942. }
  9943. /**
  9944. * Removes the membership from all layers.
  9945. */
  9946. disableAll() {
  9947. this.mask = 0;
  9948. }
  9949. /**
  9950. * Returns `true` if this and the given layers object have at least one
  9951. * layer in common.
  9952. *
  9953. * @param {Layers} layers - The layers to test.
  9954. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9955. */
  9956. test( layers ) {
  9957. return ( this.mask & layers.mask ) !== 0;
  9958. }
  9959. /**
  9960. * Returns `true` if the given layer is enabled.
  9961. *
  9962. * @param {number} layer - The layer to test.
  9963. * @return {boolean } Whether the given layer is enabled or not.
  9964. */
  9965. isEnabled( layer ) {
  9966. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9967. }
  9968. }
  9969. let _object3DId = 0;
  9970. const _v1$4 = /*@__PURE__*/ new Vector3();
  9971. const _q1 = /*@__PURE__*/ new Quaternion();
  9972. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9973. const _target = /*@__PURE__*/ new Vector3();
  9974. const _position$3 = /*@__PURE__*/ new Vector3();
  9975. const _scale$2 = /*@__PURE__*/ new Vector3();
  9976. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9977. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9978. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9979. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9980. /**
  9981. * Fires when the object has been added to its parent object.
  9982. *
  9983. * @event Object3D#added
  9984. * @type {Object}
  9985. */
  9986. const _addedEvent = { type: 'added' };
  9987. /**
  9988. * Fires when the object has been removed from its parent object.
  9989. *
  9990. * @event Object3D#removed
  9991. * @type {Object}
  9992. */
  9993. const _removedEvent = { type: 'removed' };
  9994. /**
  9995. * Fires when a new child object has been added.
  9996. *
  9997. * @event Object3D#childadded
  9998. * @type {Object}
  9999. */
  10000. const _childaddedEvent = { type: 'childadded', child: null };
  10001. /**
  10002. * Fires when a child object has been removed.
  10003. *
  10004. * @event Object3D#childremoved
  10005. * @type {Object}
  10006. */
  10007. const _childremovedEvent = { type: 'childremoved', child: null };
  10008. /**
  10009. * This is the base class for most objects in three.js and provides a set of
  10010. * properties and methods for manipulating objects in 3D space.
  10011. *
  10012. * @augments EventDispatcher
  10013. */
  10014. class Object3D extends EventDispatcher {
  10015. /**
  10016. * Constructs a new 3D object.
  10017. */
  10018. constructor() {
  10019. super();
  10020. /**
  10021. * This flag can be used for type testing.
  10022. *
  10023. * @type {boolean}
  10024. * @readonly
  10025. * @default true
  10026. */
  10027. this.isObject3D = true;
  10028. /**
  10029. * The ID of the 3D object.
  10030. *
  10031. * @name Object3D#id
  10032. * @type {number}
  10033. * @readonly
  10034. */
  10035. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10036. /**
  10037. * The UUID of the 3D object.
  10038. *
  10039. * @type {string}
  10040. * @readonly
  10041. */
  10042. this.uuid = generateUUID();
  10043. /**
  10044. * The name of the 3D object.
  10045. *
  10046. * @type {string}
  10047. */
  10048. this.name = '';
  10049. /**
  10050. * The type property is used for detecting the object type
  10051. * in context of serialization/deserialization.
  10052. *
  10053. * @type {string}
  10054. * @readonly
  10055. */
  10056. this.type = 'Object3D';
  10057. /**
  10058. * A reference to the parent object.
  10059. *
  10060. * @type {?Object3D}
  10061. * @default null
  10062. */
  10063. this.parent = null;
  10064. /**
  10065. * An array holding the child 3D objects of this instance.
  10066. *
  10067. * @type {Array<Object3D>}
  10068. */
  10069. this.children = [];
  10070. /**
  10071. * Defines the `up` direction of the 3D object which influences
  10072. * the orientation via methods like {@link Object3D#lookAt}.
  10073. *
  10074. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10075. *
  10076. * @type {Vector3}
  10077. */
  10078. this.up = Object3D.DEFAULT_UP.clone();
  10079. const position = new Vector3();
  10080. const rotation = new Euler();
  10081. const quaternion = new Quaternion();
  10082. const scale = new Vector3( 1, 1, 1 );
  10083. function onRotationChange() {
  10084. quaternion.setFromEuler( rotation, false );
  10085. }
  10086. function onQuaternionChange() {
  10087. rotation.setFromQuaternion( quaternion, undefined, false );
  10088. }
  10089. rotation._onChange( onRotationChange );
  10090. quaternion._onChange( onQuaternionChange );
  10091. Object.defineProperties( this, {
  10092. /**
  10093. * Represents the object's local position.
  10094. *
  10095. * @name Object3D#position
  10096. * @type {Vector3}
  10097. * @default (0,0,0)
  10098. */
  10099. position: {
  10100. configurable: true,
  10101. enumerable: true,
  10102. value: position
  10103. },
  10104. /**
  10105. * Represents the object's local rotation as Euler angles, in radians.
  10106. *
  10107. * @name Object3D#rotation
  10108. * @type {Euler}
  10109. * @default (0,0,0)
  10110. */
  10111. rotation: {
  10112. configurable: true,
  10113. enumerable: true,
  10114. value: rotation
  10115. },
  10116. /**
  10117. * Represents the object's local rotation as Quaternions.
  10118. *
  10119. * @name Object3D#quaternion
  10120. * @type {Quaternion}
  10121. */
  10122. quaternion: {
  10123. configurable: true,
  10124. enumerable: true,
  10125. value: quaternion
  10126. },
  10127. /**
  10128. * Represents the object's local scale.
  10129. *
  10130. * @name Object3D#scale
  10131. * @type {Vector3}
  10132. * @default (1,1,1)
  10133. */
  10134. scale: {
  10135. configurable: true,
  10136. enumerable: true,
  10137. value: scale
  10138. },
  10139. /**
  10140. * Represents the object's model-view matrix.
  10141. *
  10142. * @name Object3D#modelViewMatrix
  10143. * @type {Matrix4}
  10144. */
  10145. modelViewMatrix: {
  10146. value: new Matrix4()
  10147. },
  10148. /**
  10149. * Represents the object's normal matrix.
  10150. *
  10151. * @name Object3D#normalMatrix
  10152. * @type {Matrix3}
  10153. */
  10154. normalMatrix: {
  10155. value: new Matrix3()
  10156. }
  10157. } );
  10158. /**
  10159. * Represents the object's transformation matrix in local space.
  10160. *
  10161. * @type {Matrix4}
  10162. */
  10163. this.matrix = new Matrix4();
  10164. /**
  10165. * Represents the object's transformation matrix in world space.
  10166. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10167. *
  10168. * @type {Matrix4}
  10169. */
  10170. this.matrixWorld = new Matrix4();
  10171. /**
  10172. * When set to `true`, the engine automatically computes the local matrix from position,
  10173. * rotation and scale every frame.
  10174. *
  10175. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10176. *
  10177. * @type {boolean}
  10178. * @default true
  10179. */
  10180. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10181. /**
  10182. * When set to `true`, the engine automatically computes the world matrix from the current local
  10183. * matrix and the object's transformation hierarchy.
  10184. *
  10185. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10186. *
  10187. * @type {boolean}
  10188. * @default true
  10189. */
  10190. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10191. /**
  10192. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10193. * to `false`.
  10194. *
  10195. * @type {boolean}
  10196. * @default false
  10197. */
  10198. this.matrixWorldNeedsUpdate = false;
  10199. /**
  10200. * The layer membership of the 3D object. The 3D object is only visible if it has
  10201. * at least one layer in common with the camera in use. This property can also be
  10202. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10203. *
  10204. * @type {Layers}
  10205. */
  10206. this.layers = new Layers();
  10207. /**
  10208. * When set to `true`, the 3D object gets rendered.
  10209. *
  10210. * @type {boolean}
  10211. * @default true
  10212. */
  10213. this.visible = true;
  10214. /**
  10215. * When set to `true`, the 3D object gets rendered into shadow maps.
  10216. *
  10217. * @type {boolean}
  10218. * @default false
  10219. */
  10220. this.castShadow = false;
  10221. /**
  10222. * When set to `true`, the 3D object is affected by shadows in the scene.
  10223. *
  10224. * @type {boolean}
  10225. * @default false
  10226. */
  10227. this.receiveShadow = false;
  10228. /**
  10229. * When set to `true`, the 3D object is honored by view frustum culling.
  10230. *
  10231. * @type {boolean}
  10232. * @default true
  10233. */
  10234. this.frustumCulled = true;
  10235. /**
  10236. * This value allows the default rendering order of scene graph objects to be
  10237. * overridden although opaque and transparent objects remain sorted independently.
  10238. * When this property is set for an instance of {@link Group},all descendants
  10239. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10240. * render order.
  10241. *
  10242. * @type {number}
  10243. * @default 0
  10244. */
  10245. this.renderOrder = 0;
  10246. /**
  10247. * An array holding the animation clips of the 3D object.
  10248. *
  10249. * @type {Array<AnimationClip>}
  10250. */
  10251. this.animations = [];
  10252. /**
  10253. * Custom depth material to be used when rendering to the depth map. Can only be used
  10254. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10255. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10256. * material for proper shadows.
  10257. *
  10258. * Only relevant in context of {@link WebGLRenderer}.
  10259. *
  10260. * @type {(Material|undefined)}
  10261. * @default undefined
  10262. */
  10263. this.customDepthMaterial = undefined;
  10264. /**
  10265. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10266. *
  10267. * Only relevant in context of {@link WebGLRenderer}.
  10268. *
  10269. * @type {(Material|undefined)}
  10270. * @default undefined
  10271. */
  10272. this.customDistanceMaterial = undefined;
  10273. /**
  10274. * An object that can be used to store custom data about the 3D object. It
  10275. * should not hold references to functions as these will not be cloned.
  10276. *
  10277. * @type {Object}
  10278. */
  10279. this.userData = {};
  10280. }
  10281. /**
  10282. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10283. *
  10284. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10285. * @param {Object3D} object - The 3D object.
  10286. * @param {Camera} camera - The camera that is used to render the scene.
  10287. * @param {Camera} shadowCamera - The shadow camera.
  10288. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10289. * @param {Material} depthMaterial - The depth material.
  10290. * @param {Object} group - The geometry group data.
  10291. */
  10292. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10293. /**
  10294. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10295. *
  10296. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10297. * @param {Object3D} object - The 3D object.
  10298. * @param {Camera} camera - The camera that is used to render the scene.
  10299. * @param {Camera} shadowCamera - The shadow camera.
  10300. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10301. * @param {Material} depthMaterial - The depth material.
  10302. * @param {Object} group - The geometry group data.
  10303. */
  10304. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10305. /**
  10306. * A callback that is executed immediately before a 3D object is rendered.
  10307. *
  10308. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10309. * @param {Object3D} object - The 3D object.
  10310. * @param {Camera} camera - The camera that is used to render the scene.
  10311. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10312. * @param {Material} material - The 3D object's material.
  10313. * @param {Object} group - The geometry group data.
  10314. */
  10315. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10316. /**
  10317. * A callback that is executed immediately after a 3D object is rendered.
  10318. *
  10319. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10320. * @param {Object3D} object - The 3D object.
  10321. * @param {Camera} camera - The camera that is used to render the scene.
  10322. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10323. * @param {Material} material - The 3D object's material.
  10324. * @param {Object} group - The geometry group data.
  10325. */
  10326. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10327. /**
  10328. * Applies the given transformation matrix to the object and updates the object's position,
  10329. * rotation and scale.
  10330. *
  10331. * @param {Matrix4} matrix - The transformation matrix.
  10332. */
  10333. applyMatrix4( matrix ) {
  10334. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10335. this.matrix.premultiply( matrix );
  10336. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10337. }
  10338. /**
  10339. * Applies a rotation represented by given the quaternion to the 3D object.
  10340. *
  10341. * @param {Quaternion} q - The quaternion.
  10342. * @return {Object3D} A reference to this instance.
  10343. */
  10344. applyQuaternion( q ) {
  10345. this.quaternion.premultiply( q );
  10346. return this;
  10347. }
  10348. /**
  10349. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10350. *
  10351. * @param {Vector3} axis - The (normalized) axis vector.
  10352. * @param {number} angle - The angle in radians.
  10353. */
  10354. setRotationFromAxisAngle( axis, angle ) {
  10355. // assumes axis is normalized
  10356. this.quaternion.setFromAxisAngle( axis, angle );
  10357. }
  10358. /**
  10359. * Sets the given rotation represented as Euler angles to the 3D object.
  10360. *
  10361. * @param {Euler} euler - The Euler angles.
  10362. */
  10363. setRotationFromEuler( euler ) {
  10364. this.quaternion.setFromEuler( euler, true );
  10365. }
  10366. /**
  10367. * Sets the given rotation represented as rotation matrix to the 3D object.
  10368. *
  10369. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10370. * a pure rotation matrix (i.e, unscaled).
  10371. */
  10372. setRotationFromMatrix( m ) {
  10373. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10374. this.quaternion.setFromRotationMatrix( m );
  10375. }
  10376. /**
  10377. * Sets the given rotation represented as a Quaternion to the 3D object.
  10378. *
  10379. * @param {Quaternion} q - The Quaternion
  10380. */
  10381. setRotationFromQuaternion( q ) {
  10382. // assumes q is normalized
  10383. this.quaternion.copy( q );
  10384. }
  10385. /**
  10386. * Rotates the 3D object along an axis in local space.
  10387. *
  10388. * @param {Vector3} axis - The (normalized) axis vector.
  10389. * @param {number} angle - The angle in radians.
  10390. * @return {Object3D} A reference to this instance.
  10391. */
  10392. rotateOnAxis( axis, angle ) {
  10393. // rotate object on axis in object space
  10394. // axis is assumed to be normalized
  10395. _q1.setFromAxisAngle( axis, angle );
  10396. this.quaternion.multiply( _q1 );
  10397. return this;
  10398. }
  10399. /**
  10400. * Rotates the 3D object along an axis in world space.
  10401. *
  10402. * @param {Vector3} axis - The (normalized) axis vector.
  10403. * @param {number} angle - The angle in radians.
  10404. * @return {Object3D} A reference to this instance.
  10405. */
  10406. rotateOnWorldAxis( axis, angle ) {
  10407. // rotate object on axis in world space
  10408. // axis is assumed to be normalized
  10409. // method assumes no rotated parent
  10410. _q1.setFromAxisAngle( axis, angle );
  10411. this.quaternion.premultiply( _q1 );
  10412. return this;
  10413. }
  10414. /**
  10415. * Rotates the 3D object around its X axis in local space.
  10416. *
  10417. * @param {number} angle - The angle in radians.
  10418. * @return {Object3D} A reference to this instance.
  10419. */
  10420. rotateX( angle ) {
  10421. return this.rotateOnAxis( _xAxis, angle );
  10422. }
  10423. /**
  10424. * Rotates the 3D object around its Y axis in local space.
  10425. *
  10426. * @param {number} angle - The angle in radians.
  10427. * @return {Object3D} A reference to this instance.
  10428. */
  10429. rotateY( angle ) {
  10430. return this.rotateOnAxis( _yAxis, angle );
  10431. }
  10432. /**
  10433. * Rotates the 3D object around its Z axis in local space.
  10434. *
  10435. * @param {number} angle - The angle in radians.
  10436. * @return {Object3D} A reference to this instance.
  10437. */
  10438. rotateZ( angle ) {
  10439. return this.rotateOnAxis( _zAxis, angle );
  10440. }
  10441. /**
  10442. * Translate the 3D object by a distance along the given axis in local space.
  10443. *
  10444. * @param {Vector3} axis - The (normalized) axis vector.
  10445. * @param {number} distance - The distance in world units.
  10446. * @return {Object3D} A reference to this instance.
  10447. */
  10448. translateOnAxis( axis, distance ) {
  10449. // translate object by distance along axis in object space
  10450. // axis is assumed to be normalized
  10451. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10452. this.position.add( _v1$4.multiplyScalar( distance ) );
  10453. return this;
  10454. }
  10455. /**
  10456. * Translate the 3D object by a distance along its X-axis in local space.
  10457. *
  10458. * @param {number} distance - The distance in world units.
  10459. * @return {Object3D} A reference to this instance.
  10460. */
  10461. translateX( distance ) {
  10462. return this.translateOnAxis( _xAxis, distance );
  10463. }
  10464. /**
  10465. * Translate the 3D object by a distance along its Y-axis in local space.
  10466. *
  10467. * @param {number} distance - The distance in world units.
  10468. * @return {Object3D} A reference to this instance.
  10469. */
  10470. translateY( distance ) {
  10471. return this.translateOnAxis( _yAxis, distance );
  10472. }
  10473. /**
  10474. * Translate the 3D object by a distance along its Z-axis in local space.
  10475. *
  10476. * @param {number} distance - The distance in world units.
  10477. * @return {Object3D} A reference to this instance.
  10478. */
  10479. translateZ( distance ) {
  10480. return this.translateOnAxis( _zAxis, distance );
  10481. }
  10482. /**
  10483. * Converts the given vector from this 3D object's local space to world space.
  10484. *
  10485. * @param {Vector3} vector - The vector to convert.
  10486. * @return {Vector3} The converted vector.
  10487. */
  10488. localToWorld( vector ) {
  10489. this.updateWorldMatrix( true, false );
  10490. return vector.applyMatrix4( this.matrixWorld );
  10491. }
  10492. /**
  10493. * Converts the given vector from this 3D object's word space to local space.
  10494. *
  10495. * @param {Vector3} vector - The vector to convert.
  10496. * @return {Vector3} The converted vector.
  10497. */
  10498. worldToLocal( vector ) {
  10499. this.updateWorldMatrix( true, false );
  10500. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10501. }
  10502. /**
  10503. * Rotates the object to face a point in world space.
  10504. *
  10505. * This method does not support objects having non-uniformly-scaled parent(s).
  10506. *
  10507. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10508. * @param {number} [y] - The y coordinate in world space.
  10509. * @param {number} [z] - The z coordinate in world space.
  10510. */
  10511. lookAt( x, y, z ) {
  10512. // This method does not support objects having non-uniformly-scaled parent(s)
  10513. if ( x.isVector3 ) {
  10514. _target.copy( x );
  10515. } else {
  10516. _target.set( x, y, z );
  10517. }
  10518. const parent = this.parent;
  10519. this.updateWorldMatrix( true, false );
  10520. _position$3.setFromMatrixPosition( this.matrixWorld );
  10521. if ( this.isCamera || this.isLight ) {
  10522. _m1$1.lookAt( _position$3, _target, this.up );
  10523. } else {
  10524. _m1$1.lookAt( _target, _position$3, this.up );
  10525. }
  10526. this.quaternion.setFromRotationMatrix( _m1$1 );
  10527. if ( parent ) {
  10528. _m1$1.extractRotation( parent.matrixWorld );
  10529. _q1.setFromRotationMatrix( _m1$1 );
  10530. this.quaternion.premultiply( _q1.invert() );
  10531. }
  10532. }
  10533. /**
  10534. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10535. * objects may be added. Any current parent on an object passed in here will be
  10536. * removed, since an object can have at most one parent.
  10537. *
  10538. * @fires Object3D#added
  10539. * @fires Object3D#childadded
  10540. * @param {Object3D} object - The 3D object to add.
  10541. * @return {Object3D} A reference to this instance.
  10542. */
  10543. add( object ) {
  10544. if ( arguments.length > 1 ) {
  10545. for ( let i = 0; i < arguments.length; i ++ ) {
  10546. this.add( arguments[ i ] );
  10547. }
  10548. return this;
  10549. }
  10550. if ( object === this ) {
  10551. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10552. return this;
  10553. }
  10554. if ( object && object.isObject3D ) {
  10555. object.removeFromParent();
  10556. object.parent = this;
  10557. this.children.push( object );
  10558. object.dispatchEvent( _addedEvent );
  10559. _childaddedEvent.child = object;
  10560. this.dispatchEvent( _childaddedEvent );
  10561. _childaddedEvent.child = null;
  10562. } else {
  10563. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10564. }
  10565. return this;
  10566. }
  10567. /**
  10568. * Removes the given 3D object as child from this 3D object.
  10569. * An arbitrary number of objects may be removed.
  10570. *
  10571. * @fires Object3D#removed
  10572. * @fires Object3D#childremoved
  10573. * @param {Object3D} object - The 3D object to remove.
  10574. * @return {Object3D} A reference to this instance.
  10575. */
  10576. remove( object ) {
  10577. if ( arguments.length > 1 ) {
  10578. for ( let i = 0; i < arguments.length; i ++ ) {
  10579. this.remove( arguments[ i ] );
  10580. }
  10581. return this;
  10582. }
  10583. const index = this.children.indexOf( object );
  10584. if ( index !== -1 ) {
  10585. object.parent = null;
  10586. this.children.splice( index, 1 );
  10587. object.dispatchEvent( _removedEvent );
  10588. _childremovedEvent.child = object;
  10589. this.dispatchEvent( _childremovedEvent );
  10590. _childremovedEvent.child = null;
  10591. }
  10592. return this;
  10593. }
  10594. /**
  10595. * Removes this 3D object from its current parent.
  10596. *
  10597. * @fires Object3D#removed
  10598. * @fires Object3D#childremoved
  10599. * @return {Object3D} A reference to this instance.
  10600. */
  10601. removeFromParent() {
  10602. const parent = this.parent;
  10603. if ( parent !== null ) {
  10604. parent.remove( this );
  10605. }
  10606. return this;
  10607. }
  10608. /**
  10609. * Removes all child objects.
  10610. *
  10611. * @fires Object3D#removed
  10612. * @fires Object3D#childremoved
  10613. * @return {Object3D} A reference to this instance.
  10614. */
  10615. clear() {
  10616. return this.remove( ... this.children );
  10617. }
  10618. /**
  10619. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10620. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10621. *
  10622. * @fires Object3D#added
  10623. * @fires Object3D#childadded
  10624. * @param {Object3D} object - The 3D object to attach.
  10625. * @return {Object3D} A reference to this instance.
  10626. */
  10627. attach( object ) {
  10628. // adds object as a child of this, while maintaining the object's world transform
  10629. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10630. this.updateWorldMatrix( true, false );
  10631. _m1$1.copy( this.matrixWorld ).invert();
  10632. if ( object.parent !== null ) {
  10633. object.parent.updateWorldMatrix( true, false );
  10634. _m1$1.multiply( object.parent.matrixWorld );
  10635. }
  10636. object.applyMatrix4( _m1$1 );
  10637. object.removeFromParent();
  10638. object.parent = this;
  10639. this.children.push( object );
  10640. object.updateWorldMatrix( false, true );
  10641. object.dispatchEvent( _addedEvent );
  10642. _childaddedEvent.child = object;
  10643. this.dispatchEvent( _childaddedEvent );
  10644. _childaddedEvent.child = null;
  10645. return this;
  10646. }
  10647. /**
  10648. * Searches through the 3D object and its children, starting with the 3D object
  10649. * itself, and returns the first with a matching ID.
  10650. *
  10651. * @param {number} id - The id.
  10652. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10653. */
  10654. getObjectById( id ) {
  10655. return this.getObjectByProperty( 'id', id );
  10656. }
  10657. /**
  10658. * Searches through the 3D object and its children, starting with the 3D object
  10659. * itself, and returns the first with a matching name.
  10660. *
  10661. * @param {string} name - The name.
  10662. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10663. */
  10664. getObjectByName( name ) {
  10665. return this.getObjectByProperty( 'name', name );
  10666. }
  10667. /**
  10668. * Searches through the 3D object and its children, starting with the 3D object
  10669. * itself, and returns the first with a matching property value.
  10670. *
  10671. * @param {string} name - The name of the property.
  10672. * @param {any} value - The value.
  10673. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10674. */
  10675. getObjectByProperty( name, value ) {
  10676. if ( this[ name ] === value ) return this;
  10677. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10678. const child = this.children[ i ];
  10679. const object = child.getObjectByProperty( name, value );
  10680. if ( object !== undefined ) {
  10681. return object;
  10682. }
  10683. }
  10684. return undefined;
  10685. }
  10686. /**
  10687. * Searches through the 3D object and its children, starting with the 3D object
  10688. * itself, and returns all 3D objects with a matching property value.
  10689. *
  10690. * @param {string} name - The name of the property.
  10691. * @param {any} value - The value.
  10692. * @param {Array<Object3D>} result - The method stores the result in this array.
  10693. * @return {Array<Object3D>} The found 3D objects.
  10694. */
  10695. getObjectsByProperty( name, value, result = [] ) {
  10696. if ( this[ name ] === value ) result.push( this );
  10697. const children = this.children;
  10698. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10699. children[ i ].getObjectsByProperty( name, value, result );
  10700. }
  10701. return result;
  10702. }
  10703. /**
  10704. * Returns a vector representing the position of the 3D object in world space.
  10705. *
  10706. * @param {Vector3} target - The target vector the result is stored to.
  10707. * @return {Vector3} The 3D object's position in world space.
  10708. */
  10709. getWorldPosition( target ) {
  10710. this.updateWorldMatrix( true, false );
  10711. return target.setFromMatrixPosition( this.matrixWorld );
  10712. }
  10713. /**
  10714. * Returns a Quaternion representing the position of the 3D object in world space.
  10715. *
  10716. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10717. * @return {Quaternion} The 3D object's rotation in world space.
  10718. */
  10719. getWorldQuaternion( target ) {
  10720. this.updateWorldMatrix( true, false );
  10721. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10722. return target;
  10723. }
  10724. /**
  10725. * Returns a vector representing the scale of the 3D object in world space.
  10726. *
  10727. * @param {Vector3} target - The target vector the result is stored to.
  10728. * @return {Vector3} The 3D object's scale in world space.
  10729. */
  10730. getWorldScale( target ) {
  10731. this.updateWorldMatrix( true, false );
  10732. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10733. return target;
  10734. }
  10735. /**
  10736. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10737. *
  10738. * @param {Vector3} target - The target vector the result is stored to.
  10739. * @return {Vector3} The 3D object's direction in world space.
  10740. */
  10741. getWorldDirection( target ) {
  10742. this.updateWorldMatrix( true, false );
  10743. const e = this.matrixWorld.elements;
  10744. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10745. }
  10746. /**
  10747. * Abstract method to get intersections between a casted ray and this
  10748. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10749. * implement this method in order to use raycasting.
  10750. *
  10751. * @abstract
  10752. * @param {Raycaster} raycaster - The raycaster.
  10753. * @param {Array<Object>} intersects - An array holding the result of the method.
  10754. */
  10755. raycast( /* raycaster, intersects */ ) {}
  10756. /**
  10757. * Executes the callback on this 3D object and all descendants.
  10758. *
  10759. * Note: Modifying the scene graph inside the callback is discouraged.
  10760. *
  10761. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10762. */
  10763. traverse( callback ) {
  10764. callback( this );
  10765. const children = this.children;
  10766. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10767. children[ i ].traverse( callback );
  10768. }
  10769. }
  10770. /**
  10771. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10772. * Descendants of invisible 3D objects are not traversed.
  10773. *
  10774. * Note: Modifying the scene graph inside the callback is discouraged.
  10775. *
  10776. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10777. */
  10778. traverseVisible( callback ) {
  10779. if ( this.visible === false ) return;
  10780. callback( this );
  10781. const children = this.children;
  10782. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10783. children[ i ].traverseVisible( callback );
  10784. }
  10785. }
  10786. /**
  10787. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10788. *
  10789. * Note: Modifying the scene graph inside the callback is discouraged.
  10790. *
  10791. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10792. */
  10793. traverseAncestors( callback ) {
  10794. const parent = this.parent;
  10795. if ( parent !== null ) {
  10796. callback( parent );
  10797. parent.traverseAncestors( callback );
  10798. }
  10799. }
  10800. /**
  10801. * Updates the transformation matrix in local space by computing it from the current
  10802. * position, rotation and scale values.
  10803. */
  10804. updateMatrix() {
  10805. this.matrix.compose( this.position, this.quaternion, this.scale );
  10806. this.matrixWorldNeedsUpdate = true;
  10807. }
  10808. /**
  10809. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10810. *
  10811. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10812. * local space. The computation of the local and world matrix can be controlled with the
  10813. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10814. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10815. *
  10816. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10817. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10818. */
  10819. updateMatrixWorld( force ) {
  10820. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10821. if ( this.matrixWorldNeedsUpdate || force ) {
  10822. if ( this.matrixWorldAutoUpdate === true ) {
  10823. if ( this.parent === null ) {
  10824. this.matrixWorld.copy( this.matrix );
  10825. } else {
  10826. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10827. }
  10828. }
  10829. this.matrixWorldNeedsUpdate = false;
  10830. force = true;
  10831. }
  10832. // make sure descendants are updated if required
  10833. const children = this.children;
  10834. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10835. const child = children[ i ];
  10836. child.updateMatrixWorld( force );
  10837. }
  10838. }
  10839. /**
  10840. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10841. * update of ancestor and descendant nodes.
  10842. *
  10843. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10844. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10845. */
  10846. updateWorldMatrix( updateParents, updateChildren ) {
  10847. const parent = this.parent;
  10848. if ( updateParents === true && parent !== null ) {
  10849. parent.updateWorldMatrix( true, false );
  10850. }
  10851. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10852. if ( this.matrixWorldAutoUpdate === true ) {
  10853. if ( this.parent === null ) {
  10854. this.matrixWorld.copy( this.matrix );
  10855. } else {
  10856. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10857. }
  10858. }
  10859. // make sure descendants are updated
  10860. if ( updateChildren === true ) {
  10861. const children = this.children;
  10862. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10863. const child = children[ i ];
  10864. child.updateWorldMatrix( false, true );
  10865. }
  10866. }
  10867. }
  10868. /**
  10869. * Serializes the 3D object into JSON.
  10870. *
  10871. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10872. * @return {Object} A JSON object representing the serialized 3D object.
  10873. * @see {@link ObjectLoader#parse}
  10874. */
  10875. toJSON( meta ) {
  10876. // meta is a string when called from JSON.stringify
  10877. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10878. const output = {};
  10879. // meta is a hash used to collect geometries, materials.
  10880. // not providing it implies that this is the root object
  10881. // being serialized.
  10882. if ( isRootObject ) {
  10883. // initialize meta obj
  10884. meta = {
  10885. geometries: {},
  10886. materials: {},
  10887. textures: {},
  10888. images: {},
  10889. shapes: {},
  10890. skeletons: {},
  10891. animations: {},
  10892. nodes: {}
  10893. };
  10894. output.metadata = {
  10895. version: 4.7,
  10896. type: 'Object',
  10897. generator: 'Object3D.toJSON'
  10898. };
  10899. }
  10900. // standard Object3D serialization
  10901. const object = {};
  10902. object.uuid = this.uuid;
  10903. object.type = this.type;
  10904. if ( this.name !== '' ) object.name = this.name;
  10905. if ( this.castShadow === true ) object.castShadow = true;
  10906. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10907. if ( this.visible === false ) object.visible = false;
  10908. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10909. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10910. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10911. object.layers = this.layers.mask;
  10912. object.matrix = this.matrix.toArray();
  10913. object.up = this.up.toArray();
  10914. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10915. // object specific properties
  10916. if ( this.isInstancedMesh ) {
  10917. object.type = 'InstancedMesh';
  10918. object.count = this.count;
  10919. object.instanceMatrix = this.instanceMatrix.toJSON();
  10920. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10921. }
  10922. if ( this.isBatchedMesh ) {
  10923. object.type = 'BatchedMesh';
  10924. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10925. object.sortObjects = this.sortObjects;
  10926. object.drawRanges = this._drawRanges;
  10927. object.reservedRanges = this._reservedRanges;
  10928. object.geometryInfo = this._geometryInfo.map( info => ( {
  10929. ...info,
  10930. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10931. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10932. } ) );
  10933. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10934. object.availableInstanceIds = this._availableInstanceIds.slice();
  10935. object.availableGeometryIds = this._availableGeometryIds.slice();
  10936. object.nextIndexStart = this._nextIndexStart;
  10937. object.nextVertexStart = this._nextVertexStart;
  10938. object.geometryCount = this._geometryCount;
  10939. object.maxInstanceCount = this._maxInstanceCount;
  10940. object.maxVertexCount = this._maxVertexCount;
  10941. object.maxIndexCount = this._maxIndexCount;
  10942. object.geometryInitialized = this._geometryInitialized;
  10943. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10944. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10945. if ( this._colorsTexture !== null ) {
  10946. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10947. }
  10948. if ( this.boundingSphere !== null ) {
  10949. object.boundingSphere = this.boundingSphere.toJSON();
  10950. }
  10951. if ( this.boundingBox !== null ) {
  10952. object.boundingBox = this.boundingBox.toJSON();
  10953. }
  10954. }
  10955. //
  10956. function serialize( library, element ) {
  10957. if ( library[ element.uuid ] === undefined ) {
  10958. library[ element.uuid ] = element.toJSON( meta );
  10959. }
  10960. return element.uuid;
  10961. }
  10962. if ( this.isScene ) {
  10963. if ( this.background ) {
  10964. if ( this.background.isColor ) {
  10965. object.background = this.background.toJSON();
  10966. } else if ( this.background.isTexture ) {
  10967. object.background = this.background.toJSON( meta ).uuid;
  10968. }
  10969. }
  10970. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10971. object.environment = this.environment.toJSON( meta ).uuid;
  10972. }
  10973. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10974. object.geometry = serialize( meta.geometries, this.geometry );
  10975. const parameters = this.geometry.parameters;
  10976. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10977. const shapes = parameters.shapes;
  10978. if ( Array.isArray( shapes ) ) {
  10979. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10980. const shape = shapes[ i ];
  10981. serialize( meta.shapes, shape );
  10982. }
  10983. } else {
  10984. serialize( meta.shapes, shapes );
  10985. }
  10986. }
  10987. }
  10988. if ( this.isSkinnedMesh ) {
  10989. object.bindMode = this.bindMode;
  10990. object.bindMatrix = this.bindMatrix.toArray();
  10991. if ( this.skeleton !== undefined ) {
  10992. serialize( meta.skeletons, this.skeleton );
  10993. object.skeleton = this.skeleton.uuid;
  10994. }
  10995. }
  10996. if ( this.material !== undefined ) {
  10997. if ( Array.isArray( this.material ) ) {
  10998. const uuids = [];
  10999. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11000. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11001. }
  11002. object.material = uuids;
  11003. } else {
  11004. object.material = serialize( meta.materials, this.material );
  11005. }
  11006. }
  11007. //
  11008. if ( this.children.length > 0 ) {
  11009. object.children = [];
  11010. for ( let i = 0; i < this.children.length; i ++ ) {
  11011. object.children.push( this.children[ i ].toJSON( meta ).object );
  11012. }
  11013. }
  11014. //
  11015. if ( this.animations.length > 0 ) {
  11016. object.animations = [];
  11017. for ( let i = 0; i < this.animations.length; i ++ ) {
  11018. const animation = this.animations[ i ];
  11019. object.animations.push( serialize( meta.animations, animation ) );
  11020. }
  11021. }
  11022. if ( isRootObject ) {
  11023. const geometries = extractFromCache( meta.geometries );
  11024. const materials = extractFromCache( meta.materials );
  11025. const textures = extractFromCache( meta.textures );
  11026. const images = extractFromCache( meta.images );
  11027. const shapes = extractFromCache( meta.shapes );
  11028. const skeletons = extractFromCache( meta.skeletons );
  11029. const animations = extractFromCache( meta.animations );
  11030. const nodes = extractFromCache( meta.nodes );
  11031. if ( geometries.length > 0 ) output.geometries = geometries;
  11032. if ( materials.length > 0 ) output.materials = materials;
  11033. if ( textures.length > 0 ) output.textures = textures;
  11034. if ( images.length > 0 ) output.images = images;
  11035. if ( shapes.length > 0 ) output.shapes = shapes;
  11036. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11037. if ( animations.length > 0 ) output.animations = animations;
  11038. if ( nodes.length > 0 ) output.nodes = nodes;
  11039. }
  11040. output.object = object;
  11041. return output;
  11042. // extract data from the cache hash
  11043. // remove metadata on each item
  11044. // and return as array
  11045. function extractFromCache( cache ) {
  11046. const values = [];
  11047. for ( const key in cache ) {
  11048. const data = cache[ key ];
  11049. delete data.metadata;
  11050. values.push( data );
  11051. }
  11052. return values;
  11053. }
  11054. }
  11055. /**
  11056. * Returns a new 3D object with copied values from this instance.
  11057. *
  11058. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11059. * @return {Object3D} A clone of this instance.
  11060. */
  11061. clone( recursive ) {
  11062. return new this.constructor().copy( this, recursive );
  11063. }
  11064. /**
  11065. * Copies the values of the given 3D object to this instance.
  11066. *
  11067. * @param {Object3D} source - The 3D object to copy.
  11068. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11069. * @return {Object3D} A reference to this instance.
  11070. */
  11071. copy( source, recursive = true ) {
  11072. this.name = source.name;
  11073. this.up.copy( source.up );
  11074. this.position.copy( source.position );
  11075. this.rotation.order = source.rotation.order;
  11076. this.quaternion.copy( source.quaternion );
  11077. this.scale.copy( source.scale );
  11078. this.matrix.copy( source.matrix );
  11079. this.matrixWorld.copy( source.matrixWorld );
  11080. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11081. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11082. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11083. this.layers.mask = source.layers.mask;
  11084. this.visible = source.visible;
  11085. this.castShadow = source.castShadow;
  11086. this.receiveShadow = source.receiveShadow;
  11087. this.frustumCulled = source.frustumCulled;
  11088. this.renderOrder = source.renderOrder;
  11089. this.animations = source.animations.slice();
  11090. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11091. if ( recursive === true ) {
  11092. for ( let i = 0; i < source.children.length; i ++ ) {
  11093. const child = source.children[ i ];
  11094. this.add( child.clone() );
  11095. }
  11096. }
  11097. return this;
  11098. }
  11099. }
  11100. /**
  11101. * The default up direction for objects, also used as the default
  11102. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11103. *
  11104. * @static
  11105. * @type {Vector3}
  11106. * @default (0,1,0)
  11107. */
  11108. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11109. /**
  11110. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11111. * newly created 3D objects.
  11112. *
  11113. * @static
  11114. * @type {boolean}
  11115. * @default true
  11116. */
  11117. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11118. /**
  11119. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11120. * newly created 3D objects.
  11121. *
  11122. * @static
  11123. * @type {boolean}
  11124. * @default true
  11125. */
  11126. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11127. const _v0$1 = /*@__PURE__*/ new Vector3();
  11128. const _v1$3 = /*@__PURE__*/ new Vector3();
  11129. const _v2$2 = /*@__PURE__*/ new Vector3();
  11130. const _v3$2 = /*@__PURE__*/ new Vector3();
  11131. const _vab = /*@__PURE__*/ new Vector3();
  11132. const _vac = /*@__PURE__*/ new Vector3();
  11133. const _vbc = /*@__PURE__*/ new Vector3();
  11134. const _vap = /*@__PURE__*/ new Vector3();
  11135. const _vbp = /*@__PURE__*/ new Vector3();
  11136. const _vcp = /*@__PURE__*/ new Vector3();
  11137. const _v40 = /*@__PURE__*/ new Vector4();
  11138. const _v41 = /*@__PURE__*/ new Vector4();
  11139. const _v42 = /*@__PURE__*/ new Vector4();
  11140. /**
  11141. * A geometric triangle as defined by three vectors representing its three corners.
  11142. */
  11143. class Triangle {
  11144. /**
  11145. * Constructs a new triangle.
  11146. *
  11147. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11148. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11149. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11150. */
  11151. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11152. /**
  11153. * The first corner of the triangle.
  11154. *
  11155. * @type {Vector3}
  11156. */
  11157. this.a = a;
  11158. /**
  11159. * The second corner of the triangle.
  11160. *
  11161. * @type {Vector3}
  11162. */
  11163. this.b = b;
  11164. /**
  11165. * The third corner of the triangle.
  11166. *
  11167. * @type {Vector3}
  11168. */
  11169. this.c = c;
  11170. }
  11171. /**
  11172. * Computes the normal vector of a triangle.
  11173. *
  11174. * @param {Vector3} a - The first corner of the triangle.
  11175. * @param {Vector3} b - The second corner of the triangle.
  11176. * @param {Vector3} c - The third corner of the triangle.
  11177. * @param {Vector3} target - The target vector that is used to store the method's result.
  11178. * @return {Vector3} The triangle's normal.
  11179. */
  11180. static getNormal( a, b, c, target ) {
  11181. target.subVectors( c, b );
  11182. _v0$1.subVectors( a, b );
  11183. target.cross( _v0$1 );
  11184. const targetLengthSq = target.lengthSq();
  11185. if ( targetLengthSq > 0 ) {
  11186. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11187. }
  11188. return target.set( 0, 0, 0 );
  11189. }
  11190. /**
  11191. * Computes a barycentric coordinates from the given vector.
  11192. * Returns `null` if the triangle is degenerate.
  11193. *
  11194. * @param {Vector3} point - A point in 3D space.
  11195. * @param {Vector3} a - The first corner of the triangle.
  11196. * @param {Vector3} b - The second corner of the triangle.
  11197. * @param {Vector3} c - The third corner of the triangle.
  11198. * @param {Vector3} target - The target vector that is used to store the method's result.
  11199. * @return {?Vector3} The barycentric coordinates for the given point
  11200. */
  11201. static getBarycoord( point, a, b, c, target ) {
  11202. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11203. _v0$1.subVectors( c, a );
  11204. _v1$3.subVectors( b, a );
  11205. _v2$2.subVectors( point, a );
  11206. const dot00 = _v0$1.dot( _v0$1 );
  11207. const dot01 = _v0$1.dot( _v1$3 );
  11208. const dot02 = _v0$1.dot( _v2$2 );
  11209. const dot11 = _v1$3.dot( _v1$3 );
  11210. const dot12 = _v1$3.dot( _v2$2 );
  11211. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11212. // collinear or singular triangle
  11213. if ( denom === 0 ) {
  11214. target.set( 0, 0, 0 );
  11215. return null;
  11216. }
  11217. const invDenom = 1 / denom;
  11218. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11219. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11220. // barycentric coordinates must always sum to 1
  11221. return target.set( 1 - u - v, v, u );
  11222. }
  11223. /**
  11224. * Returns `true` if the given point, when projected onto the plane of the
  11225. * triangle, lies within the triangle.
  11226. *
  11227. * @param {Vector3} point - The point in 3D space to test.
  11228. * @param {Vector3} a - The first corner of the triangle.
  11229. * @param {Vector3} b - The second corner of the triangle.
  11230. * @param {Vector3} c - The third corner of the triangle.
  11231. * @return {boolean} Whether the given point, when projected onto the plane of the
  11232. * triangle, lies within the triangle or not.
  11233. */
  11234. static containsPoint( point, a, b, c ) {
  11235. // if the triangle is degenerate then we can't contain a point
  11236. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11237. return false;
  11238. }
  11239. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11240. }
  11241. /**
  11242. * Computes the value barycentrically interpolated for the given point on the
  11243. * triangle. Returns `null` if the triangle is degenerate.
  11244. *
  11245. * @param {Vector3} point - Position of interpolated point.
  11246. * @param {Vector3} p1 - The first corner of the triangle.
  11247. * @param {Vector3} p2 - The second corner of the triangle.
  11248. * @param {Vector3} p3 - The third corner of the triangle.
  11249. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11250. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11251. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11252. * @param {Vector3} target - The target vector that is used to store the method's result.
  11253. * @return {?Vector3} The interpolated value.
  11254. */
  11255. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11256. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11257. target.x = 0;
  11258. target.y = 0;
  11259. if ( 'z' in target ) target.z = 0;
  11260. if ( 'w' in target ) target.w = 0;
  11261. return null;
  11262. }
  11263. target.setScalar( 0 );
  11264. target.addScaledVector( v1, _v3$2.x );
  11265. target.addScaledVector( v2, _v3$2.y );
  11266. target.addScaledVector( v3, _v3$2.z );
  11267. return target;
  11268. }
  11269. /**
  11270. * Computes the value barycentrically interpolated for the given attribute and indices.
  11271. *
  11272. * @param {BufferAttribute} attr - The attribute to interpolate.
  11273. * @param {number} i1 - Index of first vertex.
  11274. * @param {number} i2 - Index of second vertex.
  11275. * @param {number} i3 - Index of third vertex.
  11276. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11277. * @param {Vector3} target - The target vector that is used to store the method's result.
  11278. * @return {Vector3} The interpolated attribute value.
  11279. */
  11280. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11281. _v40.setScalar( 0 );
  11282. _v41.setScalar( 0 );
  11283. _v42.setScalar( 0 );
  11284. _v40.fromBufferAttribute( attr, i1 );
  11285. _v41.fromBufferAttribute( attr, i2 );
  11286. _v42.fromBufferAttribute( attr, i3 );
  11287. target.setScalar( 0 );
  11288. target.addScaledVector( _v40, barycoord.x );
  11289. target.addScaledVector( _v41, barycoord.y );
  11290. target.addScaledVector( _v42, barycoord.z );
  11291. return target;
  11292. }
  11293. /**
  11294. * Returns `true` if the triangle is oriented towards the given direction.
  11295. *
  11296. * @param {Vector3} a - The first corner of the triangle.
  11297. * @param {Vector3} b - The second corner of the triangle.
  11298. * @param {Vector3} c - The third corner of the triangle.
  11299. * @param {Vector3} direction - The (normalized) direction vector.
  11300. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11301. */
  11302. static isFrontFacing( a, b, c, direction ) {
  11303. _v0$1.subVectors( c, b );
  11304. _v1$3.subVectors( a, b );
  11305. // strictly front facing
  11306. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11307. }
  11308. /**
  11309. * Sets the triangle's vertices by copying the given values.
  11310. *
  11311. * @param {Vector3} a - The first corner of the triangle.
  11312. * @param {Vector3} b - The second corner of the triangle.
  11313. * @param {Vector3} c - The third corner of the triangle.
  11314. * @return {Triangle} A reference to this triangle.
  11315. */
  11316. set( a, b, c ) {
  11317. this.a.copy( a );
  11318. this.b.copy( b );
  11319. this.c.copy( c );
  11320. return this;
  11321. }
  11322. /**
  11323. * Sets the triangle's vertices by copying the given array values.
  11324. *
  11325. * @param {Array<Vector3>} points - An array with 3D points.
  11326. * @param {number} i0 - The array index representing the first corner of the triangle.
  11327. * @param {number} i1 - The array index representing the second corner of the triangle.
  11328. * @param {number} i2 - The array index representing the third corner of the triangle.
  11329. * @return {Triangle} A reference to this triangle.
  11330. */
  11331. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11332. this.a.copy( points[ i0 ] );
  11333. this.b.copy( points[ i1 ] );
  11334. this.c.copy( points[ i2 ] );
  11335. return this;
  11336. }
  11337. /**
  11338. * Sets the triangle's vertices by copying the given attribute values.
  11339. *
  11340. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11341. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11342. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11343. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11344. * @return {Triangle} A reference to this triangle.
  11345. */
  11346. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11347. this.a.fromBufferAttribute( attribute, i0 );
  11348. this.b.fromBufferAttribute( attribute, i1 );
  11349. this.c.fromBufferAttribute( attribute, i2 );
  11350. return this;
  11351. }
  11352. /**
  11353. * Returns a new triangle with copied values from this instance.
  11354. *
  11355. * @return {Triangle} A clone of this instance.
  11356. */
  11357. clone() {
  11358. return new this.constructor().copy( this );
  11359. }
  11360. /**
  11361. * Copies the values of the given triangle to this instance.
  11362. *
  11363. * @param {Triangle} triangle - The triangle to copy.
  11364. * @return {Triangle} A reference to this triangle.
  11365. */
  11366. copy( triangle ) {
  11367. this.a.copy( triangle.a );
  11368. this.b.copy( triangle.b );
  11369. this.c.copy( triangle.c );
  11370. return this;
  11371. }
  11372. /**
  11373. * Computes the area of the triangle.
  11374. *
  11375. * @return {number} The triangle's area.
  11376. */
  11377. getArea() {
  11378. _v0$1.subVectors( this.c, this.b );
  11379. _v1$3.subVectors( this.a, this.b );
  11380. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11381. }
  11382. /**
  11383. * Computes the midpoint of the triangle.
  11384. *
  11385. * @param {Vector3} target - The target vector that is used to store the method's result.
  11386. * @return {Vector3} The triangle's midpoint.
  11387. */
  11388. getMidpoint( target ) {
  11389. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11390. }
  11391. /**
  11392. * Computes the normal of the triangle.
  11393. *
  11394. * @param {Vector3} target - The target vector that is used to store the method's result.
  11395. * @return {Vector3} The triangle's normal.
  11396. */
  11397. getNormal( target ) {
  11398. return Triangle.getNormal( this.a, this.b, this.c, target );
  11399. }
  11400. /**
  11401. * Computes a plane the triangle lies within.
  11402. *
  11403. * @param {Plane} target - The target vector that is used to store the method's result.
  11404. * @return {Plane} The plane the triangle lies within.
  11405. */
  11406. getPlane( target ) {
  11407. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11408. }
  11409. /**
  11410. * Computes a barycentric coordinates from the given vector.
  11411. * Returns `null` if the triangle is degenerate.
  11412. *
  11413. * @param {Vector3} point - A point in 3D space.
  11414. * @param {Vector3} target - The target vector that is used to store the method's result.
  11415. * @return {?Vector3} The barycentric coordinates for the given point
  11416. */
  11417. getBarycoord( point, target ) {
  11418. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11419. }
  11420. /**
  11421. * Computes the value barycentrically interpolated for the given point on the
  11422. * triangle. Returns `null` if the triangle is degenerate.
  11423. *
  11424. * @param {Vector3} point - Position of interpolated point.
  11425. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11426. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11427. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11428. * @param {Vector3} target - The target vector that is used to store the method's result.
  11429. * @return {?Vector3} The interpolated value.
  11430. */
  11431. getInterpolation( point, v1, v2, v3, target ) {
  11432. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11433. }
  11434. /**
  11435. * Returns `true` if the given point, when projected onto the plane of the
  11436. * triangle, lies within the triangle.
  11437. *
  11438. * @param {Vector3} point - The point in 3D space to test.
  11439. * @return {boolean} Whether the given point, when projected onto the plane of the
  11440. * triangle, lies within the triangle or not.
  11441. */
  11442. containsPoint( point ) {
  11443. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11444. }
  11445. /**
  11446. * Returns `true` if the triangle is oriented towards the given direction.
  11447. *
  11448. * @param {Vector3} direction - The (normalized) direction vector.
  11449. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11450. */
  11451. isFrontFacing( direction ) {
  11452. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11453. }
  11454. /**
  11455. * Returns `true` if this triangle intersects with the given box.
  11456. *
  11457. * @param {Box3} box - The box to intersect.
  11458. * @return {boolean} Whether this triangle intersects with the given box or not.
  11459. */
  11460. intersectsBox( box ) {
  11461. return box.intersectsTriangle( this );
  11462. }
  11463. /**
  11464. * Returns the closest point on the triangle to the given point.
  11465. *
  11466. * @param {Vector3} p - The point to compute the closest point for.
  11467. * @param {Vector3} target - The target vector that is used to store the method's result.
  11468. * @return {Vector3} The closest point on the triangle.
  11469. */
  11470. closestPointToPoint( p, target ) {
  11471. const a = this.a, b = this.b, c = this.c;
  11472. let v, w;
  11473. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11474. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11475. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11476. // basically, we're distinguishing which of the voronoi regions of the triangle
  11477. // the point lies in with the minimum amount of redundant computation.
  11478. _vab.subVectors( b, a );
  11479. _vac.subVectors( c, a );
  11480. _vap.subVectors( p, a );
  11481. const d1 = _vab.dot( _vap );
  11482. const d2 = _vac.dot( _vap );
  11483. if ( d1 <= 0 && d2 <= 0 ) {
  11484. // vertex region of A; barycentric coords (1, 0, 0)
  11485. return target.copy( a );
  11486. }
  11487. _vbp.subVectors( p, b );
  11488. const d3 = _vab.dot( _vbp );
  11489. const d4 = _vac.dot( _vbp );
  11490. if ( d3 >= 0 && d4 <= d3 ) {
  11491. // vertex region of B; barycentric coords (0, 1, 0)
  11492. return target.copy( b );
  11493. }
  11494. const vc = d1 * d4 - d3 * d2;
  11495. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11496. v = d1 / ( d1 - d3 );
  11497. // edge region of AB; barycentric coords (1-v, v, 0)
  11498. return target.copy( a ).addScaledVector( _vab, v );
  11499. }
  11500. _vcp.subVectors( p, c );
  11501. const d5 = _vab.dot( _vcp );
  11502. const d6 = _vac.dot( _vcp );
  11503. if ( d6 >= 0 && d5 <= d6 ) {
  11504. // vertex region of C; barycentric coords (0, 0, 1)
  11505. return target.copy( c );
  11506. }
  11507. const vb = d5 * d2 - d1 * d6;
  11508. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11509. w = d2 / ( d2 - d6 );
  11510. // edge region of AC; barycentric coords (1-w, 0, w)
  11511. return target.copy( a ).addScaledVector( _vac, w );
  11512. }
  11513. const va = d3 * d6 - d5 * d4;
  11514. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11515. _vbc.subVectors( c, b );
  11516. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11517. // edge region of BC; barycentric coords (0, 1-w, w)
  11518. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11519. }
  11520. // face region
  11521. const denom = 1 / ( va + vb + vc );
  11522. // u = va * denom
  11523. v = vb * denom;
  11524. w = vc * denom;
  11525. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11526. }
  11527. /**
  11528. * Returns `true` if this triangle is equal with the given one.
  11529. *
  11530. * @param {Triangle} triangle - The triangle to test for equality.
  11531. * @return {boolean} Whether this triangle is equal with the given one.
  11532. */
  11533. equals( triangle ) {
  11534. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11535. }
  11536. }
  11537. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11538. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11539. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11540. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11541. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11542. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11543. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11544. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11545. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11546. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11547. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11548. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11549. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11550. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11551. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11552. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11553. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11554. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11555. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11556. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11557. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11558. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11559. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11560. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11561. const _hslA = { h: 0, s: 0, l: 0 };
  11562. const _hslB = { h: 0, s: 0, l: 0 };
  11563. function hue2rgb( p, q, t ) {
  11564. if ( t < 0 ) t += 1;
  11565. if ( t > 1 ) t -= 1;
  11566. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11567. if ( t < 1 / 2 ) return q;
  11568. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11569. return p;
  11570. }
  11571. /**
  11572. * A Color instance is represented by RGB components in the linear <i>working
  11573. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11574. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11575. * strings) are converted to the working color space automatically.
  11576. *
  11577. * ```js
  11578. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11579. * const color = new THREE.Color().setHex( 0x112233 );
  11580. * ```
  11581. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11582. * ```js
  11583. * // assumed already LinearSRGBColorSpace; no conversion
  11584. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11585. *
  11586. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11587. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11588. * ```
  11589. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11590. * see <i>Color management</i>. Iterating through a Color instance will yield
  11591. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11592. * in any of the following ways:
  11593. * ```js
  11594. * //empty constructor - will default white
  11595. * const color1 = new THREE.Color();
  11596. *
  11597. * //Hexadecimal color (recommended)
  11598. * const color2 = new THREE.Color( 0xff0000 );
  11599. *
  11600. * //RGB string
  11601. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11602. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11603. *
  11604. * //X11 color name - all 140 color names are supported.
  11605. * //Note the lack of CamelCase in the name
  11606. * const color5 = new THREE.Color( 'skyblue' );
  11607. * //HSL string
  11608. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11609. *
  11610. * //Separate RGB values between 0 and 1
  11611. * const color7 = new THREE.Color( 1, 0, 0 );
  11612. * ```
  11613. */
  11614. class Color {
  11615. /**
  11616. * Constructs a new color.
  11617. *
  11618. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11619. * and that method is used throughout the rest of the documentation.
  11620. *
  11621. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11622. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11623. * @param {number} [g] - The green component.
  11624. * @param {number} [b] - The blue component.
  11625. */
  11626. constructor( r, g, b ) {
  11627. /**
  11628. * This flag can be used for type testing.
  11629. *
  11630. * @type {boolean}
  11631. * @readonly
  11632. * @default true
  11633. */
  11634. this.isColor = true;
  11635. /**
  11636. * The red component.
  11637. *
  11638. * @type {number}
  11639. * @default 1
  11640. */
  11641. this.r = 1;
  11642. /**
  11643. * The green component.
  11644. *
  11645. * @type {number}
  11646. * @default 1
  11647. */
  11648. this.g = 1;
  11649. /**
  11650. * The blue component.
  11651. *
  11652. * @type {number}
  11653. * @default 1
  11654. */
  11655. this.b = 1;
  11656. return this.set( r, g, b );
  11657. }
  11658. /**
  11659. * Sets the colors's components from the given values.
  11660. *
  11661. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11662. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11663. * @param {number} [g] - The green component.
  11664. * @param {number} [b] - The blue component.
  11665. * @return {Color} A reference to this color.
  11666. */
  11667. set( r, g, b ) {
  11668. if ( g === undefined && b === undefined ) {
  11669. // r is THREE.Color, hex or string
  11670. const value = r;
  11671. if ( value && value.isColor ) {
  11672. this.copy( value );
  11673. } else if ( typeof value === 'number' ) {
  11674. this.setHex( value );
  11675. } else if ( typeof value === 'string' ) {
  11676. this.setStyle( value );
  11677. }
  11678. } else {
  11679. this.setRGB( r, g, b );
  11680. }
  11681. return this;
  11682. }
  11683. /**
  11684. * Sets the colors's components to the given scalar value.
  11685. *
  11686. * @param {number} scalar - The scalar value.
  11687. * @return {Color} A reference to this color.
  11688. */
  11689. setScalar( scalar ) {
  11690. this.r = scalar;
  11691. this.g = scalar;
  11692. this.b = scalar;
  11693. return this;
  11694. }
  11695. /**
  11696. * Sets this color from a hexadecimal value.
  11697. *
  11698. * @param {number} hex - The hexadecimal value.
  11699. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11700. * @return {Color} A reference to this color.
  11701. */
  11702. setHex( hex, colorSpace = SRGBColorSpace ) {
  11703. hex = Math.floor( hex );
  11704. this.r = ( hex >> 16 & 255 ) / 255;
  11705. this.g = ( hex >> 8 & 255 ) / 255;
  11706. this.b = ( hex & 255 ) / 255;
  11707. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11708. return this;
  11709. }
  11710. /**
  11711. * Sets this color from RGB values.
  11712. *
  11713. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11714. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11715. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11716. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11717. * @return {Color} A reference to this color.
  11718. */
  11719. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11720. this.r = r;
  11721. this.g = g;
  11722. this.b = b;
  11723. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11724. return this;
  11725. }
  11726. /**
  11727. * Sets this color from RGB values.
  11728. *
  11729. * @param {number} h - Hue value between `0.0` and `1.0`.
  11730. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11731. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11732. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11733. * @return {Color} A reference to this color.
  11734. */
  11735. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11736. // h,s,l ranges are in 0.0 - 1.0
  11737. h = euclideanModulo( h, 1 );
  11738. s = clamp( s, 0, 1 );
  11739. l = clamp( l, 0, 1 );
  11740. if ( s === 0 ) {
  11741. this.r = this.g = this.b = l;
  11742. } else {
  11743. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11744. const q = ( 2 * l ) - p;
  11745. this.r = hue2rgb( q, p, h + 1 / 3 );
  11746. this.g = hue2rgb( q, p, h );
  11747. this.b = hue2rgb( q, p, h - 1 / 3 );
  11748. }
  11749. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11750. return this;
  11751. }
  11752. /**
  11753. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11754. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11755. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11756. * all 140 color names are supported).
  11757. *
  11758. * @param {string} style - Color as a CSS-style string.
  11759. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11760. * @return {Color} A reference to this color.
  11761. */
  11762. setStyle( style, colorSpace = SRGBColorSpace ) {
  11763. function handleAlpha( string ) {
  11764. if ( string === undefined ) return;
  11765. if ( parseFloat( string ) < 1 ) {
  11766. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11767. }
  11768. }
  11769. let m;
  11770. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11771. // rgb / hsl
  11772. let color;
  11773. const name = m[ 1 ];
  11774. const components = m[ 2 ];
  11775. switch ( name ) {
  11776. case 'rgb':
  11777. case 'rgba':
  11778. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11779. // rgb(255,0,0) rgba(255,0,0,0.5)
  11780. handleAlpha( color[ 4 ] );
  11781. return this.setRGB(
  11782. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11783. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11784. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11785. colorSpace
  11786. );
  11787. }
  11788. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11789. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11790. handleAlpha( color[ 4 ] );
  11791. return this.setRGB(
  11792. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11793. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11794. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11795. colorSpace
  11796. );
  11797. }
  11798. break;
  11799. case 'hsl':
  11800. case 'hsla':
  11801. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11802. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11803. handleAlpha( color[ 4 ] );
  11804. return this.setHSL(
  11805. parseFloat( color[ 1 ] ) / 360,
  11806. parseFloat( color[ 2 ] ) / 100,
  11807. parseFloat( color[ 3 ] ) / 100,
  11808. colorSpace
  11809. );
  11810. }
  11811. break;
  11812. default:
  11813. console.warn( 'THREE.Color: Unknown color model ' + style );
  11814. }
  11815. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11816. // hex color
  11817. const hex = m[ 1 ];
  11818. const size = hex.length;
  11819. if ( size === 3 ) {
  11820. // #ff0
  11821. return this.setRGB(
  11822. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11823. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11824. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11825. colorSpace
  11826. );
  11827. } else if ( size === 6 ) {
  11828. // #ff0000
  11829. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11830. } else {
  11831. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11832. }
  11833. } else if ( style && style.length > 0 ) {
  11834. return this.setColorName( style, colorSpace );
  11835. }
  11836. return this;
  11837. }
  11838. /**
  11839. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11840. * you don't need the other CSS-style formats.
  11841. *
  11842. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11843. * ```js
  11844. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11845. * ```
  11846. *
  11847. * @param {string} style - The color name.
  11848. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11849. * @return {Color} A reference to this color.
  11850. */
  11851. setColorName( style, colorSpace = SRGBColorSpace ) {
  11852. // color keywords
  11853. const hex = _colorKeywords[ style.toLowerCase() ];
  11854. if ( hex !== undefined ) {
  11855. // red
  11856. this.setHex( hex, colorSpace );
  11857. } else {
  11858. // unknown color
  11859. console.warn( 'THREE.Color: Unknown color ' + style );
  11860. }
  11861. return this;
  11862. }
  11863. /**
  11864. * Returns a new color with copied values from this instance.
  11865. *
  11866. * @return {Color} A clone of this instance.
  11867. */
  11868. clone() {
  11869. return new this.constructor( this.r, this.g, this.b );
  11870. }
  11871. /**
  11872. * Copies the values of the given color to this instance.
  11873. *
  11874. * @param {Color} color - The color to copy.
  11875. * @return {Color} A reference to this color.
  11876. */
  11877. copy( color ) {
  11878. this.r = color.r;
  11879. this.g = color.g;
  11880. this.b = color.b;
  11881. return this;
  11882. }
  11883. /**
  11884. * Copies the given color into this color, and then converts this color from
  11885. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11886. *
  11887. * @param {Color} color - The color to copy/convert.
  11888. * @return {Color} A reference to this color.
  11889. */
  11890. copySRGBToLinear( color ) {
  11891. this.r = SRGBToLinear( color.r );
  11892. this.g = SRGBToLinear( color.g );
  11893. this.b = SRGBToLinear( color.b );
  11894. return this;
  11895. }
  11896. /**
  11897. * Copies the given color into this color, and then converts this color from
  11898. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11899. *
  11900. * @param {Color} color - The color to copy/convert.
  11901. * @return {Color} A reference to this color.
  11902. */
  11903. copyLinearToSRGB( color ) {
  11904. this.r = LinearToSRGB( color.r );
  11905. this.g = LinearToSRGB( color.g );
  11906. this.b = LinearToSRGB( color.b );
  11907. return this;
  11908. }
  11909. /**
  11910. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11911. *
  11912. * @return {Color} A reference to this color.
  11913. */
  11914. convertSRGBToLinear() {
  11915. this.copySRGBToLinear( this );
  11916. return this;
  11917. }
  11918. /**
  11919. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11920. *
  11921. * @return {Color} A reference to this color.
  11922. */
  11923. convertLinearToSRGB() {
  11924. this.copyLinearToSRGB( this );
  11925. return this;
  11926. }
  11927. /**
  11928. * Returns the hexadecimal value of this color.
  11929. *
  11930. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11931. * @return {number} The hexadecimal value.
  11932. */
  11933. getHex( colorSpace = SRGBColorSpace ) {
  11934. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11935. 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 ) );
  11936. }
  11937. /**
  11938. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11939. *
  11940. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11941. * @return {string} The hexadecimal value as a string.
  11942. */
  11943. getHexString( colorSpace = SRGBColorSpace ) {
  11944. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11945. }
  11946. /**
  11947. * Converts the colors RGB values into the HSL format and stores them into the
  11948. * given target object.
  11949. *
  11950. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11951. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11952. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11953. */
  11954. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11955. // h,s,l ranges are in 0.0 - 1.0
  11956. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11957. const r = _color.r, g = _color.g, b = _color.b;
  11958. const max = Math.max( r, g, b );
  11959. const min = Math.min( r, g, b );
  11960. let hue, saturation;
  11961. const lightness = ( min + max ) / 2.0;
  11962. if ( min === max ) {
  11963. hue = 0;
  11964. saturation = 0;
  11965. } else {
  11966. const delta = max - min;
  11967. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11968. switch ( max ) {
  11969. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11970. case g: hue = ( b - r ) / delta + 2; break;
  11971. case b: hue = ( r - g ) / delta + 4; break;
  11972. }
  11973. hue /= 6;
  11974. }
  11975. target.h = hue;
  11976. target.s = saturation;
  11977. target.l = lightness;
  11978. return target;
  11979. }
  11980. /**
  11981. * Returns the RGB values of this color and stores them into the given target object.
  11982. *
  11983. * @param {Color} target - The target color that is used to store the method's result.
  11984. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11985. * @return {Color} The RGB representation of this color.
  11986. */
  11987. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11988. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11989. target.r = _color.r;
  11990. target.g = _color.g;
  11991. target.b = _color.b;
  11992. return target;
  11993. }
  11994. /**
  11995. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11996. *
  11997. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11998. * @return {string} The CSS representation of this color.
  11999. */
  12000. getStyle( colorSpace = SRGBColorSpace ) {
  12001. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12002. const r = _color.r, g = _color.g, b = _color.b;
  12003. if ( colorSpace !== SRGBColorSpace ) {
  12004. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12005. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12006. }
  12007. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12008. }
  12009. /**
  12010. * Adds the given HSL values to this color's values.
  12011. * Internally, this converts the color's RGB values to HSL, adds HSL
  12012. * and then converts the color back to RGB.
  12013. *
  12014. * @param {number} h - Hue value between `0.0` and `1.0`.
  12015. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12016. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12017. * @return {Color} A reference to this color.
  12018. */
  12019. offsetHSL( h, s, l ) {
  12020. this.getHSL( _hslA );
  12021. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12022. }
  12023. /**
  12024. * Adds the RGB values of the given color to the RGB values of this color.
  12025. *
  12026. * @param {Color} color - The color to add.
  12027. * @return {Color} A reference to this color.
  12028. */
  12029. add( color ) {
  12030. this.r += color.r;
  12031. this.g += color.g;
  12032. this.b += color.b;
  12033. return this;
  12034. }
  12035. /**
  12036. * Adds the RGB values of the given colors and stores the result in this instance.
  12037. *
  12038. * @param {Color} color1 - The first color.
  12039. * @param {Color} color2 - The second color.
  12040. * @return {Color} A reference to this color.
  12041. */
  12042. addColors( color1, color2 ) {
  12043. this.r = color1.r + color2.r;
  12044. this.g = color1.g + color2.g;
  12045. this.b = color1.b + color2.b;
  12046. return this;
  12047. }
  12048. /**
  12049. * Adds the given scalar value to the RGB values of this color.
  12050. *
  12051. * @param {number} s - The scalar to add.
  12052. * @return {Color} A reference to this color.
  12053. */
  12054. addScalar( s ) {
  12055. this.r += s;
  12056. this.g += s;
  12057. this.b += s;
  12058. return this;
  12059. }
  12060. /**
  12061. * Subtracts the RGB values of the given color from the RGB values of this color.
  12062. *
  12063. * @param {Color} color - The color to subtract.
  12064. * @return {Color} A reference to this color.
  12065. */
  12066. sub( color ) {
  12067. this.r = Math.max( 0, this.r - color.r );
  12068. this.g = Math.max( 0, this.g - color.g );
  12069. this.b = Math.max( 0, this.b - color.b );
  12070. return this;
  12071. }
  12072. /**
  12073. * Multiplies the RGB values of the given color with the RGB values of this color.
  12074. *
  12075. * @param {Color} color - The color to multiply.
  12076. * @return {Color} A reference to this color.
  12077. */
  12078. multiply( color ) {
  12079. this.r *= color.r;
  12080. this.g *= color.g;
  12081. this.b *= color.b;
  12082. return this;
  12083. }
  12084. /**
  12085. * Multiplies the given scalar value with the RGB values of this color.
  12086. *
  12087. * @param {number} s - The scalar to multiply.
  12088. * @return {Color} A reference to this color.
  12089. */
  12090. multiplyScalar( s ) {
  12091. this.r *= s;
  12092. this.g *= s;
  12093. this.b *= s;
  12094. return this;
  12095. }
  12096. /**
  12097. * Linearly interpolates this color's RGB values toward the RGB values of the
  12098. * given color. The alpha argument can be thought of as the ratio between
  12099. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12100. *
  12101. * @param {Color} color - The color to converge on.
  12102. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12103. * @return {Color} A reference to this color.
  12104. */
  12105. lerp( color, alpha ) {
  12106. this.r += ( color.r - this.r ) * alpha;
  12107. this.g += ( color.g - this.g ) * alpha;
  12108. this.b += ( color.b - this.b ) * alpha;
  12109. return this;
  12110. }
  12111. /**
  12112. * Linearly interpolates between the given colors and stores the result in this instance.
  12113. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12114. * is the first and `1.0` is the second color.
  12115. *
  12116. * @param {Color} color1 - The first color.
  12117. * @param {Color} color2 - The second color.
  12118. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12119. * @return {Color} A reference to this color.
  12120. */
  12121. lerpColors( color1, color2, alpha ) {
  12122. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12123. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12124. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12125. return this;
  12126. }
  12127. /**
  12128. * Linearly interpolates this color's HSL values toward the HSL values of the
  12129. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12130. * from one color to the other, but instead going through all the hues in between
  12131. * those two colors. The alpha argument can be thought of as the ratio between
  12132. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12133. *
  12134. * @param {Color} color - The color to converge on.
  12135. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12136. * @return {Color} A reference to this color.
  12137. */
  12138. lerpHSL( color, alpha ) {
  12139. this.getHSL( _hslA );
  12140. color.getHSL( _hslB );
  12141. const h = lerp( _hslA.h, _hslB.h, alpha );
  12142. const s = lerp( _hslA.s, _hslB.s, alpha );
  12143. const l = lerp( _hslA.l, _hslB.l, alpha );
  12144. this.setHSL( h, s, l );
  12145. return this;
  12146. }
  12147. /**
  12148. * Sets the color's RGB components from the given 3D vector.
  12149. *
  12150. * @param {Vector3} v - The vector to set.
  12151. * @return {Color} A reference to this color.
  12152. */
  12153. setFromVector3( v ) {
  12154. this.r = v.x;
  12155. this.g = v.y;
  12156. this.b = v.z;
  12157. return this;
  12158. }
  12159. /**
  12160. * Transforms this color with the given 3x3 matrix.
  12161. *
  12162. * @param {Matrix3} m - The matrix.
  12163. * @return {Color} A reference to this color.
  12164. */
  12165. applyMatrix3( m ) {
  12166. const r = this.r, g = this.g, b = this.b;
  12167. const e = m.elements;
  12168. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12169. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12170. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12171. return this;
  12172. }
  12173. /**
  12174. * Returns `true` if this color is equal with the given one.
  12175. *
  12176. * @param {Color} c - The color to test for equality.
  12177. * @return {boolean} Whether this bounding color is equal with the given one.
  12178. */
  12179. equals( c ) {
  12180. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12181. }
  12182. /**
  12183. * Sets this color's RGB components from the given array.
  12184. *
  12185. * @param {Array<number>} array - An array holding the RGB values.
  12186. * @param {number} [offset=0] - The offset into the array.
  12187. * @return {Color} A reference to this color.
  12188. */
  12189. fromArray( array, offset = 0 ) {
  12190. this.r = array[ offset ];
  12191. this.g = array[ offset + 1 ];
  12192. this.b = array[ offset + 2 ];
  12193. return this;
  12194. }
  12195. /**
  12196. * Writes the RGB components of this color to the given array. If no array is provided,
  12197. * the method returns a new instance.
  12198. *
  12199. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12200. * @param {number} [offset=0] - Index of the first element in the array.
  12201. * @return {Array<number>} The color components.
  12202. */
  12203. toArray( array = [], offset = 0 ) {
  12204. array[ offset ] = this.r;
  12205. array[ offset + 1 ] = this.g;
  12206. array[ offset + 2 ] = this.b;
  12207. return array;
  12208. }
  12209. /**
  12210. * Sets the components of this color from the given buffer attribute.
  12211. *
  12212. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12213. * @param {number} index - The index into the attribute.
  12214. * @return {Color} A reference to this color.
  12215. */
  12216. fromBufferAttribute( attribute, index ) {
  12217. this.r = attribute.getX( index );
  12218. this.g = attribute.getY( index );
  12219. this.b = attribute.getZ( index );
  12220. return this;
  12221. }
  12222. /**
  12223. * This methods defines the serialization result of this class. Returns the color
  12224. * as a hexadecimal value.
  12225. *
  12226. * @return {number} The hexadecimal value.
  12227. */
  12228. toJSON() {
  12229. return this.getHex();
  12230. }
  12231. *[ Symbol.iterator ]() {
  12232. yield this.r;
  12233. yield this.g;
  12234. yield this.b;
  12235. }
  12236. }
  12237. const _color = /*@__PURE__*/ new Color();
  12238. /**
  12239. * A dictionary with X11 color names.
  12240. *
  12241. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12242. *
  12243. * @static
  12244. * @type {Object}
  12245. */
  12246. Color.NAMES = _colorKeywords;
  12247. let _materialId = 0;
  12248. /**
  12249. * Abstract base class for materials.
  12250. *
  12251. * Materials define the appearance of renderable 3D objects.
  12252. *
  12253. * @abstract
  12254. * @augments EventDispatcher
  12255. */
  12256. class Material extends EventDispatcher {
  12257. /**
  12258. * Constructs a new material.
  12259. */
  12260. constructor() {
  12261. super();
  12262. /**
  12263. * This flag can be used for type testing.
  12264. *
  12265. * @type {boolean}
  12266. * @readonly
  12267. * @default true
  12268. */
  12269. this.isMaterial = true;
  12270. /**
  12271. * The ID of the material.
  12272. *
  12273. * @name Material#id
  12274. * @type {number}
  12275. * @readonly
  12276. */
  12277. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12278. /**
  12279. * The UUID of the material.
  12280. *
  12281. * @type {string}
  12282. * @readonly
  12283. */
  12284. this.uuid = generateUUID();
  12285. /**
  12286. * The name of the material.
  12287. *
  12288. * @type {string}
  12289. */
  12290. this.name = '';
  12291. /**
  12292. * The type property is used for detecting the object type
  12293. * in context of serialization/deserialization.
  12294. *
  12295. * @type {string}
  12296. * @readonly
  12297. */
  12298. this.type = 'Material';
  12299. /**
  12300. * Defines the blending type of the material.
  12301. *
  12302. * It must be set to `CustomBlending` if custom blending properties like
  12303. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12304. * should have any effect.
  12305. *
  12306. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12307. * @default NormalBlending
  12308. */
  12309. this.blending = NormalBlending;
  12310. /**
  12311. * Defines which side of faces will be rendered - front, back or both.
  12312. *
  12313. * @type {(FrontSide|BackSide|DoubleSide)}
  12314. * @default FrontSide
  12315. */
  12316. this.side = FrontSide;
  12317. /**
  12318. * If set to `true`, vertex colors should be used.
  12319. *
  12320. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12321. * four (RGBA) component color buffer attribute is used.
  12322. *
  12323. * @type {boolean}
  12324. * @default false
  12325. */
  12326. this.vertexColors = false;
  12327. /**
  12328. * Defines how transparent the material is.
  12329. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12330. *
  12331. * If the {@link Material#transparent} is not set to `true`,
  12332. * the material will remain fully opaque and this value will only affect its color.
  12333. *
  12334. * @type {number}
  12335. * @default 1
  12336. */
  12337. this.opacity = 1;
  12338. /**
  12339. * Defines whether this material is transparent. This has an effect on
  12340. * rendering as transparent objects need special treatment and are rendered
  12341. * after non-transparent objects.
  12342. *
  12343. * When set to true, the extent to which the material is transparent is
  12344. * controlled by {@link Material#opacity}.
  12345. *
  12346. * @type {boolean}
  12347. * @default false
  12348. */
  12349. this.transparent = false;
  12350. /**
  12351. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12352. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12353. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12354. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12355. *
  12356. * @type {boolean}
  12357. * @default false
  12358. */
  12359. this.alphaHash = false;
  12360. /**
  12361. * Defines the blending source factor.
  12362. *
  12363. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12364. * @default SrcAlphaFactor
  12365. */
  12366. this.blendSrc = SrcAlphaFactor;
  12367. /**
  12368. * Defines the blending destination factor.
  12369. *
  12370. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12371. * @default OneMinusSrcAlphaFactor
  12372. */
  12373. this.blendDst = OneMinusSrcAlphaFactor;
  12374. /**
  12375. * Defines the blending equation.
  12376. *
  12377. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12378. * @default AddEquation
  12379. */
  12380. this.blendEquation = AddEquation;
  12381. /**
  12382. * Defines the blending source alpha factor.
  12383. *
  12384. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12385. * @default null
  12386. */
  12387. this.blendSrcAlpha = null;
  12388. /**
  12389. * Defines the blending destination alpha factor.
  12390. *
  12391. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12392. * @default null
  12393. */
  12394. this.blendDstAlpha = null;
  12395. /**
  12396. * Defines the blending equation of the alpha channel.
  12397. *
  12398. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12399. * @default null
  12400. */
  12401. this.blendEquationAlpha = null;
  12402. /**
  12403. * Represents the RGB values of the constant blend color.
  12404. *
  12405. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12406. *
  12407. * @type {Color}
  12408. * @default (0,0,0)
  12409. */
  12410. this.blendColor = new Color( 0, 0, 0 );
  12411. /**
  12412. * Represents the alpha value of the constant blend color.
  12413. *
  12414. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12415. *
  12416. * @type {number}
  12417. * @default 0
  12418. */
  12419. this.blendAlpha = 0;
  12420. /**
  12421. * Defines the depth function.
  12422. *
  12423. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12424. * @default LessEqualDepth
  12425. */
  12426. this.depthFunc = LessEqualDepth;
  12427. /**
  12428. * Whether to have depth test enabled when rendering this material.
  12429. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12430. *
  12431. * @type {boolean}
  12432. * @default true
  12433. */
  12434. this.depthTest = true;
  12435. /**
  12436. * Whether rendering this material has any effect on the depth buffer.
  12437. *
  12438. * When drawing 2D overlays it can be useful to disable the depth writing in
  12439. * order to layer several things together without creating z-index artifacts.
  12440. *
  12441. * @type {boolean}
  12442. * @default true
  12443. */
  12444. this.depthWrite = true;
  12445. /**
  12446. * The bit mask to use when writing to the stencil buffer.
  12447. *
  12448. * @type {number}
  12449. * @default 0xff
  12450. */
  12451. this.stencilWriteMask = 0xff;
  12452. /**
  12453. * The stencil comparison function to use.
  12454. *
  12455. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12456. * @default AlwaysStencilFunc
  12457. */
  12458. this.stencilFunc = AlwaysStencilFunc;
  12459. /**
  12460. * The value to use when performing stencil comparisons or stencil operations.
  12461. *
  12462. * @type {number}
  12463. * @default 0
  12464. */
  12465. this.stencilRef = 0;
  12466. /**
  12467. * The bit mask to use when comparing against the stencil buffer.
  12468. *
  12469. * @type {number}
  12470. * @default 0xff
  12471. */
  12472. this.stencilFuncMask = 0xff;
  12473. /**
  12474. * Which stencil operation to perform when the comparison function returns `false`.
  12475. *
  12476. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12477. * @default KeepStencilOp
  12478. */
  12479. this.stencilFail = KeepStencilOp;
  12480. /**
  12481. * Which stencil operation to perform when the comparison function returns
  12482. * `true` but the depth test fails.
  12483. *
  12484. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12485. * @default KeepStencilOp
  12486. */
  12487. this.stencilZFail = KeepStencilOp;
  12488. /**
  12489. * Which stencil operation to perform when the comparison function returns
  12490. * `true` and the depth test passes.
  12491. *
  12492. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12493. * @default KeepStencilOp
  12494. */
  12495. this.stencilZPass = KeepStencilOp;
  12496. /**
  12497. * Whether stencil operations are performed against the stencil buffer. In
  12498. * order to perform writes or comparisons against the stencil buffer this
  12499. * value must be `true`.
  12500. *
  12501. * @type {boolean}
  12502. * @default false
  12503. */
  12504. this.stencilWrite = false;
  12505. /**
  12506. * User-defined clipping planes specified as THREE.Plane objects in world
  12507. * space. These planes apply to the objects this material is attached to.
  12508. * Points in space whose signed distance to the plane is negative are clipped
  12509. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12510. * be `true`.
  12511. *
  12512. * @type {?Array<Plane>}
  12513. * @default null
  12514. */
  12515. this.clippingPlanes = null;
  12516. /**
  12517. * Changes the behavior of clipping planes so that only their intersection is
  12518. * clipped, rather than their union.
  12519. *
  12520. * @type {boolean}
  12521. * @default false
  12522. */
  12523. this.clipIntersection = false;
  12524. /**
  12525. * Defines whether to clip shadows according to the clipping planes specified
  12526. * on this material.
  12527. *
  12528. * @type {boolean}
  12529. * @default false
  12530. */
  12531. this.clipShadows = false;
  12532. /**
  12533. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12534. * is determined as follows:
  12535. *
  12536. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12537. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12538. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12539. *
  12540. * @type {?(FrontSide|BackSide|DoubleSide)}
  12541. * @default null
  12542. */
  12543. this.shadowSide = null;
  12544. /**
  12545. * Whether to render the material's color.
  12546. *
  12547. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12548. * objects that occlude other objects.
  12549. *
  12550. * @type {boolean}
  12551. * @default true
  12552. */
  12553. this.colorWrite = true;
  12554. /**
  12555. * Override the renderer's default precision for this material.
  12556. *
  12557. * @type {?('highp'|'mediump'|'lowp')}
  12558. * @default null
  12559. */
  12560. this.precision = null;
  12561. /**
  12562. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12563. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12564. * The offset is added before the depth test is performed and before the value is written
  12565. * into the depth buffer.
  12566. *
  12567. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12568. * rendering solids with highlighted edges.
  12569. *
  12570. * @type {boolean}
  12571. * @default false
  12572. */
  12573. this.polygonOffset = false;
  12574. /**
  12575. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12576. *
  12577. * @type {number}
  12578. * @default 0
  12579. */
  12580. this.polygonOffsetFactor = 0;
  12581. /**
  12582. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12583. *
  12584. * @type {number}
  12585. * @default 0
  12586. */
  12587. this.polygonOffsetUnits = 0;
  12588. /**
  12589. * Whether to apply dithering to the color to remove the appearance of banding.
  12590. *
  12591. * @type {boolean}
  12592. * @default false
  12593. */
  12594. this.dithering = false;
  12595. /**
  12596. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12597. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12598. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12599. *
  12600. * @type {boolean}
  12601. * @default false
  12602. */
  12603. this.alphaToCoverage = false;
  12604. /**
  12605. * Whether to premultiply the alpha (transparency) value.
  12606. *
  12607. * @type {boolean}
  12608. * @default false
  12609. */
  12610. this.premultipliedAlpha = false;
  12611. /**
  12612. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12613. *
  12614. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12615. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12616. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12617. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12618. * disable the two pass rendering to avoid performance issues.
  12619. *
  12620. * @type {boolean}
  12621. * @default false
  12622. */
  12623. this.forceSinglePass = false;
  12624. /**
  12625. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12626. *
  12627. * @type {boolean}
  12628. * @default true
  12629. */
  12630. this.allowOverride = true;
  12631. /**
  12632. * Defines whether 3D objects using this material are visible.
  12633. *
  12634. * @type {boolean}
  12635. * @default true
  12636. */
  12637. this.visible = true;
  12638. /**
  12639. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12640. *
  12641. * It is ignored when rendering to a render target or using post processing or when using
  12642. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12643. *
  12644. * @type {boolean}
  12645. * @default true
  12646. */
  12647. this.toneMapped = true;
  12648. /**
  12649. * An object that can be used to store custom data about the Material. It
  12650. * should not hold references to functions as these will not be cloned.
  12651. *
  12652. * @type {Object}
  12653. */
  12654. this.userData = {};
  12655. /**
  12656. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12657. *
  12658. * @type {number}
  12659. * @readonly
  12660. * @default 0
  12661. */
  12662. this.version = 0;
  12663. this._alphaTest = 0;
  12664. }
  12665. /**
  12666. * Sets the alpha value to be used when running an alpha test. The material
  12667. * will not be rendered if the opacity is lower than this value.
  12668. *
  12669. * @type {number}
  12670. * @readonly
  12671. * @default 0
  12672. */
  12673. get alphaTest() {
  12674. return this._alphaTest;
  12675. }
  12676. set alphaTest( value ) {
  12677. if ( this._alphaTest > 0 !== value > 0 ) {
  12678. this.version ++;
  12679. }
  12680. this._alphaTest = value;
  12681. }
  12682. /**
  12683. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12684. *
  12685. * This method can only be used when rendering with {@link WebGLRenderer}.
  12686. *
  12687. * @param {WebGLRenderer} renderer - The renderer.
  12688. * @param {Scene} scene - The scene.
  12689. * @param {Camera} camera - The camera that is used to render the scene.
  12690. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12691. * @param {Object3D} object - The 3D object.
  12692. * @param {Object} group - The geometry group data.
  12693. */
  12694. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12695. /**
  12696. * An optional callback that is executed immediately before the shader
  12697. * program is compiled. This function is called with the shader source code
  12698. * as a parameter. Useful for the modification of built-in materials.
  12699. *
  12700. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12701. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12702. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12703. *
  12704. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12705. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12706. */
  12707. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12708. /**
  12709. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12710. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12711. * shader or recompile the shader for this material as needed.
  12712. *
  12713. * This method can only be used when rendering with {@link WebGLRenderer}.
  12714. *
  12715. * @return {string} The custom program cache key.
  12716. */
  12717. customProgramCacheKey() {
  12718. return this.onBeforeCompile.toString();
  12719. }
  12720. /**
  12721. * This method can be used to set default values from parameter objects.
  12722. * It is a generic implementation so it can be used with different types
  12723. * of materials.
  12724. *
  12725. * @param {Object} [values] - The material values to set.
  12726. */
  12727. setValues( values ) {
  12728. if ( values === undefined ) return;
  12729. for ( const key in values ) {
  12730. const newValue = values[ key ];
  12731. if ( newValue === undefined ) {
  12732. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12733. continue;
  12734. }
  12735. const currentValue = this[ key ];
  12736. if ( currentValue === undefined ) {
  12737. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12738. continue;
  12739. }
  12740. if ( currentValue && currentValue.isColor ) {
  12741. currentValue.set( newValue );
  12742. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12743. currentValue.copy( newValue );
  12744. } else {
  12745. this[ key ] = newValue;
  12746. }
  12747. }
  12748. }
  12749. /**
  12750. * Serializes the material into JSON.
  12751. *
  12752. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12753. * @return {Object} A JSON object representing the serialized material.
  12754. * @see {@link ObjectLoader#parse}
  12755. */
  12756. toJSON( meta ) {
  12757. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12758. if ( isRootObject ) {
  12759. meta = {
  12760. textures: {},
  12761. images: {}
  12762. };
  12763. }
  12764. const data = {
  12765. metadata: {
  12766. version: 4.7,
  12767. type: 'Material',
  12768. generator: 'Material.toJSON'
  12769. }
  12770. };
  12771. // standard Material serialization
  12772. data.uuid = this.uuid;
  12773. data.type = this.type;
  12774. if ( this.name !== '' ) data.name = this.name;
  12775. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12776. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12777. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12778. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12779. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12780. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12781. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12782. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12783. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12784. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12785. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12786. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12787. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12788. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12789. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12790. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12791. }
  12792. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12793. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12794. }
  12795. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12796. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12797. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12798. }
  12799. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12800. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12801. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12802. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12803. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12804. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12805. }
  12806. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12807. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12808. }
  12809. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12810. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12811. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12812. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12813. }
  12814. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12815. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12816. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12817. if ( this.lightMap && this.lightMap.isTexture ) {
  12818. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12819. data.lightMapIntensity = this.lightMapIntensity;
  12820. }
  12821. if ( this.aoMap && this.aoMap.isTexture ) {
  12822. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12823. data.aoMapIntensity = this.aoMapIntensity;
  12824. }
  12825. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12826. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12827. data.bumpScale = this.bumpScale;
  12828. }
  12829. if ( this.normalMap && this.normalMap.isTexture ) {
  12830. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12831. data.normalMapType = this.normalMapType;
  12832. data.normalScale = this.normalScale.toArray();
  12833. }
  12834. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12835. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12836. data.displacementScale = this.displacementScale;
  12837. data.displacementBias = this.displacementBias;
  12838. }
  12839. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12840. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12841. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12842. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12843. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12844. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12845. if ( this.envMap && this.envMap.isTexture ) {
  12846. data.envMap = this.envMap.toJSON( meta ).uuid;
  12847. if ( this.combine !== undefined ) data.combine = this.combine;
  12848. }
  12849. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12850. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12851. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12852. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12853. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12854. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12855. }
  12856. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12857. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12858. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12859. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12860. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12861. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12862. if ( this.size !== undefined ) data.size = this.size;
  12863. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12864. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12865. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12866. if ( this.side !== FrontSide ) data.side = this.side;
  12867. if ( this.vertexColors === true ) data.vertexColors = true;
  12868. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12869. if ( this.transparent === true ) data.transparent = true;
  12870. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12871. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12872. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12873. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12874. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12875. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12876. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12877. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12878. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12879. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12880. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12881. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12882. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12883. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12884. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12885. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12886. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12887. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12888. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12889. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12890. // rotation (SpriteMaterial)
  12891. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12892. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12893. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12894. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12895. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12896. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12897. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12898. if ( this.scale !== undefined ) data.scale = this.scale;
  12899. if ( this.dithering === true ) data.dithering = true;
  12900. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12901. if ( this.alphaHash === true ) data.alphaHash = true;
  12902. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12903. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12904. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12905. if ( this.wireframe === true ) data.wireframe = true;
  12906. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12907. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12908. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12909. if ( this.flatShading === true ) data.flatShading = true;
  12910. if ( this.visible === false ) data.visible = false;
  12911. if ( this.toneMapped === false ) data.toneMapped = false;
  12912. if ( this.fog === false ) data.fog = false;
  12913. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12914. // TODO: Copied from Object3D.toJSON
  12915. function extractFromCache( cache ) {
  12916. const values = [];
  12917. for ( const key in cache ) {
  12918. const data = cache[ key ];
  12919. delete data.metadata;
  12920. values.push( data );
  12921. }
  12922. return values;
  12923. }
  12924. if ( isRootObject ) {
  12925. const textures = extractFromCache( meta.textures );
  12926. const images = extractFromCache( meta.images );
  12927. if ( textures.length > 0 ) data.textures = textures;
  12928. if ( images.length > 0 ) data.images = images;
  12929. }
  12930. return data;
  12931. }
  12932. /**
  12933. * Returns a new material with copied values from this instance.
  12934. *
  12935. * @return {Material} A clone of this instance.
  12936. */
  12937. clone() {
  12938. return new this.constructor().copy( this );
  12939. }
  12940. /**
  12941. * Copies the values of the given material to this instance.
  12942. *
  12943. * @param {Material} source - The material to copy.
  12944. * @return {Material} A reference to this instance.
  12945. */
  12946. copy( source ) {
  12947. this.name = source.name;
  12948. this.blending = source.blending;
  12949. this.side = source.side;
  12950. this.vertexColors = source.vertexColors;
  12951. this.opacity = source.opacity;
  12952. this.transparent = source.transparent;
  12953. this.blendSrc = source.blendSrc;
  12954. this.blendDst = source.blendDst;
  12955. this.blendEquation = source.blendEquation;
  12956. this.blendSrcAlpha = source.blendSrcAlpha;
  12957. this.blendDstAlpha = source.blendDstAlpha;
  12958. this.blendEquationAlpha = source.blendEquationAlpha;
  12959. this.blendColor.copy( source.blendColor );
  12960. this.blendAlpha = source.blendAlpha;
  12961. this.depthFunc = source.depthFunc;
  12962. this.depthTest = source.depthTest;
  12963. this.depthWrite = source.depthWrite;
  12964. this.stencilWriteMask = source.stencilWriteMask;
  12965. this.stencilFunc = source.stencilFunc;
  12966. this.stencilRef = source.stencilRef;
  12967. this.stencilFuncMask = source.stencilFuncMask;
  12968. this.stencilFail = source.stencilFail;
  12969. this.stencilZFail = source.stencilZFail;
  12970. this.stencilZPass = source.stencilZPass;
  12971. this.stencilWrite = source.stencilWrite;
  12972. const srcPlanes = source.clippingPlanes;
  12973. let dstPlanes = null;
  12974. if ( srcPlanes !== null ) {
  12975. const n = srcPlanes.length;
  12976. dstPlanes = new Array( n );
  12977. for ( let i = 0; i !== n; ++ i ) {
  12978. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12979. }
  12980. }
  12981. this.clippingPlanes = dstPlanes;
  12982. this.clipIntersection = source.clipIntersection;
  12983. this.clipShadows = source.clipShadows;
  12984. this.shadowSide = source.shadowSide;
  12985. this.colorWrite = source.colorWrite;
  12986. this.precision = source.precision;
  12987. this.polygonOffset = source.polygonOffset;
  12988. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12989. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12990. this.dithering = source.dithering;
  12991. this.alphaTest = source.alphaTest;
  12992. this.alphaHash = source.alphaHash;
  12993. this.alphaToCoverage = source.alphaToCoverage;
  12994. this.premultipliedAlpha = source.premultipliedAlpha;
  12995. this.forceSinglePass = source.forceSinglePass;
  12996. this.visible = source.visible;
  12997. this.toneMapped = source.toneMapped;
  12998. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  12999. return this;
  13000. }
  13001. /**
  13002. * Frees the GPU-related resources allocated by this instance. Call this
  13003. * method whenever this instance is no longer used in your app.
  13004. *
  13005. * @fires Material#dispose
  13006. */
  13007. dispose() {
  13008. /**
  13009. * Fires when the material has been disposed of.
  13010. *
  13011. * @event Material#dispose
  13012. * @type {Object}
  13013. */
  13014. this.dispatchEvent( { type: 'dispose' } );
  13015. }
  13016. /**
  13017. * Setting this property to `true` indicates the engine the material
  13018. * needs to be recompiled.
  13019. *
  13020. * @type {boolean}
  13021. * @default false
  13022. * @param {boolean} value
  13023. */
  13024. set needsUpdate( value ) {
  13025. if ( value === true ) this.version ++;
  13026. }
  13027. }
  13028. /**
  13029. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13030. *
  13031. * This material is not affected by lights.
  13032. *
  13033. * @augments Material
  13034. */
  13035. class MeshBasicMaterial extends Material {
  13036. /**
  13037. * Constructs a new mesh basic material.
  13038. *
  13039. * @param {Object} [parameters] - An object with one or more properties
  13040. * defining the material's appearance. Any property of the material
  13041. * (including any property from inherited materials) can be passed
  13042. * in here. Color values can be passed any type of value accepted
  13043. * by {@link Color#set}.
  13044. */
  13045. constructor( parameters ) {
  13046. super();
  13047. /**
  13048. * This flag can be used for type testing.
  13049. *
  13050. * @type {boolean}
  13051. * @readonly
  13052. * @default true
  13053. */
  13054. this.isMeshBasicMaterial = true;
  13055. this.type = 'MeshBasicMaterial';
  13056. /**
  13057. * Color of the material.
  13058. *
  13059. * @type {Color}
  13060. * @default (1,1,1)
  13061. */
  13062. this.color = new Color( 0xffffff ); // diffuse
  13063. /**
  13064. * The color map. May optionally include an alpha channel, typically combined
  13065. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13066. * color is modulated by the diffuse `color`.
  13067. *
  13068. * @type {?Texture}
  13069. * @default null
  13070. */
  13071. this.map = null;
  13072. /**
  13073. * The light map. Requires a second set of UVs.
  13074. *
  13075. * @type {?Texture}
  13076. * @default null
  13077. */
  13078. this.lightMap = null;
  13079. /**
  13080. * Intensity of the baked light.
  13081. *
  13082. * @type {number}
  13083. * @default 1
  13084. */
  13085. this.lightMapIntensity = 1.0;
  13086. /**
  13087. * The red channel of this texture is used as the ambient occlusion map.
  13088. * Requires a second set of UVs.
  13089. *
  13090. * @type {?Texture}
  13091. * @default null
  13092. */
  13093. this.aoMap = null;
  13094. /**
  13095. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13096. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13097. * red channel is also `1`, ambient light is fully occluded on a surface.
  13098. *
  13099. * @type {number}
  13100. * @default 1
  13101. */
  13102. this.aoMapIntensity = 1.0;
  13103. /**
  13104. * Specular map used by the material.
  13105. *
  13106. * @type {?Texture}
  13107. * @default null
  13108. */
  13109. this.specularMap = null;
  13110. /**
  13111. * The alpha map is a grayscale texture that controls the opacity across the
  13112. * surface (black: fully transparent; white: fully opaque).
  13113. *
  13114. * Only the color of the texture is used, ignoring the alpha channel if one
  13115. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13116. * when sampling this texture due to the extra bit of precision provided for
  13117. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13118. * luminance/alpha textures will also still work as expected.
  13119. *
  13120. * @type {?Texture}
  13121. * @default null
  13122. */
  13123. this.alphaMap = null;
  13124. /**
  13125. * The environment map.
  13126. *
  13127. * @type {?Texture}
  13128. * @default null
  13129. */
  13130. this.envMap = null;
  13131. /**
  13132. * The rotation of the environment map in radians.
  13133. *
  13134. * @type {Euler}
  13135. * @default (0,0,0)
  13136. */
  13137. this.envMapRotation = new Euler();
  13138. /**
  13139. * How to combine the result of the surface's color with the environment map, if any.
  13140. *
  13141. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13142. * blend between the two colors.
  13143. *
  13144. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13145. * @default MultiplyOperation
  13146. */
  13147. this.combine = MultiplyOperation;
  13148. /**
  13149. * How much the environment map affects the surface.
  13150. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13151. *
  13152. * @type {number}
  13153. * @default 1
  13154. */
  13155. this.reflectivity = 1;
  13156. /**
  13157. * The index of refraction (IOR) of air (approximately 1) divided by the
  13158. * index of refraction of the material. It is used with environment mapping
  13159. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13160. * The refraction ratio should not exceed `1`.
  13161. *
  13162. * @type {number}
  13163. * @default 0.98
  13164. */
  13165. this.refractionRatio = 0.98;
  13166. /**
  13167. * Renders the geometry as a wireframe.
  13168. *
  13169. * @type {boolean}
  13170. * @default false
  13171. */
  13172. this.wireframe = false;
  13173. /**
  13174. * Controls the thickness of the wireframe.
  13175. *
  13176. * Can only be used with {@link SVGRenderer}.
  13177. *
  13178. * @type {number}
  13179. * @default 1
  13180. */
  13181. this.wireframeLinewidth = 1;
  13182. /**
  13183. * Defines appearance of wireframe ends.
  13184. *
  13185. * Can only be used with {@link SVGRenderer}.
  13186. *
  13187. * @type {('round'|'bevel'|'miter')}
  13188. * @default 'round'
  13189. */
  13190. this.wireframeLinecap = 'round';
  13191. /**
  13192. * Defines appearance of wireframe joints.
  13193. *
  13194. * Can only be used with {@link SVGRenderer}.
  13195. *
  13196. * @type {('round'|'bevel'|'miter')}
  13197. * @default 'round'
  13198. */
  13199. this.wireframeLinejoin = 'round';
  13200. /**
  13201. * Whether the material is affected by fog or not.
  13202. *
  13203. * @type {boolean}
  13204. * @default true
  13205. */
  13206. this.fog = true;
  13207. this.setValues( parameters );
  13208. }
  13209. copy( source ) {
  13210. super.copy( source );
  13211. this.color.copy( source.color );
  13212. this.map = source.map;
  13213. this.lightMap = source.lightMap;
  13214. this.lightMapIntensity = source.lightMapIntensity;
  13215. this.aoMap = source.aoMap;
  13216. this.aoMapIntensity = source.aoMapIntensity;
  13217. this.specularMap = source.specularMap;
  13218. this.alphaMap = source.alphaMap;
  13219. this.envMap = source.envMap;
  13220. this.envMapRotation.copy( source.envMapRotation );
  13221. this.combine = source.combine;
  13222. this.reflectivity = source.reflectivity;
  13223. this.refractionRatio = source.refractionRatio;
  13224. this.wireframe = source.wireframe;
  13225. this.wireframeLinewidth = source.wireframeLinewidth;
  13226. this.wireframeLinecap = source.wireframeLinecap;
  13227. this.wireframeLinejoin = source.wireframeLinejoin;
  13228. this.fog = source.fog;
  13229. return this;
  13230. }
  13231. }
  13232. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13233. const _tables = /*@__PURE__*/ _generateTables();
  13234. function _generateTables() {
  13235. // float32 to float16 helpers
  13236. const buffer = new ArrayBuffer( 4 );
  13237. const floatView = new Float32Array( buffer );
  13238. const uint32View = new Uint32Array( buffer );
  13239. const baseTable = new Uint32Array( 512 );
  13240. const shiftTable = new Uint32Array( 512 );
  13241. for ( let i = 0; i < 256; ++ i ) {
  13242. const e = i - 127;
  13243. // very small number (0, -0)
  13244. if ( e < -27 ) {
  13245. baseTable[ i ] = 0x0000;
  13246. baseTable[ i | 0x100 ] = 0x8000;
  13247. shiftTable[ i ] = 24;
  13248. shiftTable[ i | 0x100 ] = 24;
  13249. // small number (denorm)
  13250. } else if ( e < -14 ) {
  13251. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13252. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13253. shiftTable[ i ] = - e - 1;
  13254. shiftTable[ i | 0x100 ] = - e - 1;
  13255. // normal number
  13256. } else if ( e <= 15 ) {
  13257. baseTable[ i ] = ( e + 15 ) << 10;
  13258. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13259. shiftTable[ i ] = 13;
  13260. shiftTable[ i | 0x100 ] = 13;
  13261. // large number (Infinity, -Infinity)
  13262. } else if ( e < 128 ) {
  13263. baseTable[ i ] = 0x7c00;
  13264. baseTable[ i | 0x100 ] = 0xfc00;
  13265. shiftTable[ i ] = 24;
  13266. shiftTable[ i | 0x100 ] = 24;
  13267. // stay (NaN, Infinity, -Infinity)
  13268. } else {
  13269. baseTable[ i ] = 0x7c00;
  13270. baseTable[ i | 0x100 ] = 0xfc00;
  13271. shiftTable[ i ] = 13;
  13272. shiftTable[ i | 0x100 ] = 13;
  13273. }
  13274. }
  13275. // float16 to float32 helpers
  13276. const mantissaTable = new Uint32Array( 2048 );
  13277. const exponentTable = new Uint32Array( 64 );
  13278. const offsetTable = new Uint32Array( 64 );
  13279. for ( let i = 1; i < 1024; ++ i ) {
  13280. let m = i << 13; // zero pad mantissa bits
  13281. let e = 0; // zero exponent
  13282. // normalized
  13283. while ( ( m & 0x00800000 ) === 0 ) {
  13284. m <<= 1;
  13285. e -= 0x00800000; // decrement exponent
  13286. }
  13287. m &= -8388609; // clear leading 1 bit
  13288. e += 0x38800000; // adjust bias
  13289. mantissaTable[ i ] = m | e;
  13290. }
  13291. for ( let i = 1024; i < 2048; ++ i ) {
  13292. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13293. }
  13294. for ( let i = 1; i < 31; ++ i ) {
  13295. exponentTable[ i ] = i << 23;
  13296. }
  13297. exponentTable[ 31 ] = 0x47800000;
  13298. exponentTable[ 32 ] = 0x80000000;
  13299. for ( let i = 33; i < 63; ++ i ) {
  13300. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13301. }
  13302. exponentTable[ 63 ] = 0xc7800000;
  13303. for ( let i = 1; i < 64; ++ i ) {
  13304. if ( i !== 32 ) {
  13305. offsetTable[ i ] = 1024;
  13306. }
  13307. }
  13308. return {
  13309. floatView: floatView,
  13310. uint32View: uint32View,
  13311. baseTable: baseTable,
  13312. shiftTable: shiftTable,
  13313. mantissaTable: mantissaTable,
  13314. exponentTable: exponentTable,
  13315. offsetTable: offsetTable
  13316. };
  13317. }
  13318. /**
  13319. * Returns a half precision floating point value (FP16) from the given single
  13320. * precision floating point value (FP32).
  13321. *
  13322. * @param {number} val - A single precision floating point value.
  13323. * @return {number} The FP16 value.
  13324. */
  13325. function toHalfFloat( val ) {
  13326. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13327. val = clamp( val, -65504, 65504 );
  13328. _tables.floatView[ 0 ] = val;
  13329. const f = _tables.uint32View[ 0 ];
  13330. const e = ( f >> 23 ) & 0x1ff;
  13331. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13332. }
  13333. /**
  13334. * Returns a single precision floating point value (FP32) from the given half
  13335. * precision floating point value (FP16).
  13336. *
  13337. * @param {number} val - A half precision floating point value.
  13338. * @return {number} The FP32 value.
  13339. */
  13340. function fromHalfFloat( val ) {
  13341. const m = val >> 10;
  13342. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13343. return _tables.floatView[ 0 ];
  13344. }
  13345. /**
  13346. * A class containing utility functions for data.
  13347. *
  13348. * @hideconstructor
  13349. */
  13350. class DataUtils {
  13351. /**
  13352. * Returns a half precision floating point value (FP16) from the given single
  13353. * precision floating point value (FP32).
  13354. *
  13355. * @param {number} val - A single precision floating point value.
  13356. * @return {number} The FP16 value.
  13357. */
  13358. static toHalfFloat( val ) {
  13359. return toHalfFloat( val );
  13360. }
  13361. /**
  13362. * Returns a single precision floating point value (FP32) from the given half
  13363. * precision floating point value (FP16).
  13364. *
  13365. * @param {number} val - A half precision floating point value.
  13366. * @return {number} The FP32 value.
  13367. */
  13368. static fromHalfFloat( val ) {
  13369. return fromHalfFloat( val );
  13370. }
  13371. }
  13372. const _vector$9 = /*@__PURE__*/ new Vector3();
  13373. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13374. let _id$2 = 0;
  13375. /**
  13376. * This class stores data for an attribute (such as vertex positions, face
  13377. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13378. * a geometry, which allows for more efficient passing of data to the GPU.
  13379. *
  13380. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13381. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13382. */
  13383. class BufferAttribute {
  13384. /**
  13385. * Constructs a new buffer attribute.
  13386. *
  13387. * @param {TypedArray} array - The array holding the attribute data.
  13388. * @param {number} itemSize - The item size.
  13389. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13390. */
  13391. constructor( array, itemSize, normalized = false ) {
  13392. if ( Array.isArray( array ) ) {
  13393. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13394. }
  13395. /**
  13396. * This flag can be used for type testing.
  13397. *
  13398. * @type {boolean}
  13399. * @readonly
  13400. * @default true
  13401. */
  13402. this.isBufferAttribute = true;
  13403. /**
  13404. * The ID of the buffer attribute.
  13405. *
  13406. * @name BufferAttribute#id
  13407. * @type {number}
  13408. * @readonly
  13409. */
  13410. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13411. /**
  13412. * The name of the buffer attribute.
  13413. *
  13414. * @type {string}
  13415. */
  13416. this.name = '';
  13417. /**
  13418. * The array holding the attribute data. It should have `itemSize * numVertices`
  13419. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13420. *
  13421. * @type {TypedArray}
  13422. */
  13423. this.array = array;
  13424. /**
  13425. * The number of values of the array that should be associated with a particular vertex.
  13426. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13427. * normal, or color), then the value should be `3`.
  13428. *
  13429. * @type {number}
  13430. */
  13431. this.itemSize = itemSize;
  13432. /**
  13433. * Represents the number of items this buffer attribute stores. It is internally computed
  13434. * by dividing the `array` length by the `itemSize`.
  13435. *
  13436. * @type {number}
  13437. * @readonly
  13438. */
  13439. this.count = array !== undefined ? array.length / itemSize : 0;
  13440. /**
  13441. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13442. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13443. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13444. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13445. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13446. *
  13447. * @type {boolean}
  13448. */
  13449. this.normalized = normalized;
  13450. /**
  13451. * Defines the intended usage pattern of the data store for optimization purposes.
  13452. *
  13453. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13454. * instantiate a new one and set the desired usage before the next render.
  13455. *
  13456. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13457. * @default StaticDrawUsage
  13458. */
  13459. this.usage = StaticDrawUsage;
  13460. /**
  13461. * This can be used to only update some components of stored vectors (for example, just the
  13462. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13463. *
  13464. * @type {Array<Object>}
  13465. */
  13466. this.updateRanges = [];
  13467. /**
  13468. * Configures the bound GPU type for use in shaders.
  13469. *
  13470. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13471. * For lower precision float types, use `Float16BufferAttribute`.
  13472. *
  13473. * @type {(FloatType|IntType)}
  13474. * @default FloatType
  13475. */
  13476. this.gpuType = FloatType;
  13477. /**
  13478. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13479. *
  13480. * @type {number}
  13481. */
  13482. this.version = 0;
  13483. }
  13484. /**
  13485. * A callback function that is executed after the renderer has transferred the attribute
  13486. * array data to the GPU.
  13487. */
  13488. onUploadCallback() {}
  13489. /**
  13490. * Flag to indicate that this attribute has changed and should be re-sent to
  13491. * the GPU. Set this to `true` when you modify the value of the array.
  13492. *
  13493. * @type {number}
  13494. * @default false
  13495. * @param {boolean} value
  13496. */
  13497. set needsUpdate( value ) {
  13498. if ( value === true ) this.version ++;
  13499. }
  13500. /**
  13501. * Sets the usage of this buffer attribute.
  13502. *
  13503. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13504. * @return {BufferAttribute} A reference to this buffer attribute.
  13505. */
  13506. setUsage( value ) {
  13507. this.usage = value;
  13508. return this;
  13509. }
  13510. /**
  13511. * Adds a range of data in the data array to be updated on the GPU.
  13512. *
  13513. * @param {number} start - Position at which to start update.
  13514. * @param {number} count - The number of components to update.
  13515. */
  13516. addUpdateRange( start, count ) {
  13517. this.updateRanges.push( { start, count } );
  13518. }
  13519. /**
  13520. * Clears the update ranges.
  13521. */
  13522. clearUpdateRanges() {
  13523. this.updateRanges.length = 0;
  13524. }
  13525. /**
  13526. * Copies the values of the given buffer attribute to this instance.
  13527. *
  13528. * @param {BufferAttribute} source - The buffer attribute to copy.
  13529. * @return {BufferAttribute} A reference to this instance.
  13530. */
  13531. copy( source ) {
  13532. this.name = source.name;
  13533. this.array = new source.array.constructor( source.array );
  13534. this.itemSize = source.itemSize;
  13535. this.count = source.count;
  13536. this.normalized = source.normalized;
  13537. this.usage = source.usage;
  13538. this.gpuType = source.gpuType;
  13539. return this;
  13540. }
  13541. /**
  13542. * Copies a vector from the given buffer attribute to this one. The start
  13543. * and destination position in the attribute buffers are represented by the
  13544. * given indices.
  13545. *
  13546. * @param {number} index1 - The destination index into this buffer attribute.
  13547. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13548. * @param {number} index2 - The source index into the given buffer attribute.
  13549. * @return {BufferAttribute} A reference to this instance.
  13550. */
  13551. copyAt( index1, attribute, index2 ) {
  13552. index1 *= this.itemSize;
  13553. index2 *= attribute.itemSize;
  13554. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13555. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13556. }
  13557. return this;
  13558. }
  13559. /**
  13560. * Copies the given array data into this buffer attribute.
  13561. *
  13562. * @param {(TypedArray|Array)} array - The array to copy.
  13563. * @return {BufferAttribute} A reference to this instance.
  13564. */
  13565. copyArray( array ) {
  13566. this.array.set( array );
  13567. return this;
  13568. }
  13569. /**
  13570. * Applies the given 3x3 matrix to the given attribute. Works with
  13571. * item size `2` and `3`.
  13572. *
  13573. * @param {Matrix3} m - The matrix to apply.
  13574. * @return {BufferAttribute} A reference to this instance.
  13575. */
  13576. applyMatrix3( m ) {
  13577. if ( this.itemSize === 2 ) {
  13578. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13579. _vector2$1.fromBufferAttribute( this, i );
  13580. _vector2$1.applyMatrix3( m );
  13581. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13582. }
  13583. } else if ( this.itemSize === 3 ) {
  13584. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13585. _vector$9.fromBufferAttribute( this, i );
  13586. _vector$9.applyMatrix3( m );
  13587. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13588. }
  13589. }
  13590. return this;
  13591. }
  13592. /**
  13593. * Applies the given 4x4 matrix to the given attribute. Only works with
  13594. * item size `3`.
  13595. *
  13596. * @param {Matrix4} m - The matrix to apply.
  13597. * @return {BufferAttribute} A reference to this instance.
  13598. */
  13599. applyMatrix4( m ) {
  13600. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13601. _vector$9.fromBufferAttribute( this, i );
  13602. _vector$9.applyMatrix4( m );
  13603. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13604. }
  13605. return this;
  13606. }
  13607. /**
  13608. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13609. * item size `3`.
  13610. *
  13611. * @param {Matrix3} m - The normal matrix to apply.
  13612. * @return {BufferAttribute} A reference to this instance.
  13613. */
  13614. applyNormalMatrix( m ) {
  13615. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13616. _vector$9.fromBufferAttribute( this, i );
  13617. _vector$9.applyNormalMatrix( m );
  13618. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13619. }
  13620. return this;
  13621. }
  13622. /**
  13623. * Applies the given 4x4 matrix to the given attribute. Only works with
  13624. * item size `3` and with direction vectors.
  13625. *
  13626. * @param {Matrix4} m - The matrix to apply.
  13627. * @return {BufferAttribute} A reference to this instance.
  13628. */
  13629. transformDirection( m ) {
  13630. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13631. _vector$9.fromBufferAttribute( this, i );
  13632. _vector$9.transformDirection( m );
  13633. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13634. }
  13635. return this;
  13636. }
  13637. /**
  13638. * Sets the given array data in the buffer attribute.
  13639. *
  13640. * @param {(TypedArray|Array)} value - The array data to set.
  13641. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13642. * @return {BufferAttribute} A reference to this instance.
  13643. */
  13644. set( value, offset = 0 ) {
  13645. // Matching BufferAttribute constructor, do not normalize the array.
  13646. this.array.set( value, offset );
  13647. return this;
  13648. }
  13649. /**
  13650. * Returns the given component of the vector at the given index.
  13651. *
  13652. * @param {number} index - The index into the buffer attribute.
  13653. * @param {number} component - The component index.
  13654. * @return {number} The returned value.
  13655. */
  13656. getComponent( index, component ) {
  13657. let value = this.array[ index * this.itemSize + component ];
  13658. if ( this.normalized ) value = denormalize( value, this.array );
  13659. return value;
  13660. }
  13661. /**
  13662. * Sets the given value to the given component of the vector at the given index.
  13663. *
  13664. * @param {number} index - The index into the buffer attribute.
  13665. * @param {number} component - The component index.
  13666. * @param {number} value - The value to set.
  13667. * @return {BufferAttribute} A reference to this instance.
  13668. */
  13669. setComponent( index, component, value ) {
  13670. if ( this.normalized ) value = normalize( value, this.array );
  13671. this.array[ index * this.itemSize + component ] = value;
  13672. return this;
  13673. }
  13674. /**
  13675. * Returns the x component of the vector at the given index.
  13676. *
  13677. * @param {number} index - The index into the buffer attribute.
  13678. * @return {number} The x component.
  13679. */
  13680. getX( index ) {
  13681. let x = this.array[ index * this.itemSize ];
  13682. if ( this.normalized ) x = denormalize( x, this.array );
  13683. return x;
  13684. }
  13685. /**
  13686. * Sets the x component of the vector at the given index.
  13687. *
  13688. * @param {number} index - The index into the buffer attribute.
  13689. * @param {number} x - The value to set.
  13690. * @return {BufferAttribute} A reference to this instance.
  13691. */
  13692. setX( index, x ) {
  13693. if ( this.normalized ) x = normalize( x, this.array );
  13694. this.array[ index * this.itemSize ] = x;
  13695. return this;
  13696. }
  13697. /**
  13698. * Returns the y component of the vector at the given index.
  13699. *
  13700. * @param {number} index - The index into the buffer attribute.
  13701. * @return {number} The y component.
  13702. */
  13703. getY( index ) {
  13704. let y = this.array[ index * this.itemSize + 1 ];
  13705. if ( this.normalized ) y = denormalize( y, this.array );
  13706. return y;
  13707. }
  13708. /**
  13709. * Sets the y component of the vector at the given index.
  13710. *
  13711. * @param {number} index - The index into the buffer attribute.
  13712. * @param {number} y - The value to set.
  13713. * @return {BufferAttribute} A reference to this instance.
  13714. */
  13715. setY( index, y ) {
  13716. if ( this.normalized ) y = normalize( y, this.array );
  13717. this.array[ index * this.itemSize + 1 ] = y;
  13718. return this;
  13719. }
  13720. /**
  13721. * Returns the z component of the vector at the given index.
  13722. *
  13723. * @param {number} index - The index into the buffer attribute.
  13724. * @return {number} The z component.
  13725. */
  13726. getZ( index ) {
  13727. let z = this.array[ index * this.itemSize + 2 ];
  13728. if ( this.normalized ) z = denormalize( z, this.array );
  13729. return z;
  13730. }
  13731. /**
  13732. * Sets the z component of the vector at the given index.
  13733. *
  13734. * @param {number} index - The index into the buffer attribute.
  13735. * @param {number} z - The value to set.
  13736. * @return {BufferAttribute} A reference to this instance.
  13737. */
  13738. setZ( index, z ) {
  13739. if ( this.normalized ) z = normalize( z, this.array );
  13740. this.array[ index * this.itemSize + 2 ] = z;
  13741. return this;
  13742. }
  13743. /**
  13744. * Returns the w component of the vector at the given index.
  13745. *
  13746. * @param {number} index - The index into the buffer attribute.
  13747. * @return {number} The w component.
  13748. */
  13749. getW( index ) {
  13750. let w = this.array[ index * this.itemSize + 3 ];
  13751. if ( this.normalized ) w = denormalize( w, this.array );
  13752. return w;
  13753. }
  13754. /**
  13755. * Sets the w component of the vector at the given index.
  13756. *
  13757. * @param {number} index - The index into the buffer attribute.
  13758. * @param {number} w - The value to set.
  13759. * @return {BufferAttribute} A reference to this instance.
  13760. */
  13761. setW( index, w ) {
  13762. if ( this.normalized ) w = normalize( w, this.array );
  13763. this.array[ index * this.itemSize + 3 ] = w;
  13764. return this;
  13765. }
  13766. /**
  13767. * Sets the x and y component of the vector at the given index.
  13768. *
  13769. * @param {number} index - The index into the buffer attribute.
  13770. * @param {number} x - The value for the x component to set.
  13771. * @param {number} y - The value for the y component to set.
  13772. * @return {BufferAttribute} A reference to this instance.
  13773. */
  13774. setXY( index, x, y ) {
  13775. index *= this.itemSize;
  13776. if ( this.normalized ) {
  13777. x = normalize( x, this.array );
  13778. y = normalize( y, this.array );
  13779. }
  13780. this.array[ index + 0 ] = x;
  13781. this.array[ index + 1 ] = y;
  13782. return this;
  13783. }
  13784. /**
  13785. * Sets the x, y and z component of the vector at the given index.
  13786. *
  13787. * @param {number} index - The index into the buffer attribute.
  13788. * @param {number} x - The value for the x component to set.
  13789. * @param {number} y - The value for the y component to set.
  13790. * @param {number} z - The value for the z component to set.
  13791. * @return {BufferAttribute} A reference to this instance.
  13792. */
  13793. setXYZ( index, x, y, z ) {
  13794. index *= this.itemSize;
  13795. if ( this.normalized ) {
  13796. x = normalize( x, this.array );
  13797. y = normalize( y, this.array );
  13798. z = normalize( z, this.array );
  13799. }
  13800. this.array[ index + 0 ] = x;
  13801. this.array[ index + 1 ] = y;
  13802. this.array[ index + 2 ] = z;
  13803. return this;
  13804. }
  13805. /**
  13806. * Sets the x, y, z and w component of the vector at the given index.
  13807. *
  13808. * @param {number} index - The index into the buffer attribute.
  13809. * @param {number} x - The value for the x component to set.
  13810. * @param {number} y - The value for the y component to set.
  13811. * @param {number} z - The value for the z component to set.
  13812. * @param {number} w - The value for the w component to set.
  13813. * @return {BufferAttribute} A reference to this instance.
  13814. */
  13815. setXYZW( index, x, y, z, w ) {
  13816. index *= this.itemSize;
  13817. if ( this.normalized ) {
  13818. x = normalize( x, this.array );
  13819. y = normalize( y, this.array );
  13820. z = normalize( z, this.array );
  13821. w = normalize( w, this.array );
  13822. }
  13823. this.array[ index + 0 ] = x;
  13824. this.array[ index + 1 ] = y;
  13825. this.array[ index + 2 ] = z;
  13826. this.array[ index + 3 ] = w;
  13827. return this;
  13828. }
  13829. /**
  13830. * Sets the given callback function that is executed after the Renderer has transferred
  13831. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13832. * the upload when attribute data are not needed anymore on the CPU side.
  13833. *
  13834. * @param {Function} callback - The `onUpload()` callback.
  13835. * @return {BufferAttribute} A reference to this instance.
  13836. */
  13837. onUpload( callback ) {
  13838. this.onUploadCallback = callback;
  13839. return this;
  13840. }
  13841. /**
  13842. * Returns a new buffer attribute with copied values from this instance.
  13843. *
  13844. * @return {BufferAttribute} A clone of this instance.
  13845. */
  13846. clone() {
  13847. return new this.constructor( this.array, this.itemSize ).copy( this );
  13848. }
  13849. /**
  13850. * Serializes the buffer attribute into JSON.
  13851. *
  13852. * @return {Object} A JSON object representing the serialized buffer attribute.
  13853. */
  13854. toJSON() {
  13855. const data = {
  13856. itemSize: this.itemSize,
  13857. type: this.array.constructor.name,
  13858. array: Array.from( this.array ),
  13859. normalized: this.normalized
  13860. };
  13861. if ( this.name !== '' ) data.name = this.name;
  13862. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13863. return data;
  13864. }
  13865. }
  13866. /**
  13867. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13868. * a plain `Array` instance.
  13869. *
  13870. * @augments BufferAttribute
  13871. */
  13872. class Int8BufferAttribute extends BufferAttribute {
  13873. /**
  13874. * Constructs a new buffer attribute.
  13875. *
  13876. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13877. * @param {number} itemSize - The item size.
  13878. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13879. */
  13880. constructor( array, itemSize, normalized ) {
  13881. super( new Int8Array( array ), itemSize, normalized );
  13882. }
  13883. }
  13884. /**
  13885. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13886. * a plain `Array` instance.
  13887. *
  13888. * @augments BufferAttribute
  13889. */
  13890. class Uint8BufferAttribute extends BufferAttribute {
  13891. /**
  13892. * Constructs a new buffer attribute.
  13893. *
  13894. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13895. * @param {number} itemSize - The item size.
  13896. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13897. */
  13898. constructor( array, itemSize, normalized ) {
  13899. super( new Uint8Array( array ), itemSize, normalized );
  13900. }
  13901. }
  13902. /**
  13903. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13904. * a plain `Array` instance.
  13905. *
  13906. * @augments BufferAttribute
  13907. */
  13908. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13909. /**
  13910. * Constructs a new buffer attribute.
  13911. *
  13912. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13913. * @param {number} itemSize - The item size.
  13914. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13915. */
  13916. constructor( array, itemSize, normalized ) {
  13917. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13918. }
  13919. }
  13920. /**
  13921. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13922. * a plain `Array` instance.
  13923. *
  13924. * @augments BufferAttribute
  13925. */
  13926. class Int16BufferAttribute extends BufferAttribute {
  13927. /**
  13928. * Constructs a new buffer attribute.
  13929. *
  13930. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13931. * @param {number} itemSize - The item size.
  13932. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13933. */
  13934. constructor( array, itemSize, normalized ) {
  13935. super( new Int16Array( array ), itemSize, normalized );
  13936. }
  13937. }
  13938. /**
  13939. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13940. * a plain `Array` instance.
  13941. *
  13942. * @augments BufferAttribute
  13943. */
  13944. class Uint16BufferAttribute extends BufferAttribute {
  13945. /**
  13946. * Constructs a new buffer attribute.
  13947. *
  13948. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13949. * @param {number} itemSize - The item size.
  13950. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13951. */
  13952. constructor( array, itemSize, normalized ) {
  13953. super( new Uint16Array( array ), itemSize, normalized );
  13954. }
  13955. }
  13956. /**
  13957. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13958. * a plain `Array` instance.
  13959. *
  13960. * @augments BufferAttribute
  13961. */
  13962. class Int32BufferAttribute extends BufferAttribute {
  13963. /**
  13964. * Constructs a new buffer attribute.
  13965. *
  13966. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13967. * @param {number} itemSize - The item size.
  13968. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13969. */
  13970. constructor( array, itemSize, normalized ) {
  13971. super( new Int32Array( array ), itemSize, normalized );
  13972. }
  13973. }
  13974. /**
  13975. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13976. * a plain `Array` instance.
  13977. *
  13978. * @augments BufferAttribute
  13979. */
  13980. class Uint32BufferAttribute extends BufferAttribute {
  13981. /**
  13982. * Constructs a new buffer attribute.
  13983. *
  13984. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13985. * @param {number} itemSize - The item size.
  13986. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13987. */
  13988. constructor( array, itemSize, normalized ) {
  13989. super( new Uint32Array( array ), itemSize, normalized );
  13990. }
  13991. }
  13992. /**
  13993. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13994. * a plain `Array` instance.
  13995. *
  13996. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13997. * browser support is still problematic.
  13998. *
  13999. * @augments BufferAttribute
  14000. */
  14001. class Float16BufferAttribute extends BufferAttribute {
  14002. /**
  14003. * Constructs a new buffer attribute.
  14004. *
  14005. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14006. * @param {number} itemSize - The item size.
  14007. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14008. */
  14009. constructor( array, itemSize, normalized ) {
  14010. super( new Uint16Array( array ), itemSize, normalized );
  14011. this.isFloat16BufferAttribute = true;
  14012. }
  14013. getX( index ) {
  14014. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14015. if ( this.normalized ) x = denormalize( x, this.array );
  14016. return x;
  14017. }
  14018. setX( index, x ) {
  14019. if ( this.normalized ) x = normalize( x, this.array );
  14020. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14021. return this;
  14022. }
  14023. getY( index ) {
  14024. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14025. if ( this.normalized ) y = denormalize( y, this.array );
  14026. return y;
  14027. }
  14028. setY( index, y ) {
  14029. if ( this.normalized ) y = normalize( y, this.array );
  14030. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14031. return this;
  14032. }
  14033. getZ( index ) {
  14034. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14035. if ( this.normalized ) z = denormalize( z, this.array );
  14036. return z;
  14037. }
  14038. setZ( index, z ) {
  14039. if ( this.normalized ) z = normalize( z, this.array );
  14040. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14041. return this;
  14042. }
  14043. getW( index ) {
  14044. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14045. if ( this.normalized ) w = denormalize( w, this.array );
  14046. return w;
  14047. }
  14048. setW( index, w ) {
  14049. if ( this.normalized ) w = normalize( w, this.array );
  14050. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14051. return this;
  14052. }
  14053. setXY( index, x, y ) {
  14054. index *= this.itemSize;
  14055. if ( this.normalized ) {
  14056. x = normalize( x, this.array );
  14057. y = normalize( y, this.array );
  14058. }
  14059. this.array[ index + 0 ] = toHalfFloat( x );
  14060. this.array[ index + 1 ] = toHalfFloat( y );
  14061. return this;
  14062. }
  14063. setXYZ( index, x, y, z ) {
  14064. index *= this.itemSize;
  14065. if ( this.normalized ) {
  14066. x = normalize( x, this.array );
  14067. y = normalize( y, this.array );
  14068. z = normalize( z, this.array );
  14069. }
  14070. this.array[ index + 0 ] = toHalfFloat( x );
  14071. this.array[ index + 1 ] = toHalfFloat( y );
  14072. this.array[ index + 2 ] = toHalfFloat( z );
  14073. return this;
  14074. }
  14075. setXYZW( index, x, y, z, w ) {
  14076. index *= this.itemSize;
  14077. if ( this.normalized ) {
  14078. x = normalize( x, this.array );
  14079. y = normalize( y, this.array );
  14080. z = normalize( z, this.array );
  14081. w = normalize( w, this.array );
  14082. }
  14083. this.array[ index + 0 ] = toHalfFloat( x );
  14084. this.array[ index + 1 ] = toHalfFloat( y );
  14085. this.array[ index + 2 ] = toHalfFloat( z );
  14086. this.array[ index + 3 ] = toHalfFloat( w );
  14087. return this;
  14088. }
  14089. }
  14090. /**
  14091. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14092. * a plain `Array` instance.
  14093. *
  14094. * @augments BufferAttribute
  14095. */
  14096. class Float32BufferAttribute extends BufferAttribute {
  14097. /**
  14098. * Constructs a new buffer attribute.
  14099. *
  14100. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14101. * @param {number} itemSize - The item size.
  14102. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14103. */
  14104. constructor( array, itemSize, normalized ) {
  14105. super( new Float32Array( array ), itemSize, normalized );
  14106. }
  14107. }
  14108. let _id$1 = 0;
  14109. const _m1 = /*@__PURE__*/ new Matrix4();
  14110. const _obj = /*@__PURE__*/ new Object3D();
  14111. const _offset = /*@__PURE__*/ new Vector3();
  14112. const _box$2 = /*@__PURE__*/ new Box3();
  14113. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14114. const _vector$8 = /*@__PURE__*/ new Vector3();
  14115. /**
  14116. * A representation of mesh, line, or point geometry. Includes vertex
  14117. * positions, face indices, normals, colors, UVs, and custom attributes
  14118. * within buffers, reducing the cost of passing all this data to the GPU.
  14119. *
  14120. * ```js
  14121. * const geometry = new THREE.BufferGeometry();
  14122. * // create a simple square shape. We duplicate the top left and bottom right
  14123. * // vertices because each vertex needs to appear once per triangle.
  14124. * const vertices = new Float32Array( [
  14125. * -1.0, -1.0, 1.0, // v0
  14126. * 1.0, -1.0, 1.0, // v1
  14127. * 1.0, 1.0, 1.0, // v2
  14128. *
  14129. * 1.0, 1.0, 1.0, // v3
  14130. * -1.0, 1.0, 1.0, // v4
  14131. * -1.0, -1.0, 1.0 // v5
  14132. * ] );
  14133. * // itemSize = 3 because there are 3 values (components) per vertex
  14134. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14135. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14136. * const mesh = new THREE.Mesh( geometry, material );
  14137. * ```
  14138. *
  14139. * @augments EventDispatcher
  14140. */
  14141. class BufferGeometry extends EventDispatcher {
  14142. /**
  14143. * Constructs a new geometry.
  14144. */
  14145. constructor() {
  14146. super();
  14147. /**
  14148. * This flag can be used for type testing.
  14149. *
  14150. * @type {boolean}
  14151. * @readonly
  14152. * @default true
  14153. */
  14154. this.isBufferGeometry = true;
  14155. /**
  14156. * The ID of the geometry.
  14157. *
  14158. * @name BufferGeometry#id
  14159. * @type {number}
  14160. * @readonly
  14161. */
  14162. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14163. /**
  14164. * The UUID of the geometry.
  14165. *
  14166. * @type {string}
  14167. * @readonly
  14168. */
  14169. this.uuid = generateUUID();
  14170. /**
  14171. * The name of the geometry.
  14172. *
  14173. * @type {string}
  14174. */
  14175. this.name = '';
  14176. this.type = 'BufferGeometry';
  14177. /**
  14178. * Allows for vertices to be re-used across multiple triangles; this is
  14179. * called using "indexed triangles". Each triangle is associated with the
  14180. * indices of three vertices. This attribute therefore stores the index of
  14181. * each vertex for each triangular face. If this attribute is not set, the
  14182. * renderer assumes that each three contiguous positions represent a single triangle.
  14183. *
  14184. * @type {?BufferAttribute}
  14185. * @default null
  14186. */
  14187. this.index = null;
  14188. /**
  14189. * A (storage) buffer attribute which was generated with a compute shader and
  14190. * now defines indirect draw calls.
  14191. *
  14192. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14193. *
  14194. * @type {?BufferAttribute}
  14195. * @default null
  14196. */
  14197. this.indirect = null;
  14198. /**
  14199. * This dictionary has as id the name of the attribute to be set and as value
  14200. * the buffer attribute to set it to. Rather than accessing this property directly,
  14201. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14202. *
  14203. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14204. */
  14205. this.attributes = {};
  14206. /**
  14207. * This dictionary holds the morph targets of the geometry.
  14208. *
  14209. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14210. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14211. *
  14212. * @type {Object}
  14213. */
  14214. this.morphAttributes = {};
  14215. /**
  14216. * Used to control the morph target behavior; when set to `true`, the morph
  14217. * target data is treated as relative offsets, rather than as absolute
  14218. * positions/normals.
  14219. *
  14220. * @type {boolean}
  14221. * @default false
  14222. */
  14223. this.morphTargetsRelative = false;
  14224. /**
  14225. * Split the geometry into groups, each of which will be rendered in a
  14226. * separate draw call. This allows an array of materials to be used with the geometry.
  14227. *
  14228. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14229. *
  14230. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14231. * indices, and must not leave vertices or indices unused.
  14232. *
  14233. * @type {Array<Object>}
  14234. */
  14235. this.groups = [];
  14236. /**
  14237. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14238. *
  14239. * @type {Box3}
  14240. * @default null
  14241. */
  14242. this.boundingBox = null;
  14243. /**
  14244. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14245. *
  14246. * @type {Sphere}
  14247. * @default null
  14248. */
  14249. this.boundingSphere = null;
  14250. /**
  14251. * Determines the part of the geometry to render. This should not be set directly,
  14252. * instead use `setDrawRange()`.
  14253. *
  14254. * @type {{start:number,count:number}}
  14255. */
  14256. this.drawRange = { start: 0, count: Infinity };
  14257. /**
  14258. * An object that can be used to store custom data about the geometry.
  14259. * It should not hold references to functions as these will not be cloned.
  14260. *
  14261. * @type {Object}
  14262. */
  14263. this.userData = {};
  14264. }
  14265. /**
  14266. * Returns the index of this geometry.
  14267. *
  14268. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14269. */
  14270. getIndex() {
  14271. return this.index;
  14272. }
  14273. /**
  14274. * Sets the given index to this geometry.
  14275. *
  14276. * @param {Array<number>|BufferAttribute} index - The index to set.
  14277. * @return {BufferGeometry} A reference to this instance.
  14278. */
  14279. setIndex( index ) {
  14280. if ( Array.isArray( index ) ) {
  14281. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14282. } else {
  14283. this.index = index;
  14284. }
  14285. return this;
  14286. }
  14287. /**
  14288. * Sets the given indirect attribute to this geometry.
  14289. *
  14290. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14291. * @return {BufferGeometry} A reference to this instance.
  14292. */
  14293. setIndirect( indirect ) {
  14294. this.indirect = indirect;
  14295. return this;
  14296. }
  14297. /**
  14298. * Returns the indirect attribute of this geometry.
  14299. *
  14300. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14301. */
  14302. getIndirect() {
  14303. return this.indirect;
  14304. }
  14305. /**
  14306. * Returns the buffer attribute for the given name.
  14307. *
  14308. * @param {string} name - The attribute name.
  14309. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14310. * Returns `undefined` if not attribute has been found.
  14311. */
  14312. getAttribute( name ) {
  14313. return this.attributes[ name ];
  14314. }
  14315. /**
  14316. * Sets the given attribute for the given name.
  14317. *
  14318. * @param {string} name - The attribute name.
  14319. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14320. * @return {BufferGeometry} A reference to this instance.
  14321. */
  14322. setAttribute( name, attribute ) {
  14323. this.attributes[ name ] = attribute;
  14324. return this;
  14325. }
  14326. /**
  14327. * Deletes the attribute for the given name.
  14328. *
  14329. * @param {string} name - The attribute name to delete.
  14330. * @return {BufferGeometry} A reference to this instance.
  14331. */
  14332. deleteAttribute( name ) {
  14333. delete this.attributes[ name ];
  14334. return this;
  14335. }
  14336. /**
  14337. * Returns `true` if this geometry has an attribute for the given name.
  14338. *
  14339. * @param {string} name - The attribute name.
  14340. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14341. */
  14342. hasAttribute( name ) {
  14343. return this.attributes[ name ] !== undefined;
  14344. }
  14345. /**
  14346. * Adds a group to this geometry.
  14347. *
  14348. * @param {number} start - The first element in this draw call. That is the first
  14349. * vertex for non-indexed geometry, otherwise the first triangle index.
  14350. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14351. * @param {number} [materialIndex=0] - The material array index to use.
  14352. */
  14353. addGroup( start, count, materialIndex = 0 ) {
  14354. this.groups.push( {
  14355. start: start,
  14356. count: count,
  14357. materialIndex: materialIndex
  14358. } );
  14359. }
  14360. /**
  14361. * Clears all groups.
  14362. */
  14363. clearGroups() {
  14364. this.groups = [];
  14365. }
  14366. /**
  14367. * Sets the draw range for this geometry.
  14368. *
  14369. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14370. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14371. * For indexed BufferGeometry, `count` is the number of indices to render.
  14372. */
  14373. setDrawRange( start, count ) {
  14374. this.drawRange.start = start;
  14375. this.drawRange.count = count;
  14376. }
  14377. /**
  14378. * Applies the given 4x4 transformation matrix to the geometry.
  14379. *
  14380. * @param {Matrix4} matrix - The matrix to apply.
  14381. * @return {BufferGeometry} A reference to this instance.
  14382. */
  14383. applyMatrix4( matrix ) {
  14384. const position = this.attributes.position;
  14385. if ( position !== undefined ) {
  14386. position.applyMatrix4( matrix );
  14387. position.needsUpdate = true;
  14388. }
  14389. const normal = this.attributes.normal;
  14390. if ( normal !== undefined ) {
  14391. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14392. normal.applyNormalMatrix( normalMatrix );
  14393. normal.needsUpdate = true;
  14394. }
  14395. const tangent = this.attributes.tangent;
  14396. if ( tangent !== undefined ) {
  14397. tangent.transformDirection( matrix );
  14398. tangent.needsUpdate = true;
  14399. }
  14400. if ( this.boundingBox !== null ) {
  14401. this.computeBoundingBox();
  14402. }
  14403. if ( this.boundingSphere !== null ) {
  14404. this.computeBoundingSphere();
  14405. }
  14406. return this;
  14407. }
  14408. /**
  14409. * Applies the rotation represented by the Quaternion to the geometry.
  14410. *
  14411. * @param {Quaternion} q - The Quaternion to apply.
  14412. * @return {BufferGeometry} A reference to this instance.
  14413. */
  14414. applyQuaternion( q ) {
  14415. _m1.makeRotationFromQuaternion( q );
  14416. this.applyMatrix4( _m1 );
  14417. return this;
  14418. }
  14419. /**
  14420. * Rotates the geometry about the X axis. This is typically done as a one time
  14421. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14422. * real-time mesh rotation.
  14423. *
  14424. * @param {number} angle - The angle in radians.
  14425. * @return {BufferGeometry} A reference to this instance.
  14426. */
  14427. rotateX( angle ) {
  14428. // rotate geometry around world x-axis
  14429. _m1.makeRotationX( angle );
  14430. this.applyMatrix4( _m1 );
  14431. return this;
  14432. }
  14433. /**
  14434. * Rotates the geometry about the Y axis. This is typically done as a one time
  14435. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14436. * real-time mesh rotation.
  14437. *
  14438. * @param {number} angle - The angle in radians.
  14439. * @return {BufferGeometry} A reference to this instance.
  14440. */
  14441. rotateY( angle ) {
  14442. // rotate geometry around world y-axis
  14443. _m1.makeRotationY( angle );
  14444. this.applyMatrix4( _m1 );
  14445. return this;
  14446. }
  14447. /**
  14448. * Rotates the geometry about the Z axis. This is typically done as a one time
  14449. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14450. * real-time mesh rotation.
  14451. *
  14452. * @param {number} angle - The angle in radians.
  14453. * @return {BufferGeometry} A reference to this instance.
  14454. */
  14455. rotateZ( angle ) {
  14456. // rotate geometry around world z-axis
  14457. _m1.makeRotationZ( angle );
  14458. this.applyMatrix4( _m1 );
  14459. return this;
  14460. }
  14461. /**
  14462. * Translates the geometry. This is typically done as a one time
  14463. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14464. * real-time mesh rotation.
  14465. *
  14466. * @param {number} x - The x offset.
  14467. * @param {number} y - The y offset.
  14468. * @param {number} z - The z offset.
  14469. * @return {BufferGeometry} A reference to this instance.
  14470. */
  14471. translate( x, y, z ) {
  14472. // translate geometry
  14473. _m1.makeTranslation( x, y, z );
  14474. this.applyMatrix4( _m1 );
  14475. return this;
  14476. }
  14477. /**
  14478. * Scales the geometry. This is typically done as a one time
  14479. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14480. * real-time mesh rotation.
  14481. *
  14482. * @param {number} x - The x scale.
  14483. * @param {number} y - The y scale.
  14484. * @param {number} z - The z scale.
  14485. * @return {BufferGeometry} A reference to this instance.
  14486. */
  14487. scale( x, y, z ) {
  14488. // scale geometry
  14489. _m1.makeScale( x, y, z );
  14490. this.applyMatrix4( _m1 );
  14491. return this;
  14492. }
  14493. /**
  14494. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14495. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14496. * real-time mesh rotation.
  14497. *
  14498. * @param {Vector3} vector - The target point.
  14499. * @return {BufferGeometry} A reference to this instance.
  14500. */
  14501. lookAt( vector ) {
  14502. _obj.lookAt( vector );
  14503. _obj.updateMatrix();
  14504. this.applyMatrix4( _obj.matrix );
  14505. return this;
  14506. }
  14507. /**
  14508. * Center the geometry based on its bounding box.
  14509. *
  14510. * @return {BufferGeometry} A reference to this instance.
  14511. */
  14512. center() {
  14513. this.computeBoundingBox();
  14514. this.boundingBox.getCenter( _offset ).negate();
  14515. this.translate( _offset.x, _offset.y, _offset.z );
  14516. return this;
  14517. }
  14518. /**
  14519. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14520. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14521. * set to `0`.
  14522. *
  14523. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14524. * data from the array. The length of the array must match the vertex count.
  14525. *
  14526. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14527. * @return {BufferGeometry} A reference to this instance.
  14528. */
  14529. setFromPoints( points ) {
  14530. const positionAttribute = this.getAttribute( 'position' );
  14531. if ( positionAttribute === undefined ) {
  14532. const position = [];
  14533. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14534. const point = points[ i ];
  14535. position.push( point.x, point.y, point.z || 0 );
  14536. }
  14537. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14538. } else {
  14539. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14540. for ( let i = 0; i < l; i ++ ) {
  14541. const point = points[ i ];
  14542. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14543. }
  14544. if ( points.length > positionAttribute.count ) {
  14545. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14546. }
  14547. positionAttribute.needsUpdate = true;
  14548. }
  14549. return this;
  14550. }
  14551. /**
  14552. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14553. * The bounding box is not computed by the engine; it must be computed by your app.
  14554. * You may need to recompute the bounding box if the geometry vertices are modified.
  14555. */
  14556. computeBoundingBox() {
  14557. if ( this.boundingBox === null ) {
  14558. this.boundingBox = new Box3();
  14559. }
  14560. const position = this.attributes.position;
  14561. const morphAttributesPosition = this.morphAttributes.position;
  14562. if ( position && position.isGLBufferAttribute ) {
  14563. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14564. this.boundingBox.set(
  14565. new Vector3( - Infinity, - Infinity, - Infinity ),
  14566. new Vector3( + Infinity, + Infinity, + Infinity )
  14567. );
  14568. return;
  14569. }
  14570. if ( position !== undefined ) {
  14571. this.boundingBox.setFromBufferAttribute( position );
  14572. // process morph attributes if present
  14573. if ( morphAttributesPosition ) {
  14574. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14575. const morphAttribute = morphAttributesPosition[ i ];
  14576. _box$2.setFromBufferAttribute( morphAttribute );
  14577. if ( this.morphTargetsRelative ) {
  14578. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14579. this.boundingBox.expandByPoint( _vector$8 );
  14580. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14581. this.boundingBox.expandByPoint( _vector$8 );
  14582. } else {
  14583. this.boundingBox.expandByPoint( _box$2.min );
  14584. this.boundingBox.expandByPoint( _box$2.max );
  14585. }
  14586. }
  14587. }
  14588. } else {
  14589. this.boundingBox.makeEmpty();
  14590. }
  14591. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14592. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14593. }
  14594. }
  14595. /**
  14596. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14597. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14598. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14599. */
  14600. computeBoundingSphere() {
  14601. if ( this.boundingSphere === null ) {
  14602. this.boundingSphere = new Sphere();
  14603. }
  14604. const position = this.attributes.position;
  14605. const morphAttributesPosition = this.morphAttributes.position;
  14606. if ( position && position.isGLBufferAttribute ) {
  14607. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14608. this.boundingSphere.set( new Vector3(), Infinity );
  14609. return;
  14610. }
  14611. if ( position ) {
  14612. // first, find the center of the bounding sphere
  14613. const center = this.boundingSphere.center;
  14614. _box$2.setFromBufferAttribute( position );
  14615. // process morph attributes if present
  14616. if ( morphAttributesPosition ) {
  14617. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14618. const morphAttribute = morphAttributesPosition[ i ];
  14619. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14620. if ( this.morphTargetsRelative ) {
  14621. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14622. _box$2.expandByPoint( _vector$8 );
  14623. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14624. _box$2.expandByPoint( _vector$8 );
  14625. } else {
  14626. _box$2.expandByPoint( _boxMorphTargets.min );
  14627. _box$2.expandByPoint( _boxMorphTargets.max );
  14628. }
  14629. }
  14630. }
  14631. _box$2.getCenter( center );
  14632. // second, try to find a boundingSphere with a radius smaller than the
  14633. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14634. let maxRadiusSq = 0;
  14635. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14636. _vector$8.fromBufferAttribute( position, i );
  14637. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14638. }
  14639. // process morph attributes if present
  14640. if ( morphAttributesPosition ) {
  14641. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14642. const morphAttribute = morphAttributesPosition[ i ];
  14643. const morphTargetsRelative = this.morphTargetsRelative;
  14644. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14645. _vector$8.fromBufferAttribute( morphAttribute, j );
  14646. if ( morphTargetsRelative ) {
  14647. _offset.fromBufferAttribute( position, j );
  14648. _vector$8.add( _offset );
  14649. }
  14650. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14651. }
  14652. }
  14653. }
  14654. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14655. if ( isNaN( this.boundingSphere.radius ) ) {
  14656. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14657. }
  14658. }
  14659. }
  14660. /**
  14661. * Calculates and adds a tangent attribute to this geometry.
  14662. *
  14663. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14664. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14665. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14666. */
  14667. computeTangents() {
  14668. const index = this.index;
  14669. const attributes = this.attributes;
  14670. // based on http://www.terathon.com/code/tangent.html
  14671. // (per vertex tangents)
  14672. if ( index === null ||
  14673. attributes.position === undefined ||
  14674. attributes.normal === undefined ||
  14675. attributes.uv === undefined ) {
  14676. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14677. return;
  14678. }
  14679. const positionAttribute = attributes.position;
  14680. const normalAttribute = attributes.normal;
  14681. const uvAttribute = attributes.uv;
  14682. if ( this.hasAttribute( 'tangent' ) === false ) {
  14683. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14684. }
  14685. const tangentAttribute = this.getAttribute( 'tangent' );
  14686. const tan1 = [], tan2 = [];
  14687. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14688. tan1[ i ] = new Vector3();
  14689. tan2[ i ] = new Vector3();
  14690. }
  14691. const vA = new Vector3(),
  14692. vB = new Vector3(),
  14693. vC = new Vector3(),
  14694. uvA = new Vector2(),
  14695. uvB = new Vector2(),
  14696. uvC = new Vector2(),
  14697. sdir = new Vector3(),
  14698. tdir = new Vector3();
  14699. function handleTriangle( a, b, c ) {
  14700. vA.fromBufferAttribute( positionAttribute, a );
  14701. vB.fromBufferAttribute( positionAttribute, b );
  14702. vC.fromBufferAttribute( positionAttribute, c );
  14703. uvA.fromBufferAttribute( uvAttribute, a );
  14704. uvB.fromBufferAttribute( uvAttribute, b );
  14705. uvC.fromBufferAttribute( uvAttribute, c );
  14706. vB.sub( vA );
  14707. vC.sub( vA );
  14708. uvB.sub( uvA );
  14709. uvC.sub( uvA );
  14710. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14711. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14712. if ( ! isFinite( r ) ) return;
  14713. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14714. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14715. tan1[ a ].add( sdir );
  14716. tan1[ b ].add( sdir );
  14717. tan1[ c ].add( sdir );
  14718. tan2[ a ].add( tdir );
  14719. tan2[ b ].add( tdir );
  14720. tan2[ c ].add( tdir );
  14721. }
  14722. let groups = this.groups;
  14723. if ( groups.length === 0 ) {
  14724. groups = [ {
  14725. start: 0,
  14726. count: index.count
  14727. } ];
  14728. }
  14729. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14730. const group = groups[ i ];
  14731. const start = group.start;
  14732. const count = group.count;
  14733. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14734. handleTriangle(
  14735. index.getX( j + 0 ),
  14736. index.getX( j + 1 ),
  14737. index.getX( j + 2 )
  14738. );
  14739. }
  14740. }
  14741. const tmp = new Vector3(), tmp2 = new Vector3();
  14742. const n = new Vector3(), n2 = new Vector3();
  14743. function handleVertex( v ) {
  14744. n.fromBufferAttribute( normalAttribute, v );
  14745. n2.copy( n );
  14746. const t = tan1[ v ];
  14747. // Gram-Schmidt orthogonalize
  14748. tmp.copy( t );
  14749. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14750. // Calculate handedness
  14751. tmp2.crossVectors( n2, t );
  14752. const test = tmp2.dot( tan2[ v ] );
  14753. const w = ( test < 0.0 ) ? -1 : 1.0;
  14754. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14755. }
  14756. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14757. const group = groups[ i ];
  14758. const start = group.start;
  14759. const count = group.count;
  14760. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14761. handleVertex( index.getX( j + 0 ) );
  14762. handleVertex( index.getX( j + 1 ) );
  14763. handleVertex( index.getX( j + 2 ) );
  14764. }
  14765. }
  14766. }
  14767. /**
  14768. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14769. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14770. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14771. * to be the same as the face normal.
  14772. */
  14773. computeVertexNormals() {
  14774. const index = this.index;
  14775. const positionAttribute = this.getAttribute( 'position' );
  14776. if ( positionAttribute !== undefined ) {
  14777. let normalAttribute = this.getAttribute( 'normal' );
  14778. if ( normalAttribute === undefined ) {
  14779. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14780. this.setAttribute( 'normal', normalAttribute );
  14781. } else {
  14782. // reset existing normals to zero
  14783. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14784. normalAttribute.setXYZ( i, 0, 0, 0 );
  14785. }
  14786. }
  14787. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14788. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14789. const cb = new Vector3(), ab = new Vector3();
  14790. // indexed elements
  14791. if ( index ) {
  14792. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14793. const vA = index.getX( i + 0 );
  14794. const vB = index.getX( i + 1 );
  14795. const vC = index.getX( i + 2 );
  14796. pA.fromBufferAttribute( positionAttribute, vA );
  14797. pB.fromBufferAttribute( positionAttribute, vB );
  14798. pC.fromBufferAttribute( positionAttribute, vC );
  14799. cb.subVectors( pC, pB );
  14800. ab.subVectors( pA, pB );
  14801. cb.cross( ab );
  14802. nA.fromBufferAttribute( normalAttribute, vA );
  14803. nB.fromBufferAttribute( normalAttribute, vB );
  14804. nC.fromBufferAttribute( normalAttribute, vC );
  14805. nA.add( cb );
  14806. nB.add( cb );
  14807. nC.add( cb );
  14808. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14809. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14810. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14811. }
  14812. } else {
  14813. // non-indexed elements (unconnected triangle soup)
  14814. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14815. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14816. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14817. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14818. cb.subVectors( pC, pB );
  14819. ab.subVectors( pA, pB );
  14820. cb.cross( ab );
  14821. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14822. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14823. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14824. }
  14825. }
  14826. this.normalizeNormals();
  14827. normalAttribute.needsUpdate = true;
  14828. }
  14829. }
  14830. /**
  14831. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14832. * correct lighting on the geometry surfaces.
  14833. */
  14834. normalizeNormals() {
  14835. const normals = this.attributes.normal;
  14836. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14837. _vector$8.fromBufferAttribute( normals, i );
  14838. _vector$8.normalize();
  14839. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14840. }
  14841. }
  14842. /**
  14843. * Return a new non-index version of this indexed geometry. If the geometry
  14844. * is already non-indexed, the method is a NOOP.
  14845. *
  14846. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14847. */
  14848. toNonIndexed() {
  14849. function convertBufferAttribute( attribute, indices ) {
  14850. const array = attribute.array;
  14851. const itemSize = attribute.itemSize;
  14852. const normalized = attribute.normalized;
  14853. const array2 = new array.constructor( indices.length * itemSize );
  14854. let index = 0, index2 = 0;
  14855. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14856. if ( attribute.isInterleavedBufferAttribute ) {
  14857. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14858. } else {
  14859. index = indices[ i ] * itemSize;
  14860. }
  14861. for ( let j = 0; j < itemSize; j ++ ) {
  14862. array2[ index2 ++ ] = array[ index ++ ];
  14863. }
  14864. }
  14865. return new BufferAttribute( array2, itemSize, normalized );
  14866. }
  14867. //
  14868. if ( this.index === null ) {
  14869. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14870. return this;
  14871. }
  14872. const geometry2 = new BufferGeometry();
  14873. const indices = this.index.array;
  14874. const attributes = this.attributes;
  14875. // attributes
  14876. for ( const name in attributes ) {
  14877. const attribute = attributes[ name ];
  14878. const newAttribute = convertBufferAttribute( attribute, indices );
  14879. geometry2.setAttribute( name, newAttribute );
  14880. }
  14881. // morph attributes
  14882. const morphAttributes = this.morphAttributes;
  14883. for ( const name in morphAttributes ) {
  14884. const morphArray = [];
  14885. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14886. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14887. const attribute = morphAttribute[ i ];
  14888. const newAttribute = convertBufferAttribute( attribute, indices );
  14889. morphArray.push( newAttribute );
  14890. }
  14891. geometry2.morphAttributes[ name ] = morphArray;
  14892. }
  14893. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14894. // groups
  14895. const groups = this.groups;
  14896. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14897. const group = groups[ i ];
  14898. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14899. }
  14900. return geometry2;
  14901. }
  14902. /**
  14903. * Serializes the geometry into JSON.
  14904. *
  14905. * @return {Object} A JSON object representing the serialized geometry.
  14906. */
  14907. toJSON() {
  14908. const data = {
  14909. metadata: {
  14910. version: 4.7,
  14911. type: 'BufferGeometry',
  14912. generator: 'BufferGeometry.toJSON'
  14913. }
  14914. };
  14915. // standard BufferGeometry serialization
  14916. data.uuid = this.uuid;
  14917. data.type = this.type;
  14918. if ( this.name !== '' ) data.name = this.name;
  14919. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14920. if ( this.parameters !== undefined ) {
  14921. const parameters = this.parameters;
  14922. for ( const key in parameters ) {
  14923. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14924. }
  14925. return data;
  14926. }
  14927. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14928. data.data = { attributes: {} };
  14929. const index = this.index;
  14930. if ( index !== null ) {
  14931. data.data.index = {
  14932. type: index.array.constructor.name,
  14933. array: Array.prototype.slice.call( index.array )
  14934. };
  14935. }
  14936. const attributes = this.attributes;
  14937. for ( const key in attributes ) {
  14938. const attribute = attributes[ key ];
  14939. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14940. }
  14941. const morphAttributes = {};
  14942. let hasMorphAttributes = false;
  14943. for ( const key in this.morphAttributes ) {
  14944. const attributeArray = this.morphAttributes[ key ];
  14945. const array = [];
  14946. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14947. const attribute = attributeArray[ i ];
  14948. array.push( attribute.toJSON( data.data ) );
  14949. }
  14950. if ( array.length > 0 ) {
  14951. morphAttributes[ key ] = array;
  14952. hasMorphAttributes = true;
  14953. }
  14954. }
  14955. if ( hasMorphAttributes ) {
  14956. data.data.morphAttributes = morphAttributes;
  14957. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14958. }
  14959. const groups = this.groups;
  14960. if ( groups.length > 0 ) {
  14961. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14962. }
  14963. const boundingSphere = this.boundingSphere;
  14964. if ( boundingSphere !== null ) {
  14965. data.data.boundingSphere = boundingSphere.toJSON();
  14966. }
  14967. return data;
  14968. }
  14969. /**
  14970. * Returns a new geometry with copied values from this instance.
  14971. *
  14972. * @return {BufferGeometry} A clone of this instance.
  14973. */
  14974. clone() {
  14975. return new this.constructor().copy( this );
  14976. }
  14977. /**
  14978. * Copies the values of the given geometry to this instance.
  14979. *
  14980. * @param {BufferGeometry} source - The geometry to copy.
  14981. * @return {BufferGeometry} A reference to this instance.
  14982. */
  14983. copy( source ) {
  14984. // reset
  14985. this.index = null;
  14986. this.attributes = {};
  14987. this.morphAttributes = {};
  14988. this.groups = [];
  14989. this.boundingBox = null;
  14990. this.boundingSphere = null;
  14991. // used for storing cloned, shared data
  14992. const data = {};
  14993. // name
  14994. this.name = source.name;
  14995. // index
  14996. const index = source.index;
  14997. if ( index !== null ) {
  14998. this.setIndex( index.clone() );
  14999. }
  15000. // attributes
  15001. const attributes = source.attributes;
  15002. for ( const name in attributes ) {
  15003. const attribute = attributes[ name ];
  15004. this.setAttribute( name, attribute.clone( data ) );
  15005. }
  15006. // morph attributes
  15007. const morphAttributes = source.morphAttributes;
  15008. for ( const name in morphAttributes ) {
  15009. const array = [];
  15010. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15011. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15012. array.push( morphAttribute[ i ].clone( data ) );
  15013. }
  15014. this.morphAttributes[ name ] = array;
  15015. }
  15016. this.morphTargetsRelative = source.morphTargetsRelative;
  15017. // groups
  15018. const groups = source.groups;
  15019. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15020. const group = groups[ i ];
  15021. this.addGroup( group.start, group.count, group.materialIndex );
  15022. }
  15023. // bounding box
  15024. const boundingBox = source.boundingBox;
  15025. if ( boundingBox !== null ) {
  15026. this.boundingBox = boundingBox.clone();
  15027. }
  15028. // bounding sphere
  15029. const boundingSphere = source.boundingSphere;
  15030. if ( boundingSphere !== null ) {
  15031. this.boundingSphere = boundingSphere.clone();
  15032. }
  15033. // draw range
  15034. this.drawRange.start = source.drawRange.start;
  15035. this.drawRange.count = source.drawRange.count;
  15036. // user data
  15037. this.userData = source.userData;
  15038. return this;
  15039. }
  15040. /**
  15041. * Frees the GPU-related resources allocated by this instance. Call this
  15042. * method whenever this instance is no longer used in your app.
  15043. *
  15044. * @fires BufferGeometry#dispose
  15045. */
  15046. dispose() {
  15047. this.dispatchEvent( { type: 'dispose' } );
  15048. }
  15049. }
  15050. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15051. const _ray$3 = /*@__PURE__*/ new Ray();
  15052. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15053. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15054. const _vA$1 = /*@__PURE__*/ new Vector3();
  15055. const _vB$1 = /*@__PURE__*/ new Vector3();
  15056. const _vC$1 = /*@__PURE__*/ new Vector3();
  15057. const _tempA = /*@__PURE__*/ new Vector3();
  15058. const _morphA = /*@__PURE__*/ new Vector3();
  15059. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15060. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15061. /**
  15062. * Class representing triangular polygon mesh based objects.
  15063. *
  15064. * ```js
  15065. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15066. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15067. * const mesh = new THREE.Mesh( geometry, material );
  15068. * scene.add( mesh );
  15069. * ```
  15070. *
  15071. * @augments Object3D
  15072. */
  15073. class Mesh extends Object3D {
  15074. /**
  15075. * Constructs a new mesh.
  15076. *
  15077. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15078. * @param {Material|Array<Material>} [material] - The mesh material.
  15079. */
  15080. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15081. super();
  15082. /**
  15083. * This flag can be used for type testing.
  15084. *
  15085. * @type {boolean}
  15086. * @readonly
  15087. * @default true
  15088. */
  15089. this.isMesh = true;
  15090. this.type = 'Mesh';
  15091. /**
  15092. * The mesh geometry.
  15093. *
  15094. * @type {BufferGeometry}
  15095. */
  15096. this.geometry = geometry;
  15097. /**
  15098. * The mesh material.
  15099. *
  15100. * @type {Material|Array<Material>}
  15101. * @default MeshBasicMaterial
  15102. */
  15103. this.material = material;
  15104. /**
  15105. * A dictionary representing the morph targets in the geometry. The key is the
  15106. * morph targets name, the value its attribute index. This member is `undefined`
  15107. * by default and only set when morph targets are detected in the geometry.
  15108. *
  15109. * @type {Object<String,number>|undefined}
  15110. * @default undefined
  15111. */
  15112. this.morphTargetDictionary = undefined;
  15113. /**
  15114. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15115. * is applied. This member is `undefined` by default and only set when morph targets are
  15116. * detected in the geometry.
  15117. *
  15118. * @type {Array<number>|undefined}
  15119. * @default undefined
  15120. */
  15121. this.morphTargetInfluences = undefined;
  15122. /**
  15123. * The number of instances of this mesh.
  15124. * Can only be used with {@link WebGPURenderer}.
  15125. *
  15126. * @type {number}
  15127. * @default 1
  15128. */
  15129. this.count = 1;
  15130. this.updateMorphTargets();
  15131. }
  15132. copy( source, recursive ) {
  15133. super.copy( source, recursive );
  15134. if ( source.morphTargetInfluences !== undefined ) {
  15135. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15136. }
  15137. if ( source.morphTargetDictionary !== undefined ) {
  15138. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15139. }
  15140. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15141. this.geometry = source.geometry;
  15142. return this;
  15143. }
  15144. /**
  15145. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15146. * to make sure existing morph targets can influence this 3D object.
  15147. */
  15148. updateMorphTargets() {
  15149. const geometry = this.geometry;
  15150. const morphAttributes = geometry.morphAttributes;
  15151. const keys = Object.keys( morphAttributes );
  15152. if ( keys.length > 0 ) {
  15153. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15154. if ( morphAttribute !== undefined ) {
  15155. this.morphTargetInfluences = [];
  15156. this.morphTargetDictionary = {};
  15157. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15158. const name = morphAttribute[ m ].name || String( m );
  15159. this.morphTargetInfluences.push( 0 );
  15160. this.morphTargetDictionary[ name ] = m;
  15161. }
  15162. }
  15163. }
  15164. }
  15165. /**
  15166. * Returns the local-space position of the vertex at the given index, taking into
  15167. * account the current animation state of both morph targets and skinning.
  15168. *
  15169. * @param {number} index - The vertex index.
  15170. * @param {Vector3} target - The target object that is used to store the method's result.
  15171. * @return {Vector3} The vertex position in local space.
  15172. */
  15173. getVertexPosition( index, target ) {
  15174. const geometry = this.geometry;
  15175. const position = geometry.attributes.position;
  15176. const morphPosition = geometry.morphAttributes.position;
  15177. const morphTargetsRelative = geometry.morphTargetsRelative;
  15178. target.fromBufferAttribute( position, index );
  15179. const morphInfluences = this.morphTargetInfluences;
  15180. if ( morphPosition && morphInfluences ) {
  15181. _morphA.set( 0, 0, 0 );
  15182. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15183. const influence = morphInfluences[ i ];
  15184. const morphAttribute = morphPosition[ i ];
  15185. if ( influence === 0 ) continue;
  15186. _tempA.fromBufferAttribute( morphAttribute, index );
  15187. if ( morphTargetsRelative ) {
  15188. _morphA.addScaledVector( _tempA, influence );
  15189. } else {
  15190. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15191. }
  15192. }
  15193. target.add( _morphA );
  15194. }
  15195. return target;
  15196. }
  15197. /**
  15198. * Computes intersection points between a casted ray and this line.
  15199. *
  15200. * @param {Raycaster} raycaster - The raycaster.
  15201. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15202. */
  15203. raycast( raycaster, intersects ) {
  15204. const geometry = this.geometry;
  15205. const material = this.material;
  15206. const matrixWorld = this.matrixWorld;
  15207. if ( material === undefined ) return;
  15208. // test with bounding sphere in world space
  15209. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15210. _sphere$6.copy( geometry.boundingSphere );
  15211. _sphere$6.applyMatrix4( matrixWorld );
  15212. // check distance from ray origin to bounding sphere
  15213. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15214. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15215. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15216. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15217. }
  15218. // convert ray to local space of mesh
  15219. _inverseMatrix$3.copy( matrixWorld ).invert();
  15220. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15221. // test with bounding box in local space
  15222. if ( geometry.boundingBox !== null ) {
  15223. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15224. }
  15225. // test for intersections with geometry
  15226. this._computeIntersections( raycaster, intersects, _ray$3 );
  15227. }
  15228. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15229. let intersection;
  15230. const geometry = this.geometry;
  15231. const material = this.material;
  15232. const index = geometry.index;
  15233. const position = geometry.attributes.position;
  15234. const uv = geometry.attributes.uv;
  15235. const uv1 = geometry.attributes.uv1;
  15236. const normal = geometry.attributes.normal;
  15237. const groups = geometry.groups;
  15238. const drawRange = geometry.drawRange;
  15239. if ( index !== null ) {
  15240. // indexed buffer geometry
  15241. if ( Array.isArray( material ) ) {
  15242. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15243. const group = groups[ i ];
  15244. const groupMaterial = material[ group.materialIndex ];
  15245. const start = Math.max( group.start, drawRange.start );
  15246. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15247. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15248. const a = index.getX( j );
  15249. const b = index.getX( j + 1 );
  15250. const c = index.getX( j + 2 );
  15251. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15252. if ( intersection ) {
  15253. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15254. intersection.face.materialIndex = group.materialIndex;
  15255. intersects.push( intersection );
  15256. }
  15257. }
  15258. }
  15259. } else {
  15260. const start = Math.max( 0, drawRange.start );
  15261. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15262. for ( let i = start, il = end; i < il; i += 3 ) {
  15263. const a = index.getX( i );
  15264. const b = index.getX( i + 1 );
  15265. const c = index.getX( i + 2 );
  15266. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15267. if ( intersection ) {
  15268. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15269. intersects.push( intersection );
  15270. }
  15271. }
  15272. }
  15273. } else if ( position !== undefined ) {
  15274. // non-indexed buffer geometry
  15275. if ( Array.isArray( material ) ) {
  15276. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15277. const group = groups[ i ];
  15278. const groupMaterial = material[ group.materialIndex ];
  15279. const start = Math.max( group.start, drawRange.start );
  15280. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15281. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15282. const a = j;
  15283. const b = j + 1;
  15284. const c = j + 2;
  15285. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15286. if ( intersection ) {
  15287. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15288. intersection.face.materialIndex = group.materialIndex;
  15289. intersects.push( intersection );
  15290. }
  15291. }
  15292. }
  15293. } else {
  15294. const start = Math.max( 0, drawRange.start );
  15295. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15296. for ( let i = start, il = end; i < il; i += 3 ) {
  15297. const a = i;
  15298. const b = i + 1;
  15299. const c = i + 2;
  15300. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15301. if ( intersection ) {
  15302. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15303. intersects.push( intersection );
  15304. }
  15305. }
  15306. }
  15307. }
  15308. }
  15309. }
  15310. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15311. let intersect;
  15312. if ( material.side === BackSide ) {
  15313. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15314. } else {
  15315. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15316. }
  15317. if ( intersect === null ) return null;
  15318. _intersectionPointWorld.copy( point );
  15319. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15320. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15321. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15322. return {
  15323. distance: distance,
  15324. point: _intersectionPointWorld.clone(),
  15325. object: object
  15326. };
  15327. }
  15328. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15329. object.getVertexPosition( a, _vA$1 );
  15330. object.getVertexPosition( b, _vB$1 );
  15331. object.getVertexPosition( c, _vC$1 );
  15332. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15333. if ( intersection ) {
  15334. const barycoord = new Vector3();
  15335. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15336. if ( uv ) {
  15337. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15338. }
  15339. if ( uv1 ) {
  15340. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15341. }
  15342. if ( normal ) {
  15343. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15344. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15345. intersection.normal.multiplyScalar( -1 );
  15346. }
  15347. }
  15348. const face = {
  15349. a: a,
  15350. b: b,
  15351. c: c,
  15352. normal: new Vector3(),
  15353. materialIndex: 0
  15354. };
  15355. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15356. intersection.face = face;
  15357. intersection.barycoord = barycoord;
  15358. }
  15359. return intersection;
  15360. }
  15361. /**
  15362. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15363. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15364. * of the axes.
  15365. *
  15366. * ```js
  15367. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15368. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15369. * const cube = new THREE.Mesh( geometry, material );
  15370. * scene.add( cube );
  15371. * ```
  15372. *
  15373. * @augments BufferGeometry
  15374. */
  15375. class BoxGeometry extends BufferGeometry {
  15376. /**
  15377. * Constructs a new box geometry.
  15378. *
  15379. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15380. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15381. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15382. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15383. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15384. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15385. */
  15386. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15387. super();
  15388. this.type = 'BoxGeometry';
  15389. /**
  15390. * Holds the constructor parameters that have been
  15391. * used to generate the geometry. Any modification
  15392. * after instantiation does not change the geometry.
  15393. *
  15394. * @type {Object}
  15395. */
  15396. this.parameters = {
  15397. width: width,
  15398. height: height,
  15399. depth: depth,
  15400. widthSegments: widthSegments,
  15401. heightSegments: heightSegments,
  15402. depthSegments: depthSegments
  15403. };
  15404. const scope = this;
  15405. // segments
  15406. widthSegments = Math.floor( widthSegments );
  15407. heightSegments = Math.floor( heightSegments );
  15408. depthSegments = Math.floor( depthSegments );
  15409. // buffers
  15410. const indices = [];
  15411. const vertices = [];
  15412. const normals = [];
  15413. const uvs = [];
  15414. // helper variables
  15415. let numberOfVertices = 0;
  15416. let groupStart = 0;
  15417. // build each side of the box geometry
  15418. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15419. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15420. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15421. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15422. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15423. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15424. // build geometry
  15425. this.setIndex( indices );
  15426. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15427. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15428. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15429. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15430. const segmentWidth = width / gridX;
  15431. const segmentHeight = height / gridY;
  15432. const widthHalf = width / 2;
  15433. const heightHalf = height / 2;
  15434. const depthHalf = depth / 2;
  15435. const gridX1 = gridX + 1;
  15436. const gridY1 = gridY + 1;
  15437. let vertexCounter = 0;
  15438. let groupCount = 0;
  15439. const vector = new Vector3();
  15440. // generate vertices, normals and uvs
  15441. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15442. const y = iy * segmentHeight - heightHalf;
  15443. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15444. const x = ix * segmentWidth - widthHalf;
  15445. // set values to correct vector component
  15446. vector[ u ] = x * udir;
  15447. vector[ v ] = y * vdir;
  15448. vector[ w ] = depthHalf;
  15449. // now apply vector to vertex buffer
  15450. vertices.push( vector.x, vector.y, vector.z );
  15451. // set values to correct vector component
  15452. vector[ u ] = 0;
  15453. vector[ v ] = 0;
  15454. vector[ w ] = depth > 0 ? 1 : -1;
  15455. // now apply vector to normal buffer
  15456. normals.push( vector.x, vector.y, vector.z );
  15457. // uvs
  15458. uvs.push( ix / gridX );
  15459. uvs.push( 1 - ( iy / gridY ) );
  15460. // counters
  15461. vertexCounter += 1;
  15462. }
  15463. }
  15464. // indices
  15465. // 1. you need three indices to draw a single face
  15466. // 2. a single segment consists of two faces
  15467. // 3. so we need to generate six (2*3) indices per segment
  15468. for ( let iy = 0; iy < gridY; iy ++ ) {
  15469. for ( let ix = 0; ix < gridX; ix ++ ) {
  15470. const a = numberOfVertices + ix + gridX1 * iy;
  15471. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15472. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15473. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15474. // faces
  15475. indices.push( a, b, d );
  15476. indices.push( b, c, d );
  15477. // increase counter
  15478. groupCount += 6;
  15479. }
  15480. }
  15481. // add a group to the geometry. this will ensure multi material support
  15482. scope.addGroup( groupStart, groupCount, materialIndex );
  15483. // calculate new start value for groups
  15484. groupStart += groupCount;
  15485. // update total number of vertices
  15486. numberOfVertices += vertexCounter;
  15487. }
  15488. }
  15489. copy( source ) {
  15490. super.copy( source );
  15491. this.parameters = Object.assign( {}, source.parameters );
  15492. return this;
  15493. }
  15494. /**
  15495. * Factory method for creating an instance of this class from the given
  15496. * JSON object.
  15497. *
  15498. * @param {Object} data - A JSON object representing the serialized geometry.
  15499. * @return {BoxGeometry} A new instance.
  15500. */
  15501. static fromJSON( data ) {
  15502. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15503. }
  15504. }
  15505. // Uniform Utilities
  15506. function cloneUniforms( src ) {
  15507. const dst = {};
  15508. for ( const u in src ) {
  15509. dst[ u ] = {};
  15510. for ( const p in src[ u ] ) {
  15511. const property = src[ u ][ p ];
  15512. if ( property && ( property.isColor ||
  15513. property.isMatrix3 || property.isMatrix4 ||
  15514. property.isVector2 || property.isVector3 || property.isVector4 ||
  15515. property.isTexture || property.isQuaternion ) ) {
  15516. if ( property.isRenderTargetTexture ) {
  15517. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15518. dst[ u ][ p ] = null;
  15519. } else {
  15520. dst[ u ][ p ] = property.clone();
  15521. }
  15522. } else if ( Array.isArray( property ) ) {
  15523. dst[ u ][ p ] = property.slice();
  15524. } else {
  15525. dst[ u ][ p ] = property;
  15526. }
  15527. }
  15528. }
  15529. return dst;
  15530. }
  15531. function mergeUniforms( uniforms ) {
  15532. const merged = {};
  15533. for ( let u = 0; u < uniforms.length; u ++ ) {
  15534. const tmp = cloneUniforms( uniforms[ u ] );
  15535. for ( const p in tmp ) {
  15536. merged[ p ] = tmp[ p ];
  15537. }
  15538. }
  15539. return merged;
  15540. }
  15541. function cloneUniformsGroups( src ) {
  15542. const dst = [];
  15543. for ( let u = 0; u < src.length; u ++ ) {
  15544. dst.push( src[ u ].clone() );
  15545. }
  15546. return dst;
  15547. }
  15548. function getUnlitUniformColorSpace( renderer ) {
  15549. const currentRenderTarget = renderer.getRenderTarget();
  15550. if ( currentRenderTarget === null ) {
  15551. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15552. return renderer.outputColorSpace;
  15553. }
  15554. // https://github.com/mrdoob/three.js/issues/27868
  15555. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15556. return currentRenderTarget.texture.colorSpace;
  15557. }
  15558. return ColorManagement.workingColorSpace;
  15559. }
  15560. // Legacy
  15561. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15562. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15563. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15564. /**
  15565. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15566. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15567. * effect not included with any of the built-in materials.
  15568. *
  15569. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15570. *
  15571. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15572. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15573. * you don't want that, use {@link RawShaderMaterial} instead.
  15574. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15575. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15576. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15577. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15578. * - The loop variable has to be *i*.
  15579. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15580. * value of *i* for the given iteration and can be used in preprocessor
  15581. * statements.
  15582. *
  15583. * ```js
  15584. * const material = new THREE.ShaderMaterial( {
  15585. * uniforms: {
  15586. * time: { value: 1.0 },
  15587. * resolution: { value: new THREE.Vector2() }
  15588. * },
  15589. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15590. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15591. * } );
  15592. * ```
  15593. *
  15594. * @augments Material
  15595. */
  15596. class ShaderMaterial extends Material {
  15597. /**
  15598. * Constructs a new shader material.
  15599. *
  15600. * @param {Object} [parameters] - An object with one or more properties
  15601. * defining the material's appearance. Any property of the material
  15602. * (including any property from inherited materials) can be passed
  15603. * in here. Color values can be passed any type of value accepted
  15604. * by {@link Color#set}.
  15605. */
  15606. constructor( parameters ) {
  15607. super();
  15608. /**
  15609. * This flag can be used for type testing.
  15610. *
  15611. * @type {boolean}
  15612. * @readonly
  15613. * @default true
  15614. */
  15615. this.isShaderMaterial = true;
  15616. this.type = 'ShaderMaterial';
  15617. /**
  15618. * Defines custom constants using `#define` directives within the GLSL code
  15619. * for both the vertex shader and the fragment shader; each key/value pair
  15620. * yields another directive.
  15621. * ```js
  15622. * defines: {
  15623. * FOO: 15,
  15624. * BAR: true
  15625. * }
  15626. * ```
  15627. * Yields the lines:
  15628. * ```
  15629. * #define FOO 15
  15630. * #define BAR true
  15631. * ```
  15632. *
  15633. * @type {Object}
  15634. */
  15635. this.defines = {};
  15636. /**
  15637. * An object of the form:
  15638. * ```js
  15639. * {
  15640. * "uniform1": { value: 1.0 },
  15641. * "uniform2": { value: 2 }
  15642. * }
  15643. * ```
  15644. * specifying the uniforms to be passed to the shader code; keys are uniform
  15645. * names, values are definitions of the form
  15646. * ```
  15647. * {
  15648. * value: 1.0
  15649. * }
  15650. * ```
  15651. * where `value` is the value of the uniform. Names must match the name of
  15652. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15653. * on every frame, so updating the value of the uniform will immediately
  15654. * update the value available to the GLSL code.
  15655. *
  15656. * @type {Object}
  15657. */
  15658. this.uniforms = {};
  15659. /**
  15660. * An array holding uniforms groups for configuring UBOs.
  15661. *
  15662. * @type {Array<UniformsGroup>}
  15663. */
  15664. this.uniformsGroups = [];
  15665. /**
  15666. * Vertex shader GLSL code. This is the actual code for the shader.
  15667. *
  15668. * @type {string}
  15669. */
  15670. this.vertexShader = default_vertex;
  15671. /**
  15672. * Fragment shader GLSL code. This is the actual code for the shader.
  15673. *
  15674. * @type {string}
  15675. */
  15676. this.fragmentShader = default_fragment;
  15677. /**
  15678. * Controls line thickness or lines.
  15679. *
  15680. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15681. * width of one pixel.
  15682. *
  15683. * @type {number}
  15684. * @default 1
  15685. */
  15686. this.linewidth = 1;
  15687. /**
  15688. * Renders the geometry as a wireframe.
  15689. *
  15690. * @type {boolean}
  15691. * @default false
  15692. */
  15693. this.wireframe = false;
  15694. /**
  15695. * Controls the thickness of the wireframe.
  15696. *
  15697. * WebGL and WebGPU ignore this property and always render
  15698. * 1 pixel wide lines.
  15699. *
  15700. * @type {number}
  15701. * @default 1
  15702. */
  15703. this.wireframeLinewidth = 1;
  15704. /**
  15705. * Define whether the material color is affected by global fog settings; `true`
  15706. * to pass fog uniforms to the shader.
  15707. *
  15708. * @type {boolean}
  15709. * @default false
  15710. */
  15711. this.fog = false;
  15712. /**
  15713. * Defines whether this material uses lighting; `true` to pass uniform data
  15714. * related to lighting to this shader.
  15715. *
  15716. * @type {boolean}
  15717. * @default false
  15718. */
  15719. this.lights = false;
  15720. /**
  15721. * Defines whether this material supports clipping; `true` to let the renderer
  15722. * pass the clippingPlanes uniform.
  15723. *
  15724. * @type {boolean}
  15725. * @default false
  15726. */
  15727. this.clipping = false;
  15728. /**
  15729. * Overwritten and set to `true` by default.
  15730. *
  15731. * @type {boolean}
  15732. * @default true
  15733. */
  15734. this.forceSinglePass = true;
  15735. /**
  15736. * This object allows to enable certain WebGL 2 extensions.
  15737. *
  15738. * - clipCullDistance: set to `true` to use vertex shader clipping
  15739. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15740. *
  15741. * @type {{clipCullDistance:false,multiDraw:false}}
  15742. */
  15743. this.extensions = {
  15744. clipCullDistance: false, // set to use vertex shader clipping
  15745. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15746. };
  15747. /**
  15748. * When the rendered geometry doesn't include these attributes but the
  15749. * material does, these default values will be passed to the shaders. This
  15750. * avoids errors when buffer data is missing.
  15751. *
  15752. * - color: [ 1, 1, 1 ]
  15753. * - uv: [ 0, 0 ]
  15754. * - uv1: [ 0, 0 ]
  15755. *
  15756. * @type {Object}
  15757. */
  15758. this.defaultAttributeValues = {
  15759. 'color': [ 1, 1, 1 ],
  15760. 'uv': [ 0, 0 ],
  15761. 'uv1': [ 0, 0 ]
  15762. };
  15763. /**
  15764. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15765. * to bind a generic vertex index to an attribute variable.
  15766. *
  15767. * @type {string|undefined}
  15768. * @default undefined
  15769. */
  15770. this.index0AttributeName = undefined;
  15771. /**
  15772. * Can be used to force a uniform update while changing uniforms in
  15773. * {@link Object3D#onBeforeRender}.
  15774. *
  15775. * @type {boolean}
  15776. * @default false
  15777. */
  15778. this.uniformsNeedUpdate = false;
  15779. /**
  15780. * Defines the GLSL version of custom shader code.
  15781. *
  15782. * @type {?(GLSL1|GLSL3)}
  15783. * @default null
  15784. */
  15785. this.glslVersion = null;
  15786. if ( parameters !== undefined ) {
  15787. this.setValues( parameters );
  15788. }
  15789. }
  15790. copy( source ) {
  15791. super.copy( source );
  15792. this.fragmentShader = source.fragmentShader;
  15793. this.vertexShader = source.vertexShader;
  15794. this.uniforms = cloneUniforms( source.uniforms );
  15795. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15796. this.defines = Object.assign( {}, source.defines );
  15797. this.wireframe = source.wireframe;
  15798. this.wireframeLinewidth = source.wireframeLinewidth;
  15799. this.fog = source.fog;
  15800. this.lights = source.lights;
  15801. this.clipping = source.clipping;
  15802. this.extensions = Object.assign( {}, source.extensions );
  15803. this.glslVersion = source.glslVersion;
  15804. return this;
  15805. }
  15806. toJSON( meta ) {
  15807. const data = super.toJSON( meta );
  15808. data.glslVersion = this.glslVersion;
  15809. data.uniforms = {};
  15810. for ( const name in this.uniforms ) {
  15811. const uniform = this.uniforms[ name ];
  15812. const value = uniform.value;
  15813. if ( value && value.isTexture ) {
  15814. data.uniforms[ name ] = {
  15815. type: 't',
  15816. value: value.toJSON( meta ).uuid
  15817. };
  15818. } else if ( value && value.isColor ) {
  15819. data.uniforms[ name ] = {
  15820. type: 'c',
  15821. value: value.getHex()
  15822. };
  15823. } else if ( value && value.isVector2 ) {
  15824. data.uniforms[ name ] = {
  15825. type: 'v2',
  15826. value: value.toArray()
  15827. };
  15828. } else if ( value && value.isVector3 ) {
  15829. data.uniforms[ name ] = {
  15830. type: 'v3',
  15831. value: value.toArray()
  15832. };
  15833. } else if ( value && value.isVector4 ) {
  15834. data.uniforms[ name ] = {
  15835. type: 'v4',
  15836. value: value.toArray()
  15837. };
  15838. } else if ( value && value.isMatrix3 ) {
  15839. data.uniforms[ name ] = {
  15840. type: 'm3',
  15841. value: value.toArray()
  15842. };
  15843. } else if ( value && value.isMatrix4 ) {
  15844. data.uniforms[ name ] = {
  15845. type: 'm4',
  15846. value: value.toArray()
  15847. };
  15848. } else {
  15849. data.uniforms[ name ] = {
  15850. value: value
  15851. };
  15852. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15853. }
  15854. }
  15855. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15856. data.vertexShader = this.vertexShader;
  15857. data.fragmentShader = this.fragmentShader;
  15858. data.lights = this.lights;
  15859. data.clipping = this.clipping;
  15860. const extensions = {};
  15861. for ( const key in this.extensions ) {
  15862. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15863. }
  15864. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15865. return data;
  15866. }
  15867. }
  15868. /**
  15869. * Abstract base class for cameras. This class should always be inherited
  15870. * when you build a new camera.
  15871. *
  15872. * @abstract
  15873. * @augments Object3D
  15874. */
  15875. class Camera extends Object3D {
  15876. /**
  15877. * Constructs a new camera.
  15878. */
  15879. constructor() {
  15880. super();
  15881. /**
  15882. * This flag can be used for type testing.
  15883. *
  15884. * @type {boolean}
  15885. * @readonly
  15886. * @default true
  15887. */
  15888. this.isCamera = true;
  15889. this.type = 'Camera';
  15890. /**
  15891. * The flag that indicates whether the camera uses a reversed depth buffer.
  15892. *
  15893. * @type {boolean}
  15894. * @default false
  15895. */
  15896. this.reversedDepth = false;
  15897. /**
  15898. * The inverse of the camera's world matrix.
  15899. *
  15900. * @type {Matrix4}
  15901. */
  15902. this.matrixWorldInverse = new Matrix4();
  15903. /**
  15904. * The camera's projection matrix.
  15905. *
  15906. * @type {Matrix4}
  15907. */
  15908. this.projectionMatrix = new Matrix4();
  15909. /**
  15910. * The inverse of the camera's projection matrix.
  15911. *
  15912. * @type {Matrix4}
  15913. */
  15914. this.projectionMatrixInverse = new Matrix4();
  15915. /**
  15916. * The coordinate system in which the camera is used.
  15917. *
  15918. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15919. */
  15920. this.coordinateSystem = WebGLCoordinateSystem;
  15921. }
  15922. copy( source, recursive ) {
  15923. super.copy( source, recursive );
  15924. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15925. this.projectionMatrix.copy( source.projectionMatrix );
  15926. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15927. this.coordinateSystem = source.coordinateSystem;
  15928. return this;
  15929. }
  15930. /**
  15931. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15932. *
  15933. * This method is overwritten since cameras have a different forward vector compared to other
  15934. * 3D objects. A camera looks down its local, negative z-axis by default.
  15935. *
  15936. * @param {Vector3} target - The target vector the result is stored to.
  15937. * @return {Vector3} The 3D object's direction in world space.
  15938. */
  15939. getWorldDirection( target ) {
  15940. return super.getWorldDirection( target ).negate();
  15941. }
  15942. updateMatrixWorld( force ) {
  15943. super.updateMatrixWorld( force );
  15944. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15945. }
  15946. updateWorldMatrix( updateParents, updateChildren ) {
  15947. super.updateWorldMatrix( updateParents, updateChildren );
  15948. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15949. }
  15950. clone() {
  15951. return new this.constructor().copy( this );
  15952. }
  15953. }
  15954. const _v3$1 = /*@__PURE__*/ new Vector3();
  15955. const _minTarget = /*@__PURE__*/ new Vector2();
  15956. const _maxTarget = /*@__PURE__*/ new Vector2();
  15957. /**
  15958. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15959. *
  15960. * This projection mode is designed to mimic the way the human eye sees. It
  15961. * is the most common projection mode used for rendering a 3D scene.
  15962. *
  15963. * ```js
  15964. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15965. * scene.add( camera );
  15966. * ```
  15967. *
  15968. * @augments Camera
  15969. */
  15970. class PerspectiveCamera extends Camera {
  15971. /**
  15972. * Constructs a new perspective camera.
  15973. *
  15974. * @param {number} [fov=50] - The vertical field of view.
  15975. * @param {number} [aspect=1] - The aspect ratio.
  15976. * @param {number} [near=0.1] - The camera's near plane.
  15977. * @param {number} [far=2000] - The camera's far plane.
  15978. */
  15979. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15980. super();
  15981. /**
  15982. * This flag can be used for type testing.
  15983. *
  15984. * @type {boolean}
  15985. * @readonly
  15986. * @default true
  15987. */
  15988. this.isPerspectiveCamera = true;
  15989. this.type = 'PerspectiveCamera';
  15990. /**
  15991. * The vertical field of view, from bottom to top of view,
  15992. * in degrees.
  15993. *
  15994. * @type {number}
  15995. * @default 50
  15996. */
  15997. this.fov = fov;
  15998. /**
  15999. * The zoom factor of the camera.
  16000. *
  16001. * @type {number}
  16002. * @default 1
  16003. */
  16004. this.zoom = 1;
  16005. /**
  16006. * The camera's near plane. The valid range is greater than `0`
  16007. * and less than the current value of {@link PerspectiveCamera#far}.
  16008. *
  16009. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16010. * valid value for a perspective camera's near plane.
  16011. *
  16012. * @type {number}
  16013. * @default 0.1
  16014. */
  16015. this.near = near;
  16016. /**
  16017. * The camera's far plane. Must be greater than the
  16018. * current value of {@link PerspectiveCamera#near}.
  16019. *
  16020. * @type {number}
  16021. * @default 2000
  16022. */
  16023. this.far = far;
  16024. /**
  16025. * Object distance used for stereoscopy and depth-of-field effects. This
  16026. * parameter does not influence the projection matrix unless a
  16027. * {@link StereoCamera} is being used.
  16028. *
  16029. * @type {number}
  16030. * @default 10
  16031. */
  16032. this.focus = 10;
  16033. /**
  16034. * The aspect ratio, usually the canvas width / canvas height.
  16035. *
  16036. * @type {number}
  16037. * @default 1
  16038. */
  16039. this.aspect = aspect;
  16040. /**
  16041. * Represents the frustum window specification. This property should not be edited
  16042. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16043. *
  16044. * @type {?Object}
  16045. * @default null
  16046. */
  16047. this.view = null;
  16048. /**
  16049. * Film size used for the larger axis. Default is `35` (millimeters). This
  16050. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16051. * is set to a nonzero value.
  16052. *
  16053. * @type {number}
  16054. * @default 35
  16055. */
  16056. this.filmGauge = 35;
  16057. /**
  16058. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16059. *
  16060. * @type {number}
  16061. * @default 0
  16062. */
  16063. this.filmOffset = 0;
  16064. this.updateProjectionMatrix();
  16065. }
  16066. copy( source, recursive ) {
  16067. super.copy( source, recursive );
  16068. this.fov = source.fov;
  16069. this.zoom = source.zoom;
  16070. this.near = source.near;
  16071. this.far = source.far;
  16072. this.focus = source.focus;
  16073. this.aspect = source.aspect;
  16074. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16075. this.filmGauge = source.filmGauge;
  16076. this.filmOffset = source.filmOffset;
  16077. return this;
  16078. }
  16079. /**
  16080. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16081. *
  16082. * The default film gauge is 35, so that the focal length can be specified for
  16083. * a 35mm (full frame) camera.
  16084. *
  16085. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16086. */
  16087. setFocalLength( focalLength ) {
  16088. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16089. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16090. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16091. this.updateProjectionMatrix();
  16092. }
  16093. /**
  16094. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16095. * {@link PerspectiveCamera#filmGauge}.
  16096. *
  16097. * @return {number} The computed focal length.
  16098. */
  16099. getFocalLength() {
  16100. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16101. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16102. }
  16103. /**
  16104. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16105. *
  16106. * @return {number} The effective FOV.
  16107. */
  16108. getEffectiveFOV() {
  16109. return RAD2DEG * 2 * Math.atan(
  16110. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16111. }
  16112. /**
  16113. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16114. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16115. *
  16116. * @return {number} The film width.
  16117. */
  16118. getFilmWidth() {
  16119. // film not completely covered in portrait format (aspect < 1)
  16120. return this.filmGauge * Math.min( this.aspect, 1 );
  16121. }
  16122. /**
  16123. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16124. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16125. *
  16126. * @return {number} The film width.
  16127. */
  16128. getFilmHeight() {
  16129. // film not completely covered in landscape format (aspect > 1)
  16130. return this.filmGauge / Math.max( this.aspect, 1 );
  16131. }
  16132. /**
  16133. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16134. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16135. *
  16136. * @param {number} distance - The viewing distance.
  16137. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16138. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16139. */
  16140. getViewBounds( distance, minTarget, maxTarget ) {
  16141. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16142. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16143. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16144. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16145. }
  16146. /**
  16147. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16148. *
  16149. * @param {number} distance - The viewing distance.
  16150. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16151. * @returns {Vector2} The view size.
  16152. */
  16153. getViewSize( distance, target ) {
  16154. this.getViewBounds( distance, _minTarget, _maxTarget );
  16155. return target.subVectors( _maxTarget, _minTarget );
  16156. }
  16157. /**
  16158. * Sets an offset in a larger frustum. This is useful for multi-window or
  16159. * multi-monitor/multi-machine setups.
  16160. *
  16161. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16162. * the monitors are in grid like this
  16163. *```
  16164. * +---+---+---+
  16165. * | A | B | C |
  16166. * +---+---+---+
  16167. * | D | E | F |
  16168. * +---+---+---+
  16169. *```
  16170. * then for each monitor you would call it like this:
  16171. *```js
  16172. * const w = 1920;
  16173. * const h = 1080;
  16174. * const fullWidth = w * 3;
  16175. * const fullHeight = h * 2;
  16176. *
  16177. * // --A--
  16178. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16179. * // --B--
  16180. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16181. * // --C--
  16182. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16183. * // --D--
  16184. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16185. * // --E--
  16186. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16187. * // --F--
  16188. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16189. * ```
  16190. *
  16191. * Note there is no reason monitors have to be the same size or in a grid.
  16192. *
  16193. * @param {number} fullWidth - The full width of multiview setup.
  16194. * @param {number} fullHeight - The full height of multiview setup.
  16195. * @param {number} x - The horizontal offset of the subcamera.
  16196. * @param {number} y - The vertical offset of the subcamera.
  16197. * @param {number} width - The width of subcamera.
  16198. * @param {number} height - The height of subcamera.
  16199. */
  16200. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16201. this.aspect = fullWidth / fullHeight;
  16202. if ( this.view === null ) {
  16203. this.view = {
  16204. enabled: true,
  16205. fullWidth: 1,
  16206. fullHeight: 1,
  16207. offsetX: 0,
  16208. offsetY: 0,
  16209. width: 1,
  16210. height: 1
  16211. };
  16212. }
  16213. this.view.enabled = true;
  16214. this.view.fullWidth = fullWidth;
  16215. this.view.fullHeight = fullHeight;
  16216. this.view.offsetX = x;
  16217. this.view.offsetY = y;
  16218. this.view.width = width;
  16219. this.view.height = height;
  16220. this.updateProjectionMatrix();
  16221. }
  16222. /**
  16223. * Removes the view offset from the projection matrix.
  16224. */
  16225. clearViewOffset() {
  16226. if ( this.view !== null ) {
  16227. this.view.enabled = false;
  16228. }
  16229. this.updateProjectionMatrix();
  16230. }
  16231. /**
  16232. * Updates the camera's projection matrix. Must be called after any change of
  16233. * camera properties.
  16234. */
  16235. updateProjectionMatrix() {
  16236. const near = this.near;
  16237. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16238. let height = 2 * top;
  16239. let width = this.aspect * height;
  16240. let left = -0.5 * width;
  16241. const view = this.view;
  16242. if ( this.view !== null && this.view.enabled ) {
  16243. const fullWidth = view.fullWidth,
  16244. fullHeight = view.fullHeight;
  16245. left += view.offsetX * width / fullWidth;
  16246. top -= view.offsetY * height / fullHeight;
  16247. width *= view.width / fullWidth;
  16248. height *= view.height / fullHeight;
  16249. }
  16250. const skew = this.filmOffset;
  16251. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16252. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16253. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16254. }
  16255. toJSON( meta ) {
  16256. const data = super.toJSON( meta );
  16257. data.object.fov = this.fov;
  16258. data.object.zoom = this.zoom;
  16259. data.object.near = this.near;
  16260. data.object.far = this.far;
  16261. data.object.focus = this.focus;
  16262. data.object.aspect = this.aspect;
  16263. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16264. data.object.filmGauge = this.filmGauge;
  16265. data.object.filmOffset = this.filmOffset;
  16266. return data;
  16267. }
  16268. }
  16269. const fov = -90; // negative fov is not an error
  16270. const aspect = 1;
  16271. /**
  16272. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16273. * cube render target. The render target can then be used as an environment map for rendering
  16274. * realtime reflections in your scene.
  16275. *
  16276. * ```js
  16277. * // Create cube render target
  16278. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16279. *
  16280. * // Create cube camera
  16281. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16282. * scene.add( cubeCamera );
  16283. *
  16284. * // Create car
  16285. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16286. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16287. * scene.add( car );
  16288. *
  16289. * // Update the render target cube
  16290. * car.visible = false;
  16291. * cubeCamera.position.copy( car.position );
  16292. * cubeCamera.update( renderer, scene );
  16293. *
  16294. * // Render the scene
  16295. * car.visible = true;
  16296. * renderer.render( scene, camera );
  16297. * ```
  16298. *
  16299. * @augments Object3D
  16300. */
  16301. class CubeCamera extends Object3D {
  16302. /**
  16303. * Constructs a new cube camera.
  16304. *
  16305. * @param {number} near - The camera's near plane.
  16306. * @param {number} far - The camera's far plane.
  16307. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16308. */
  16309. constructor( near, far, renderTarget ) {
  16310. super();
  16311. this.type = 'CubeCamera';
  16312. /**
  16313. * A reference to the cube render target.
  16314. *
  16315. * @type {WebGLCubeRenderTarget}
  16316. */
  16317. this.renderTarget = renderTarget;
  16318. /**
  16319. * The current active coordinate system.
  16320. *
  16321. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16322. * @default null
  16323. */
  16324. this.coordinateSystem = null;
  16325. /**
  16326. * The current active mipmap level
  16327. *
  16328. * @type {number}
  16329. * @default 0
  16330. */
  16331. this.activeMipmapLevel = 0;
  16332. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16333. cameraPX.layers = this.layers;
  16334. this.add( cameraPX );
  16335. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16336. cameraNX.layers = this.layers;
  16337. this.add( cameraNX );
  16338. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16339. cameraPY.layers = this.layers;
  16340. this.add( cameraPY );
  16341. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16342. cameraNY.layers = this.layers;
  16343. this.add( cameraNY );
  16344. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16345. cameraPZ.layers = this.layers;
  16346. this.add( cameraPZ );
  16347. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16348. cameraNZ.layers = this.layers;
  16349. this.add( cameraNZ );
  16350. }
  16351. /**
  16352. * Must be called when the coordinate system of the cube camera is changed.
  16353. */
  16354. updateCoordinateSystem() {
  16355. const coordinateSystem = this.coordinateSystem;
  16356. const cameras = this.children.concat();
  16357. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16358. for ( const camera of cameras ) this.remove( camera );
  16359. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16360. cameraPX.up.set( 0, 1, 0 );
  16361. cameraPX.lookAt( 1, 0, 0 );
  16362. cameraNX.up.set( 0, 1, 0 );
  16363. cameraNX.lookAt( -1, 0, 0 );
  16364. cameraPY.up.set( 0, 0, -1 );
  16365. cameraPY.lookAt( 0, 1, 0 );
  16366. cameraNY.up.set( 0, 0, 1 );
  16367. cameraNY.lookAt( 0, -1, 0 );
  16368. cameraPZ.up.set( 0, 1, 0 );
  16369. cameraPZ.lookAt( 0, 0, 1 );
  16370. cameraNZ.up.set( 0, 1, 0 );
  16371. cameraNZ.lookAt( 0, 0, -1 );
  16372. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16373. cameraPX.up.set( 0, -1, 0 );
  16374. cameraPX.lookAt( -1, 0, 0 );
  16375. cameraNX.up.set( 0, -1, 0 );
  16376. cameraNX.lookAt( 1, 0, 0 );
  16377. cameraPY.up.set( 0, 0, 1 );
  16378. cameraPY.lookAt( 0, 1, 0 );
  16379. cameraNY.up.set( 0, 0, -1 );
  16380. cameraNY.lookAt( 0, -1, 0 );
  16381. cameraPZ.up.set( 0, -1, 0 );
  16382. cameraPZ.lookAt( 0, 0, 1 );
  16383. cameraNZ.up.set( 0, -1, 0 );
  16384. cameraNZ.lookAt( 0, 0, -1 );
  16385. } else {
  16386. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16387. }
  16388. for ( const camera of cameras ) {
  16389. this.add( camera );
  16390. camera.updateMatrixWorld();
  16391. }
  16392. }
  16393. /**
  16394. * Calling this method will render the given scene with the given renderer
  16395. * into the cube render target of the camera.
  16396. *
  16397. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16398. * @param {Scene} scene - The scene to render.
  16399. */
  16400. update( renderer, scene ) {
  16401. if ( this.parent === null ) this.updateMatrixWorld();
  16402. const { renderTarget, activeMipmapLevel } = this;
  16403. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16404. this.coordinateSystem = renderer.coordinateSystem;
  16405. this.updateCoordinateSystem();
  16406. }
  16407. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16408. const currentRenderTarget = renderer.getRenderTarget();
  16409. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16410. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16411. const currentXrEnabled = renderer.xr.enabled;
  16412. renderer.xr.enabled = false;
  16413. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16414. renderTarget.texture.generateMipmaps = false;
  16415. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16416. renderer.render( scene, cameraPX );
  16417. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16418. renderer.render( scene, cameraNX );
  16419. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16420. renderer.render( scene, cameraPY );
  16421. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16422. renderer.render( scene, cameraNY );
  16423. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16424. renderer.render( scene, cameraPZ );
  16425. // mipmaps are generated during the last call of render()
  16426. // at this point, all sides of the cube render target are defined
  16427. renderTarget.texture.generateMipmaps = generateMipmaps;
  16428. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16429. renderer.render( scene, cameraNZ );
  16430. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16431. renderer.xr.enabled = currentXrEnabled;
  16432. renderTarget.texture.needsPMREMUpdate = true;
  16433. }
  16434. }
  16435. /**
  16436. * Creates a cube texture made up of six images.
  16437. *
  16438. * ```js
  16439. * const loader = new THREE.CubeTextureLoader();
  16440. * loader.setPath( 'textures/cube/pisa/' );
  16441. *
  16442. * const textureCube = loader.load( [
  16443. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16444. * ] );
  16445. *
  16446. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16447. * ```
  16448. *
  16449. * @augments Texture
  16450. */
  16451. class CubeTexture extends Texture {
  16452. /**
  16453. * Constructs a new cube texture.
  16454. *
  16455. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16456. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16457. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16458. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16459. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16460. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16461. * @param {number} [format=RGBAFormat] - The texture format.
  16462. * @param {number} [type=UnsignedByteType] - The texture type.
  16463. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16464. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16465. */
  16466. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16467. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16468. /**
  16469. * This flag can be used for type testing.
  16470. *
  16471. * @type {boolean}
  16472. * @readonly
  16473. * @default true
  16474. */
  16475. this.isCubeTexture = true;
  16476. /**
  16477. * If set to `true`, the texture is flipped along the vertical axis when
  16478. * uploaded to the GPU.
  16479. *
  16480. * Overwritten and set to `false` by default.
  16481. *
  16482. * @type {boolean}
  16483. * @default false
  16484. */
  16485. this.flipY = false;
  16486. }
  16487. /**
  16488. * Alias for {@link CubeTexture#image}.
  16489. *
  16490. * @type {Array<Image>}
  16491. */
  16492. get images() {
  16493. return this.image;
  16494. }
  16495. set images( value ) {
  16496. this.image = value;
  16497. }
  16498. }
  16499. /**
  16500. * A cube render target used in context of {@link WebGLRenderer}.
  16501. *
  16502. * @augments WebGLRenderTarget
  16503. */
  16504. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16505. /**
  16506. * Constructs a new cube render target.
  16507. *
  16508. * @param {number} [size=1] - The size of the render target.
  16509. * @param {RenderTarget~Options} [options] - The configuration object.
  16510. */
  16511. constructor( size = 1, options = {} ) {
  16512. super( size, size, options );
  16513. /**
  16514. * This flag can be used for type testing.
  16515. *
  16516. * @type {boolean}
  16517. * @readonly
  16518. * @default true
  16519. */
  16520. this.isWebGLCubeRenderTarget = true;
  16521. const image = { width: size, height: size, depth: 1 };
  16522. const images = [ image, image, image, image, image, image ];
  16523. /**
  16524. * Overwritten with a different texture type.
  16525. *
  16526. * @type {DataArrayTexture}
  16527. */
  16528. this.texture = new CubeTexture( images );
  16529. this._setTextureOptions( options );
  16530. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16531. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16532. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16533. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16534. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16535. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16536. this.texture.isRenderTargetTexture = true;
  16537. }
  16538. /**
  16539. * Converts the given equirectangular texture to a cube map.
  16540. *
  16541. * @param {WebGLRenderer} renderer - The renderer.
  16542. * @param {Texture} texture - The equirectangular texture.
  16543. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16544. */
  16545. fromEquirectangularTexture( renderer, texture ) {
  16546. this.texture.type = texture.type;
  16547. this.texture.colorSpace = texture.colorSpace;
  16548. this.texture.generateMipmaps = texture.generateMipmaps;
  16549. this.texture.minFilter = texture.minFilter;
  16550. this.texture.magFilter = texture.magFilter;
  16551. const shader = {
  16552. uniforms: {
  16553. tEquirect: { value: null },
  16554. },
  16555. vertexShader: /* glsl */`
  16556. varying vec3 vWorldDirection;
  16557. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16558. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16559. }
  16560. void main() {
  16561. vWorldDirection = transformDirection( position, modelMatrix );
  16562. #include <begin_vertex>
  16563. #include <project_vertex>
  16564. }
  16565. `,
  16566. fragmentShader: /* glsl */`
  16567. uniform sampler2D tEquirect;
  16568. varying vec3 vWorldDirection;
  16569. #include <common>
  16570. void main() {
  16571. vec3 direction = normalize( vWorldDirection );
  16572. vec2 sampleUV = equirectUv( direction );
  16573. gl_FragColor = texture2D( tEquirect, sampleUV );
  16574. }
  16575. `
  16576. };
  16577. const geometry = new BoxGeometry( 5, 5, 5 );
  16578. const material = new ShaderMaterial( {
  16579. name: 'CubemapFromEquirect',
  16580. uniforms: cloneUniforms( shader.uniforms ),
  16581. vertexShader: shader.vertexShader,
  16582. fragmentShader: shader.fragmentShader,
  16583. side: BackSide,
  16584. blending: NoBlending
  16585. } );
  16586. material.uniforms.tEquirect.value = texture;
  16587. const mesh = new Mesh( geometry, material );
  16588. const currentMinFilter = texture.minFilter;
  16589. // Avoid blurred poles
  16590. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16591. const camera = new CubeCamera( 1, 10, this );
  16592. camera.update( renderer, mesh );
  16593. texture.minFilter = currentMinFilter;
  16594. mesh.geometry.dispose();
  16595. mesh.material.dispose();
  16596. return this;
  16597. }
  16598. /**
  16599. * Clears this cube render target.
  16600. *
  16601. * @param {WebGLRenderer} renderer - The renderer.
  16602. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16603. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16604. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16605. */
  16606. clear( renderer, color = true, depth = true, stencil = true ) {
  16607. const currentRenderTarget = renderer.getRenderTarget();
  16608. for ( let i = 0; i < 6; i ++ ) {
  16609. renderer.setRenderTarget( this, i );
  16610. renderer.clear( color, depth, stencil );
  16611. }
  16612. renderer.setRenderTarget( currentRenderTarget );
  16613. }
  16614. }
  16615. /**
  16616. * This is almost identical to an {@link Object3D}. Its purpose is to
  16617. * make working with groups of objects syntactically clearer.
  16618. *
  16619. * ```js
  16620. * // Create a group and add the two cubes.
  16621. * // These cubes can now be rotated / scaled etc as a group.
  16622. * const group = new THREE.Group();
  16623. *
  16624. * group.add( meshA );
  16625. * group.add( meshB );
  16626. *
  16627. * scene.add( group );
  16628. * ```
  16629. *
  16630. * @augments Object3D
  16631. */
  16632. class Group extends Object3D {
  16633. constructor() {
  16634. super();
  16635. /**
  16636. * This flag can be used for type testing.
  16637. *
  16638. * @type {boolean}
  16639. * @readonly
  16640. * @default true
  16641. */
  16642. this.isGroup = true;
  16643. this.type = 'Group';
  16644. }
  16645. }
  16646. const _moveEvent = { type: 'move' };
  16647. /**
  16648. * Class for representing a XR controller with its
  16649. * different coordinate systems.
  16650. *
  16651. * @private
  16652. */
  16653. class WebXRController {
  16654. /**
  16655. * Constructs a new XR controller.
  16656. */
  16657. constructor() {
  16658. /**
  16659. * A group representing the target ray space
  16660. * of the XR controller.
  16661. *
  16662. * @private
  16663. * @type {?Group}
  16664. * @default null
  16665. */
  16666. this._targetRay = null;
  16667. /**
  16668. * A group representing the grip space
  16669. * of the XR controller.
  16670. *
  16671. * @private
  16672. * @type {?Group}
  16673. * @default null
  16674. */
  16675. this._grip = null;
  16676. /**
  16677. * A group representing the hand space
  16678. * of the XR controller.
  16679. *
  16680. * @private
  16681. * @type {?Group}
  16682. * @default null
  16683. */
  16684. this._hand = null;
  16685. }
  16686. /**
  16687. * Returns a group representing the hand space of the XR controller.
  16688. *
  16689. * @return {Group} A group representing the hand space of the XR controller.
  16690. */
  16691. getHandSpace() {
  16692. if ( this._hand === null ) {
  16693. this._hand = new Group();
  16694. this._hand.matrixAutoUpdate = false;
  16695. this._hand.visible = false;
  16696. this._hand.joints = {};
  16697. this._hand.inputState = { pinching: false };
  16698. }
  16699. return this._hand;
  16700. }
  16701. /**
  16702. * Returns a group representing the target ray space of the XR controller.
  16703. *
  16704. * @return {Group} A group representing the target ray space of the XR controller.
  16705. */
  16706. getTargetRaySpace() {
  16707. if ( this._targetRay === null ) {
  16708. this._targetRay = new Group();
  16709. this._targetRay.matrixAutoUpdate = false;
  16710. this._targetRay.visible = false;
  16711. this._targetRay.hasLinearVelocity = false;
  16712. this._targetRay.linearVelocity = new Vector3();
  16713. this._targetRay.hasAngularVelocity = false;
  16714. this._targetRay.angularVelocity = new Vector3();
  16715. }
  16716. return this._targetRay;
  16717. }
  16718. /**
  16719. * Returns a group representing the grip space of the XR controller.
  16720. *
  16721. * @return {Group} A group representing the grip space of the XR controller.
  16722. */
  16723. getGripSpace() {
  16724. if ( this._grip === null ) {
  16725. this._grip = new Group();
  16726. this._grip.matrixAutoUpdate = false;
  16727. this._grip.visible = false;
  16728. this._grip.hasLinearVelocity = false;
  16729. this._grip.linearVelocity = new Vector3();
  16730. this._grip.hasAngularVelocity = false;
  16731. this._grip.angularVelocity = new Vector3();
  16732. }
  16733. return this._grip;
  16734. }
  16735. /**
  16736. * Dispatches the given event to the groups representing
  16737. * the different coordinate spaces of the XR controller.
  16738. *
  16739. * @param {Object} event - The event to dispatch.
  16740. * @return {WebXRController} A reference to this instance.
  16741. */
  16742. dispatchEvent( event ) {
  16743. if ( this._targetRay !== null ) {
  16744. this._targetRay.dispatchEvent( event );
  16745. }
  16746. if ( this._grip !== null ) {
  16747. this._grip.dispatchEvent( event );
  16748. }
  16749. if ( this._hand !== null ) {
  16750. this._hand.dispatchEvent( event );
  16751. }
  16752. return this;
  16753. }
  16754. /**
  16755. * Connects the controller with the given XR input source.
  16756. *
  16757. * @param {XRInputSource} inputSource - The input source.
  16758. * @return {WebXRController} A reference to this instance.
  16759. */
  16760. connect( inputSource ) {
  16761. if ( inputSource && inputSource.hand ) {
  16762. const hand = this._hand;
  16763. if ( hand ) {
  16764. for ( const inputjoint of inputSource.hand.values() ) {
  16765. // Initialize hand with joints when connected
  16766. this._getHandJoint( hand, inputjoint );
  16767. }
  16768. }
  16769. }
  16770. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16771. return this;
  16772. }
  16773. /**
  16774. * Disconnects the controller from the given XR input source.
  16775. *
  16776. * @param {XRInputSource} inputSource - The input source.
  16777. * @return {WebXRController} A reference to this instance.
  16778. */
  16779. disconnect( inputSource ) {
  16780. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16781. if ( this._targetRay !== null ) {
  16782. this._targetRay.visible = false;
  16783. }
  16784. if ( this._grip !== null ) {
  16785. this._grip.visible = false;
  16786. }
  16787. if ( this._hand !== null ) {
  16788. this._hand.visible = false;
  16789. }
  16790. return this;
  16791. }
  16792. /**
  16793. * Updates the controller with the given input source, XR frame and reference space.
  16794. * This updates the transformations of the groups that represent the different
  16795. * coordinate systems of the controller.
  16796. *
  16797. * @param {XRInputSource} inputSource - The input source.
  16798. * @param {XRFrame} frame - The XR frame.
  16799. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16800. * @return {WebXRController} A reference to this instance.
  16801. */
  16802. update( inputSource, frame, referenceSpace ) {
  16803. let inputPose = null;
  16804. let gripPose = null;
  16805. let handPose = null;
  16806. const targetRay = this._targetRay;
  16807. const grip = this._grip;
  16808. const hand = this._hand;
  16809. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16810. if ( hand && inputSource.hand ) {
  16811. handPose = true;
  16812. for ( const inputjoint of inputSource.hand.values() ) {
  16813. // Update the joints groups with the XRJoint poses
  16814. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16815. // The transform of this joint will be updated with the joint pose on each frame
  16816. const joint = this._getHandJoint( hand, inputjoint );
  16817. if ( jointPose !== null ) {
  16818. joint.matrix.fromArray( jointPose.transform.matrix );
  16819. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16820. joint.matrixWorldNeedsUpdate = true;
  16821. joint.jointRadius = jointPose.radius;
  16822. }
  16823. joint.visible = jointPose !== null;
  16824. }
  16825. // Custom events
  16826. // Check pinchz
  16827. const indexTip = hand.joints[ 'index-finger-tip' ];
  16828. const thumbTip = hand.joints[ 'thumb-tip' ];
  16829. const distance = indexTip.position.distanceTo( thumbTip.position );
  16830. const distanceToPinch = 0.02;
  16831. const threshold = 0.005;
  16832. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16833. hand.inputState.pinching = false;
  16834. this.dispatchEvent( {
  16835. type: 'pinchend',
  16836. handedness: inputSource.handedness,
  16837. target: this
  16838. } );
  16839. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16840. hand.inputState.pinching = true;
  16841. this.dispatchEvent( {
  16842. type: 'pinchstart',
  16843. handedness: inputSource.handedness,
  16844. target: this
  16845. } );
  16846. }
  16847. } else {
  16848. if ( grip !== null && inputSource.gripSpace ) {
  16849. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16850. if ( gripPose !== null ) {
  16851. grip.matrix.fromArray( gripPose.transform.matrix );
  16852. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16853. grip.matrixWorldNeedsUpdate = true;
  16854. if ( gripPose.linearVelocity ) {
  16855. grip.hasLinearVelocity = true;
  16856. grip.linearVelocity.copy( gripPose.linearVelocity );
  16857. } else {
  16858. grip.hasLinearVelocity = false;
  16859. }
  16860. if ( gripPose.angularVelocity ) {
  16861. grip.hasAngularVelocity = true;
  16862. grip.angularVelocity.copy( gripPose.angularVelocity );
  16863. } else {
  16864. grip.hasAngularVelocity = false;
  16865. }
  16866. }
  16867. }
  16868. }
  16869. if ( targetRay !== null ) {
  16870. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16871. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16872. if ( inputPose === null && gripPose !== null ) {
  16873. inputPose = gripPose;
  16874. }
  16875. if ( inputPose !== null ) {
  16876. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16877. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16878. targetRay.matrixWorldNeedsUpdate = true;
  16879. if ( inputPose.linearVelocity ) {
  16880. targetRay.hasLinearVelocity = true;
  16881. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16882. } else {
  16883. targetRay.hasLinearVelocity = false;
  16884. }
  16885. if ( inputPose.angularVelocity ) {
  16886. targetRay.hasAngularVelocity = true;
  16887. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16888. } else {
  16889. targetRay.hasAngularVelocity = false;
  16890. }
  16891. this.dispatchEvent( _moveEvent );
  16892. }
  16893. }
  16894. }
  16895. if ( targetRay !== null ) {
  16896. targetRay.visible = ( inputPose !== null );
  16897. }
  16898. if ( grip !== null ) {
  16899. grip.visible = ( gripPose !== null );
  16900. }
  16901. if ( hand !== null ) {
  16902. hand.visible = ( handPose !== null );
  16903. }
  16904. return this;
  16905. }
  16906. /**
  16907. * Returns a group representing the hand joint for the given input joint.
  16908. *
  16909. * @private
  16910. * @param {Group} hand - The group representing the hand space.
  16911. * @param {XRJointSpace} inputjoint - The hand joint data.
  16912. * @return {Group} A group representing the hand joint for the given input joint.
  16913. */
  16914. _getHandJoint( hand, inputjoint ) {
  16915. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16916. const joint = new Group();
  16917. joint.matrixAutoUpdate = false;
  16918. joint.visible = false;
  16919. hand.joints[ inputjoint.jointName ] = joint;
  16920. hand.add( joint );
  16921. }
  16922. return hand.joints[ inputjoint.jointName ];
  16923. }
  16924. }
  16925. /**
  16926. * This class can be used to define an exponential squared fog,
  16927. * which gives a clear view near the camera and a faster than exponentially
  16928. * densening fog farther from the camera.
  16929. *
  16930. * ```js
  16931. * const scene = new THREE.Scene();
  16932. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16933. * ```
  16934. */
  16935. class FogExp2 {
  16936. /**
  16937. * Constructs a new fog.
  16938. *
  16939. * @param {number|Color} color - The fog's color.
  16940. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16941. */
  16942. constructor( color, density = 0.00025 ) {
  16943. /**
  16944. * This flag can be used for type testing.
  16945. *
  16946. * @type {boolean}
  16947. * @readonly
  16948. * @default true
  16949. */
  16950. this.isFogExp2 = true;
  16951. /**
  16952. * The name of the fog.
  16953. *
  16954. * @type {string}
  16955. */
  16956. this.name = '';
  16957. /**
  16958. * The fog's color.
  16959. *
  16960. * @type {Color}
  16961. */
  16962. this.color = new Color( color );
  16963. /**
  16964. * Defines how fast the fog will grow dense.
  16965. *
  16966. * @type {number}
  16967. * @default 0.00025
  16968. */
  16969. this.density = density;
  16970. }
  16971. /**
  16972. * Returns a new fog with copied values from this instance.
  16973. *
  16974. * @return {FogExp2} A clone of this instance.
  16975. */
  16976. clone() {
  16977. return new FogExp2( this.color, this.density );
  16978. }
  16979. /**
  16980. * Serializes the fog into JSON.
  16981. *
  16982. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16983. * @return {Object} A JSON object representing the serialized fog
  16984. */
  16985. toJSON( /* meta */ ) {
  16986. return {
  16987. type: 'FogExp2',
  16988. name: this.name,
  16989. color: this.color.getHex(),
  16990. density: this.density
  16991. };
  16992. }
  16993. }
  16994. /**
  16995. * This class can be used to define a linear fog that grows linearly denser
  16996. * with the distance.
  16997. *
  16998. * ```js
  16999. * const scene = new THREE.Scene();
  17000. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17001. * ```
  17002. */
  17003. class Fog {
  17004. /**
  17005. * Constructs a new fog.
  17006. *
  17007. * @param {number|Color} color - The fog's color.
  17008. * @param {number} [near=1] - The minimum distance to start applying fog.
  17009. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17010. */
  17011. constructor( color, near = 1, far = 1000 ) {
  17012. /**
  17013. * This flag can be used for type testing.
  17014. *
  17015. * @type {boolean}
  17016. * @readonly
  17017. * @default true
  17018. */
  17019. this.isFog = true;
  17020. /**
  17021. * The name of the fog.
  17022. *
  17023. * @type {string}
  17024. */
  17025. this.name = '';
  17026. /**
  17027. * The fog's color.
  17028. *
  17029. * @type {Color}
  17030. */
  17031. this.color = new Color( color );
  17032. /**
  17033. * The minimum distance to start applying fog. Objects that are less than
  17034. * `near` units from the active camera won't be affected by fog.
  17035. *
  17036. * @type {number}
  17037. * @default 1
  17038. */
  17039. this.near = near;
  17040. /**
  17041. * The maximum distance at which fog stops being calculated and applied.
  17042. * Objects that are more than `far` units away from the active camera won't
  17043. * be affected by fog.
  17044. *
  17045. * @type {number}
  17046. * @default 1000
  17047. */
  17048. this.far = far;
  17049. }
  17050. /**
  17051. * Returns a new fog with copied values from this instance.
  17052. *
  17053. * @return {Fog} A clone of this instance.
  17054. */
  17055. clone() {
  17056. return new Fog( this.color, this.near, this.far );
  17057. }
  17058. /**
  17059. * Serializes the fog into JSON.
  17060. *
  17061. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17062. * @return {Object} A JSON object representing the serialized fog
  17063. */
  17064. toJSON( /* meta */ ) {
  17065. return {
  17066. type: 'Fog',
  17067. name: this.name,
  17068. color: this.color.getHex(),
  17069. near: this.near,
  17070. far: this.far
  17071. };
  17072. }
  17073. }
  17074. /**
  17075. * Scenes allow you to set up what is to be rendered and where by three.js.
  17076. * This is where you place 3D objects like meshes, lines or lights.
  17077. *
  17078. * @augments Object3D
  17079. */
  17080. class Scene extends Object3D {
  17081. /**
  17082. * Constructs a new scene.
  17083. */
  17084. constructor() {
  17085. super();
  17086. /**
  17087. * This flag can be used for type testing.
  17088. *
  17089. * @type {boolean}
  17090. * @readonly
  17091. * @default true
  17092. */
  17093. this.isScene = true;
  17094. this.type = 'Scene';
  17095. /**
  17096. * Defines the background of the scene. Valid inputs are:
  17097. *
  17098. * - A color for defining a uniform colored background.
  17099. * - A texture for defining a (flat) textured background.
  17100. * - Cube textures or equirectangular textures for defining a skybox.
  17101. *
  17102. * @type {?(Color|Texture)}
  17103. * @default null
  17104. */
  17105. this.background = null;
  17106. /**
  17107. * Sets the environment map for all physical materials in the scene. However,
  17108. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17109. * material property.
  17110. *
  17111. * @type {?Texture}
  17112. * @default null
  17113. */
  17114. this.environment = null;
  17115. /**
  17116. * A fog instance defining the type of fog that affects everything
  17117. * rendered in the scene.
  17118. *
  17119. * @type {?(Fog|FogExp2)}
  17120. * @default null
  17121. */
  17122. this.fog = null;
  17123. /**
  17124. * Sets the blurriness of the background. Only influences environment maps
  17125. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17126. * and `1`.
  17127. *
  17128. * @type {number}
  17129. * @default 0
  17130. */
  17131. this.backgroundBlurriness = 0;
  17132. /**
  17133. * Attenuates the color of the background. Only applies to background textures.
  17134. *
  17135. * @type {number}
  17136. * @default 1
  17137. */
  17138. this.backgroundIntensity = 1;
  17139. /**
  17140. * The rotation of the background in radians. Only influences environment maps
  17141. * assigned to {@link Scene#background}.
  17142. *
  17143. * @type {Euler}
  17144. * @default (0,0,0)
  17145. */
  17146. this.backgroundRotation = new Euler();
  17147. /**
  17148. * Attenuates the color of the environment. Only influences environment maps
  17149. * assigned to {@link Scene#environment}.
  17150. *
  17151. * @type {number}
  17152. * @default 1
  17153. */
  17154. this.environmentIntensity = 1;
  17155. /**
  17156. * The rotation of the environment map in radians. Only influences physical materials
  17157. * in the scene when {@link Scene#environment} is used.
  17158. *
  17159. * @type {Euler}
  17160. * @default (0,0,0)
  17161. */
  17162. this.environmentRotation = new Euler();
  17163. /**
  17164. * Forces everything in the scene to be rendered with the defined material. It is possible
  17165. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17166. *
  17167. * @type {?Material}
  17168. * @default null
  17169. */
  17170. this.overrideMaterial = null;
  17171. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17172. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17173. }
  17174. }
  17175. copy( source, recursive ) {
  17176. super.copy( source, recursive );
  17177. if ( source.background !== null ) this.background = source.background.clone();
  17178. if ( source.environment !== null ) this.environment = source.environment.clone();
  17179. if ( source.fog !== null ) this.fog = source.fog.clone();
  17180. this.backgroundBlurriness = source.backgroundBlurriness;
  17181. this.backgroundIntensity = source.backgroundIntensity;
  17182. this.backgroundRotation.copy( source.backgroundRotation );
  17183. this.environmentIntensity = source.environmentIntensity;
  17184. this.environmentRotation.copy( source.environmentRotation );
  17185. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17186. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17187. return this;
  17188. }
  17189. toJSON( meta ) {
  17190. const data = super.toJSON( meta );
  17191. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17192. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17193. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17194. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17195. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17196. data.object.environmentRotation = this.environmentRotation.toArray();
  17197. return data;
  17198. }
  17199. }
  17200. /**
  17201. * "Interleaved" means that multiple attributes, possibly of different types,
  17202. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17203. *
  17204. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17205. */
  17206. class InterleavedBuffer {
  17207. /**
  17208. * Constructs a new interleaved buffer.
  17209. *
  17210. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17211. * @param {number} stride - The number of typed-array elements per vertex.
  17212. */
  17213. constructor( array, stride ) {
  17214. /**
  17215. * This flag can be used for type testing.
  17216. *
  17217. * @type {boolean}
  17218. * @readonly
  17219. * @default true
  17220. */
  17221. this.isInterleavedBuffer = true;
  17222. /**
  17223. * A typed array with a shared buffer storing attribute data.
  17224. *
  17225. * @type {TypedArray}
  17226. */
  17227. this.array = array;
  17228. /**
  17229. * The number of typed-array elements per vertex.
  17230. *
  17231. * @type {number}
  17232. */
  17233. this.stride = stride;
  17234. /**
  17235. * The total number of elements in the array
  17236. *
  17237. * @type {number}
  17238. * @readonly
  17239. */
  17240. this.count = array !== undefined ? array.length / stride : 0;
  17241. /**
  17242. * Defines the intended usage pattern of the data store for optimization purposes.
  17243. *
  17244. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17245. * instantiate a new one and set the desired usage before the next render.
  17246. *
  17247. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17248. * @default StaticDrawUsage
  17249. */
  17250. this.usage = StaticDrawUsage;
  17251. /**
  17252. * This can be used to only update some components of stored vectors (for example, just the
  17253. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17254. *
  17255. * @type {Array<Object>}
  17256. */
  17257. this.updateRanges = [];
  17258. /**
  17259. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17260. *
  17261. * @type {number}
  17262. */
  17263. this.version = 0;
  17264. /**
  17265. * The UUID of the interleaved buffer.
  17266. *
  17267. * @type {string}
  17268. * @readonly
  17269. */
  17270. this.uuid = generateUUID();
  17271. }
  17272. /**
  17273. * A callback function that is executed after the renderer has transferred the attribute array
  17274. * data to the GPU.
  17275. */
  17276. onUploadCallback() {}
  17277. /**
  17278. * Flag to indicate that this attribute has changed and should be re-sent to
  17279. * the GPU. Set this to `true` when you modify the value of the array.
  17280. *
  17281. * @type {number}
  17282. * @default false
  17283. * @param {boolean} value
  17284. */
  17285. set needsUpdate( value ) {
  17286. if ( value === true ) this.version ++;
  17287. }
  17288. /**
  17289. * Sets the usage of this interleaved buffer.
  17290. *
  17291. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17292. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17293. */
  17294. setUsage( value ) {
  17295. this.usage = value;
  17296. return this;
  17297. }
  17298. /**
  17299. * Adds a range of data in the data array to be updated on the GPU.
  17300. *
  17301. * @param {number} start - Position at which to start update.
  17302. * @param {number} count - The number of components to update.
  17303. */
  17304. addUpdateRange( start, count ) {
  17305. this.updateRanges.push( { start, count } );
  17306. }
  17307. /**
  17308. * Clears the update ranges.
  17309. */
  17310. clearUpdateRanges() {
  17311. this.updateRanges.length = 0;
  17312. }
  17313. /**
  17314. * Copies the values of the given interleaved buffer to this instance.
  17315. *
  17316. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17317. * @return {InterleavedBuffer} A reference to this instance.
  17318. */
  17319. copy( source ) {
  17320. this.array = new source.array.constructor( source.array );
  17321. this.count = source.count;
  17322. this.stride = source.stride;
  17323. this.usage = source.usage;
  17324. return this;
  17325. }
  17326. /**
  17327. * Copies a vector from the given interleaved buffer to this one. The start
  17328. * and destination position in the attribute buffers are represented by the
  17329. * given indices.
  17330. *
  17331. * @param {number} index1 - The destination index into this interleaved buffer.
  17332. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17333. * @param {number} index2 - The source index into the given interleaved buffer.
  17334. * @return {InterleavedBuffer} A reference to this instance.
  17335. */
  17336. copyAt( index1, interleavedBuffer, index2 ) {
  17337. index1 *= this.stride;
  17338. index2 *= interleavedBuffer.stride;
  17339. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17340. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17341. }
  17342. return this;
  17343. }
  17344. /**
  17345. * Sets the given array data in the interleaved buffer.
  17346. *
  17347. * @param {(TypedArray|Array)} value - The array data to set.
  17348. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17349. * @return {InterleavedBuffer} A reference to this instance.
  17350. */
  17351. set( value, offset = 0 ) {
  17352. this.array.set( value, offset );
  17353. return this;
  17354. }
  17355. /**
  17356. * Returns a new interleaved buffer with copied values from this instance.
  17357. *
  17358. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17359. * @return {InterleavedBuffer} A clone of this instance.
  17360. */
  17361. clone( data ) {
  17362. if ( data.arrayBuffers === undefined ) {
  17363. data.arrayBuffers = {};
  17364. }
  17365. if ( this.array.buffer._uuid === undefined ) {
  17366. this.array.buffer._uuid = generateUUID();
  17367. }
  17368. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17369. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17370. }
  17371. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17372. const ib = new this.constructor( array, this.stride );
  17373. ib.setUsage( this.usage );
  17374. return ib;
  17375. }
  17376. /**
  17377. * Sets the given callback function that is executed after the Renderer has transferred
  17378. * the array data to the GPU. Can be used to perform clean-up operations after
  17379. * the upload when data are not needed anymore on the CPU side.
  17380. *
  17381. * @param {Function} callback - The `onUpload()` callback.
  17382. * @return {InterleavedBuffer} A reference to this instance.
  17383. */
  17384. onUpload( callback ) {
  17385. this.onUploadCallback = callback;
  17386. return this;
  17387. }
  17388. /**
  17389. * Serializes the interleaved buffer into JSON.
  17390. *
  17391. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17392. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17393. */
  17394. toJSON( data ) {
  17395. if ( data.arrayBuffers === undefined ) {
  17396. data.arrayBuffers = {};
  17397. }
  17398. // generate UUID for array buffer if necessary
  17399. if ( this.array.buffer._uuid === undefined ) {
  17400. this.array.buffer._uuid = generateUUID();
  17401. }
  17402. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17403. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17404. }
  17405. //
  17406. return {
  17407. uuid: this.uuid,
  17408. buffer: this.array.buffer._uuid,
  17409. type: this.array.constructor.name,
  17410. stride: this.stride
  17411. };
  17412. }
  17413. }
  17414. const _vector$7 = /*@__PURE__*/ new Vector3();
  17415. /**
  17416. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17417. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17418. * different offsets into the buffer.
  17419. */
  17420. class InterleavedBufferAttribute {
  17421. /**
  17422. * Constructs a new interleaved buffer attribute.
  17423. *
  17424. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17425. * @param {number} itemSize - The item size.
  17426. * @param {number} offset - The attribute offset into the buffer.
  17427. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17428. */
  17429. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17430. /**
  17431. * This flag can be used for type testing.
  17432. *
  17433. * @type {boolean}
  17434. * @readonly
  17435. * @default true
  17436. */
  17437. this.isInterleavedBufferAttribute = true;
  17438. /**
  17439. * The name of the buffer attribute.
  17440. *
  17441. * @type {string}
  17442. */
  17443. this.name = '';
  17444. /**
  17445. * The buffer holding the interleaved data.
  17446. *
  17447. * @type {InterleavedBuffer}
  17448. */
  17449. this.data = interleavedBuffer;
  17450. /**
  17451. * The item size, see {@link BufferAttribute#itemSize}.
  17452. *
  17453. * @type {number}
  17454. */
  17455. this.itemSize = itemSize;
  17456. /**
  17457. * The attribute offset into the buffer.
  17458. *
  17459. * @type {number}
  17460. */
  17461. this.offset = offset;
  17462. /**
  17463. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17464. *
  17465. * @type {InterleavedBuffer}
  17466. */
  17467. this.normalized = normalized;
  17468. }
  17469. /**
  17470. * The item count of this buffer attribute.
  17471. *
  17472. * @type {number}
  17473. * @readonly
  17474. */
  17475. get count() {
  17476. return this.data.count;
  17477. }
  17478. /**
  17479. * The array holding the interleaved buffer attribute data.
  17480. *
  17481. * @type {TypedArray}
  17482. */
  17483. get array() {
  17484. return this.data.array;
  17485. }
  17486. /**
  17487. * Flag to indicate that this attribute has changed and should be re-sent to
  17488. * the GPU. Set this to `true` when you modify the value of the array.
  17489. *
  17490. * @type {number}
  17491. * @default false
  17492. * @param {boolean} value
  17493. */
  17494. set needsUpdate( value ) {
  17495. this.data.needsUpdate = value;
  17496. }
  17497. /**
  17498. * Applies the given 4x4 matrix to the given attribute. Only works with
  17499. * item size `3`.
  17500. *
  17501. * @param {Matrix4} m - The matrix to apply.
  17502. * @return {InterleavedBufferAttribute} A reference to this instance.
  17503. */
  17504. applyMatrix4( m ) {
  17505. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17506. _vector$7.fromBufferAttribute( this, i );
  17507. _vector$7.applyMatrix4( m );
  17508. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17509. }
  17510. return this;
  17511. }
  17512. /**
  17513. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17514. * item size `3`.
  17515. *
  17516. * @param {Matrix3} m - The normal matrix to apply.
  17517. * @return {InterleavedBufferAttribute} A reference to this instance.
  17518. */
  17519. applyNormalMatrix( m ) {
  17520. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17521. _vector$7.fromBufferAttribute( this, i );
  17522. _vector$7.applyNormalMatrix( m );
  17523. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17524. }
  17525. return this;
  17526. }
  17527. /**
  17528. * Applies the given 4x4 matrix to the given attribute. Only works with
  17529. * item size `3` and with direction vectors.
  17530. *
  17531. * @param {Matrix4} m - The matrix to apply.
  17532. * @return {InterleavedBufferAttribute} A reference to this instance.
  17533. */
  17534. transformDirection( m ) {
  17535. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17536. _vector$7.fromBufferAttribute( this, i );
  17537. _vector$7.transformDirection( m );
  17538. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17539. }
  17540. return this;
  17541. }
  17542. /**
  17543. * Returns the given component of the vector at the given index.
  17544. *
  17545. * @param {number} index - The index into the buffer attribute.
  17546. * @param {number} component - The component index.
  17547. * @return {number} The returned value.
  17548. */
  17549. getComponent( index, component ) {
  17550. let value = this.array[ index * this.data.stride + this.offset + component ];
  17551. if ( this.normalized ) value = denormalize( value, this.array );
  17552. return value;
  17553. }
  17554. /**
  17555. * Sets the given value to the given component of the vector at the given index.
  17556. *
  17557. * @param {number} index - The index into the buffer attribute.
  17558. * @param {number} component - The component index.
  17559. * @param {number} value - The value to set.
  17560. * @return {InterleavedBufferAttribute} A reference to this instance.
  17561. */
  17562. setComponent( index, component, value ) {
  17563. if ( this.normalized ) value = normalize( value, this.array );
  17564. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17565. return this;
  17566. }
  17567. /**
  17568. * Sets the x component of the vector at the given index.
  17569. *
  17570. * @param {number} index - The index into the buffer attribute.
  17571. * @param {number} x - The value to set.
  17572. * @return {InterleavedBufferAttribute} A reference to this instance.
  17573. */
  17574. setX( index, x ) {
  17575. if ( this.normalized ) x = normalize( x, this.array );
  17576. this.data.array[ index * this.data.stride + this.offset ] = x;
  17577. return this;
  17578. }
  17579. /**
  17580. * Sets the y component of the vector at the given index.
  17581. *
  17582. * @param {number} index - The index into the buffer attribute.
  17583. * @param {number} y - The value to set.
  17584. * @return {InterleavedBufferAttribute} A reference to this instance.
  17585. */
  17586. setY( index, y ) {
  17587. if ( this.normalized ) y = normalize( y, this.array );
  17588. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17589. return this;
  17590. }
  17591. /**
  17592. * Sets the z component of the vector at the given index.
  17593. *
  17594. * @param {number} index - The index into the buffer attribute.
  17595. * @param {number} z - The value to set.
  17596. * @return {InterleavedBufferAttribute} A reference to this instance.
  17597. */
  17598. setZ( index, z ) {
  17599. if ( this.normalized ) z = normalize( z, this.array );
  17600. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17601. return this;
  17602. }
  17603. /**
  17604. * Sets the w component of the vector at the given index.
  17605. *
  17606. * @param {number} index - The index into the buffer attribute.
  17607. * @param {number} w - The value to set.
  17608. * @return {InterleavedBufferAttribute} A reference to this instance.
  17609. */
  17610. setW( index, w ) {
  17611. if ( this.normalized ) w = normalize( w, this.array );
  17612. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17613. return this;
  17614. }
  17615. /**
  17616. * Returns the x component of the vector at the given index.
  17617. *
  17618. * @param {number} index - The index into the buffer attribute.
  17619. * @return {number} The x component.
  17620. */
  17621. getX( index ) {
  17622. let x = this.data.array[ index * this.data.stride + this.offset ];
  17623. if ( this.normalized ) x = denormalize( x, this.array );
  17624. return x;
  17625. }
  17626. /**
  17627. * Returns the y component of the vector at the given index.
  17628. *
  17629. * @param {number} index - The index into the buffer attribute.
  17630. * @return {number} The y component.
  17631. */
  17632. getY( index ) {
  17633. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17634. if ( this.normalized ) y = denormalize( y, this.array );
  17635. return y;
  17636. }
  17637. /**
  17638. * Returns the z component of the vector at the given index.
  17639. *
  17640. * @param {number} index - The index into the buffer attribute.
  17641. * @return {number} The z component.
  17642. */
  17643. getZ( index ) {
  17644. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17645. if ( this.normalized ) z = denormalize( z, this.array );
  17646. return z;
  17647. }
  17648. /**
  17649. * Returns the w component of the vector at the given index.
  17650. *
  17651. * @param {number} index - The index into the buffer attribute.
  17652. * @return {number} The w component.
  17653. */
  17654. getW( index ) {
  17655. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17656. if ( this.normalized ) w = denormalize( w, this.array );
  17657. return w;
  17658. }
  17659. /**
  17660. * Sets the x and y component of the vector at the given index.
  17661. *
  17662. * @param {number} index - The index into the buffer attribute.
  17663. * @param {number} x - The value for the x component to set.
  17664. * @param {number} y - The value for the y component to set.
  17665. * @return {InterleavedBufferAttribute} A reference to this instance.
  17666. */
  17667. setXY( index, x, y ) {
  17668. index = index * this.data.stride + this.offset;
  17669. if ( this.normalized ) {
  17670. x = normalize( x, this.array );
  17671. y = normalize( y, this.array );
  17672. }
  17673. this.data.array[ index + 0 ] = x;
  17674. this.data.array[ index + 1 ] = y;
  17675. return this;
  17676. }
  17677. /**
  17678. * Sets the x, y and z component of the vector at the given index.
  17679. *
  17680. * @param {number} index - The index into the buffer attribute.
  17681. * @param {number} x - The value for the x component to set.
  17682. * @param {number} y - The value for the y component to set.
  17683. * @param {number} z - The value for the z component to set.
  17684. * @return {InterleavedBufferAttribute} A reference to this instance.
  17685. */
  17686. setXYZ( index, x, y, z ) {
  17687. index = index * this.data.stride + this.offset;
  17688. if ( this.normalized ) {
  17689. x = normalize( x, this.array );
  17690. y = normalize( y, this.array );
  17691. z = normalize( z, this.array );
  17692. }
  17693. this.data.array[ index + 0 ] = x;
  17694. this.data.array[ index + 1 ] = y;
  17695. this.data.array[ index + 2 ] = z;
  17696. return this;
  17697. }
  17698. /**
  17699. * Sets the x, y, z and w component of the vector at the given index.
  17700. *
  17701. * @param {number} index - The index into the buffer attribute.
  17702. * @param {number} x - The value for the x component to set.
  17703. * @param {number} y - The value for the y component to set.
  17704. * @param {number} z - The value for the z component to set.
  17705. * @param {number} w - The value for the w component to set.
  17706. * @return {InterleavedBufferAttribute} A reference to this instance.
  17707. */
  17708. setXYZW( index, x, y, z, w ) {
  17709. index = index * this.data.stride + this.offset;
  17710. if ( this.normalized ) {
  17711. x = normalize( x, this.array );
  17712. y = normalize( y, this.array );
  17713. z = normalize( z, this.array );
  17714. w = normalize( w, this.array );
  17715. }
  17716. this.data.array[ index + 0 ] = x;
  17717. this.data.array[ index + 1 ] = y;
  17718. this.data.array[ index + 2 ] = z;
  17719. this.data.array[ index + 3 ] = w;
  17720. return this;
  17721. }
  17722. /**
  17723. * Returns a new buffer attribute with copied values from this instance.
  17724. *
  17725. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17726. *
  17727. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17728. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17729. */
  17730. clone( data ) {
  17731. if ( data === undefined ) {
  17732. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17733. const array = [];
  17734. for ( let i = 0; i < this.count; i ++ ) {
  17735. const index = i * this.data.stride + this.offset;
  17736. for ( let j = 0; j < this.itemSize; j ++ ) {
  17737. array.push( this.data.array[ index + j ] );
  17738. }
  17739. }
  17740. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17741. } else {
  17742. if ( data.interleavedBuffers === undefined ) {
  17743. data.interleavedBuffers = {};
  17744. }
  17745. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17746. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17747. }
  17748. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17749. }
  17750. }
  17751. /**
  17752. * Serializes the buffer attribute into JSON.
  17753. *
  17754. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17755. *
  17756. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17757. * @return {Object} A JSON object representing the serialized buffer attribute.
  17758. */
  17759. toJSON( data ) {
  17760. if ( data === undefined ) {
  17761. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17762. const array = [];
  17763. for ( let i = 0; i < this.count; i ++ ) {
  17764. const index = i * this.data.stride + this.offset;
  17765. for ( let j = 0; j < this.itemSize; j ++ ) {
  17766. array.push( this.data.array[ index + j ] );
  17767. }
  17768. }
  17769. // de-interleave data and save it as an ordinary buffer attribute for now
  17770. return {
  17771. itemSize: this.itemSize,
  17772. type: this.array.constructor.name,
  17773. array: array,
  17774. normalized: this.normalized
  17775. };
  17776. } else {
  17777. // save as true interleaved attribute
  17778. if ( data.interleavedBuffers === undefined ) {
  17779. data.interleavedBuffers = {};
  17780. }
  17781. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17782. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17783. }
  17784. return {
  17785. isInterleavedBufferAttribute: true,
  17786. itemSize: this.itemSize,
  17787. data: this.data.uuid,
  17788. offset: this.offset,
  17789. normalized: this.normalized
  17790. };
  17791. }
  17792. }
  17793. }
  17794. /**
  17795. * A material for rendering instances of {@link Sprite}.
  17796. *
  17797. * ```js
  17798. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17799. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17800. *
  17801. * const sprite = new THREE.Sprite( material );
  17802. * sprite.scale.set(200, 200, 1)
  17803. * scene.add( sprite );
  17804. * ```
  17805. *
  17806. * @augments Material
  17807. */
  17808. class SpriteMaterial extends Material {
  17809. /**
  17810. * Constructs a new sprite material.
  17811. *
  17812. * @param {Object} [parameters] - An object with one or more properties
  17813. * defining the material's appearance. Any property of the material
  17814. * (including any property from inherited materials) can be passed
  17815. * in here. Color values can be passed any type of value accepted
  17816. * by {@link Color#set}.
  17817. */
  17818. constructor( parameters ) {
  17819. super();
  17820. /**
  17821. * This flag can be used for type testing.
  17822. *
  17823. * @type {boolean}
  17824. * @readonly
  17825. * @default true
  17826. */
  17827. this.isSpriteMaterial = true;
  17828. this.type = 'SpriteMaterial';
  17829. /**
  17830. * Color of the material.
  17831. *
  17832. * @type {Color}
  17833. * @default (1,1,1)
  17834. */
  17835. this.color = new Color( 0xffffff );
  17836. /**
  17837. * The color map. May optionally include an alpha channel, typically combined
  17838. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17839. * color is modulated by the diffuse `color`.
  17840. *
  17841. * @type {?Texture}
  17842. * @default null
  17843. */
  17844. this.map = null;
  17845. /**
  17846. * The alpha map is a grayscale texture that controls the opacity across the
  17847. * surface (black: fully transparent; white: fully opaque).
  17848. *
  17849. * Only the color of the texture is used, ignoring the alpha channel if one
  17850. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17851. * when sampling this texture due to the extra bit of precision provided for
  17852. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17853. * luminance/alpha textures will also still work as expected.
  17854. *
  17855. * @type {?Texture}
  17856. * @default null
  17857. */
  17858. this.alphaMap = null;
  17859. /**
  17860. * The rotation of the sprite in radians.
  17861. *
  17862. * @type {number}
  17863. * @default 0
  17864. */
  17865. this.rotation = 0;
  17866. /**
  17867. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17868. *
  17869. * @type {boolean}
  17870. * @default true
  17871. */
  17872. this.sizeAttenuation = true;
  17873. /**
  17874. * Overwritten since sprite materials are transparent
  17875. * by default.
  17876. *
  17877. * @type {boolean}
  17878. * @default true
  17879. */
  17880. this.transparent = true;
  17881. /**
  17882. * Whether the material is affected by fog or not.
  17883. *
  17884. * @type {boolean}
  17885. * @default true
  17886. */
  17887. this.fog = true;
  17888. this.setValues( parameters );
  17889. }
  17890. copy( source ) {
  17891. super.copy( source );
  17892. this.color.copy( source.color );
  17893. this.map = source.map;
  17894. this.alphaMap = source.alphaMap;
  17895. this.rotation = source.rotation;
  17896. this.sizeAttenuation = source.sizeAttenuation;
  17897. this.fog = source.fog;
  17898. return this;
  17899. }
  17900. }
  17901. let _geometry;
  17902. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17903. const _worldScale = /*@__PURE__*/ new Vector3();
  17904. const _mvPosition = /*@__PURE__*/ new Vector3();
  17905. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17906. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17907. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17908. const _vA = /*@__PURE__*/ new Vector3();
  17909. const _vB = /*@__PURE__*/ new Vector3();
  17910. const _vC = /*@__PURE__*/ new Vector3();
  17911. const _uvA = /*@__PURE__*/ new Vector2();
  17912. const _uvB = /*@__PURE__*/ new Vector2();
  17913. const _uvC = /*@__PURE__*/ new Vector2();
  17914. /**
  17915. * A sprite is a plane that always faces towards the camera, generally with a
  17916. * partially transparent texture applied.
  17917. *
  17918. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17919. * have no effect.
  17920. *
  17921. * ```js
  17922. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17923. * const material = new THREE.SpriteMaterial( { map: map } );
  17924. *
  17925. * const sprite = new THREE.Sprite( material );
  17926. * scene.add( sprite );
  17927. * ```
  17928. *
  17929. * @augments Object3D
  17930. */
  17931. class Sprite extends Object3D {
  17932. /**
  17933. * Constructs a new sprite.
  17934. *
  17935. * @param {SpriteMaterial} [material] - The sprite material.
  17936. */
  17937. constructor( material = new SpriteMaterial() ) {
  17938. super();
  17939. /**
  17940. * This flag can be used for type testing.
  17941. *
  17942. * @type {boolean}
  17943. * @readonly
  17944. * @default true
  17945. */
  17946. this.isSprite = true;
  17947. this.type = 'Sprite';
  17948. if ( _geometry === undefined ) {
  17949. _geometry = new BufferGeometry();
  17950. const float32Array = new Float32Array( [
  17951. -0.5, -0.5, 0, 0, 0,
  17952. 0.5, -0.5, 0, 1, 0,
  17953. 0.5, 0.5, 0, 1, 1,
  17954. -0.5, 0.5, 0, 0, 1
  17955. ] );
  17956. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17957. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17958. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17959. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17960. }
  17961. /**
  17962. * The sprite geometry.
  17963. *
  17964. * @type {BufferGeometry}
  17965. */
  17966. this.geometry = _geometry;
  17967. /**
  17968. * The sprite material.
  17969. *
  17970. * @type {SpriteMaterial}
  17971. */
  17972. this.material = material;
  17973. /**
  17974. * The sprite's anchor point, and the point around which the sprite rotates.
  17975. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17976. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17977. *
  17978. * @type {Vector2}
  17979. * @default (0.5,0.5)
  17980. */
  17981. this.center = new Vector2( 0.5, 0.5 );
  17982. /**
  17983. * The number of instances of this sprite.
  17984. * Can only be used with {@link WebGPURenderer}.
  17985. *
  17986. * @type {number}
  17987. * @default 1
  17988. */
  17989. this.count = 1;
  17990. }
  17991. /**
  17992. * Computes intersection points between a casted ray and this sprite.
  17993. *
  17994. * @param {Raycaster} raycaster - The raycaster.
  17995. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17996. */
  17997. raycast( raycaster, intersects ) {
  17998. if ( raycaster.camera === null ) {
  17999. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18000. }
  18001. _worldScale.setFromMatrixScale( this.matrixWorld );
  18002. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18003. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18004. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18005. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18006. _worldScale.multiplyScalar( - _mvPosition.z );
  18007. }
  18008. const rotation = this.material.rotation;
  18009. let sin, cos;
  18010. if ( rotation !== 0 ) {
  18011. cos = Math.cos( rotation );
  18012. sin = Math.sin( rotation );
  18013. }
  18014. const center = this.center;
  18015. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18016. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18017. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18018. _uvA.set( 0, 0 );
  18019. _uvB.set( 1, 0 );
  18020. _uvC.set( 1, 1 );
  18021. // check first triangle
  18022. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18023. if ( intersect === null ) {
  18024. // check second triangle
  18025. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18026. _uvB.set( 0, 1 );
  18027. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18028. if ( intersect === null ) {
  18029. return;
  18030. }
  18031. }
  18032. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18033. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18034. intersects.push( {
  18035. distance: distance,
  18036. point: _intersectPoint.clone(),
  18037. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18038. face: null,
  18039. object: this
  18040. } );
  18041. }
  18042. copy( source, recursive ) {
  18043. super.copy( source, recursive );
  18044. if ( source.center !== undefined ) this.center.copy( source.center );
  18045. this.material = source.material;
  18046. return this;
  18047. }
  18048. }
  18049. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18050. // compute position in camera space
  18051. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18052. // to check if rotation is not zero
  18053. if ( sin !== undefined ) {
  18054. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18055. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18056. } else {
  18057. _rotatedPosition.copy( _alignedPosition );
  18058. }
  18059. vertexPosition.copy( mvPosition );
  18060. vertexPosition.x += _rotatedPosition.x;
  18061. vertexPosition.y += _rotatedPosition.y;
  18062. // transform to world space
  18063. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18064. }
  18065. const _v1$2 = /*@__PURE__*/ new Vector3();
  18066. const _v2$1 = /*@__PURE__*/ new Vector3();
  18067. /**
  18068. * A component for providing a basic Level of Detail (LOD) mechanism.
  18069. *
  18070. * Every LOD level is associated with an object, and rendering can be switched
  18071. * between them at the distances specified. Typically you would create, say,
  18072. * three meshes, one for far away (low detail), one for mid range (medium
  18073. * detail) and one for close up (high detail).
  18074. *
  18075. * ```js
  18076. * const lod = new THREE.LOD();
  18077. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18078. *
  18079. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18080. * for( let i = 0; i < 3; i++ ) {
  18081. *
  18082. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18083. * const mesh = new THREE.Mesh( geometry, material );
  18084. * lod.addLevel( mesh, i * 75 );
  18085. *
  18086. * }
  18087. *
  18088. * scene.add( lod );
  18089. * ```
  18090. *
  18091. * @augments Object3D
  18092. */
  18093. class LOD extends Object3D {
  18094. /**
  18095. * Constructs a new LOD.
  18096. */
  18097. constructor() {
  18098. super();
  18099. /**
  18100. * This flag can be used for type testing.
  18101. *
  18102. * @type {boolean}
  18103. * @readonly
  18104. * @default true
  18105. */
  18106. this.isLOD = true;
  18107. /**
  18108. * The current LOD index.
  18109. *
  18110. * @private
  18111. * @type {number}
  18112. * @default 0
  18113. */
  18114. this._currentLevel = 0;
  18115. this.type = 'LOD';
  18116. Object.defineProperties( this, {
  18117. /**
  18118. * This array holds the LOD levels.
  18119. *
  18120. * @name LOD#levels
  18121. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18122. */
  18123. levels: {
  18124. enumerable: true,
  18125. value: []
  18126. }
  18127. } );
  18128. /**
  18129. * Whether the LOD object is updated automatically by the renderer per frame
  18130. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18131. * render loop by yourself.
  18132. *
  18133. * @type {boolean}
  18134. * @default true
  18135. */
  18136. this.autoUpdate = true;
  18137. }
  18138. copy( source ) {
  18139. super.copy( source, false );
  18140. const levels = source.levels;
  18141. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18142. const level = levels[ i ];
  18143. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18144. }
  18145. this.autoUpdate = source.autoUpdate;
  18146. return this;
  18147. }
  18148. /**
  18149. * Adds a mesh that will display at a certain distance and greater. Typically
  18150. * the further away the distance, the lower the detail on the mesh.
  18151. *
  18152. * @param {Object3D} object - The 3D object to display at this level.
  18153. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18154. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18155. * @return {LOD} A reference to this instance.
  18156. */
  18157. addLevel( object, distance = 0, hysteresis = 0 ) {
  18158. distance = Math.abs( distance );
  18159. const levels = this.levels;
  18160. let l;
  18161. for ( l = 0; l < levels.length; l ++ ) {
  18162. if ( distance < levels[ l ].distance ) {
  18163. break;
  18164. }
  18165. }
  18166. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18167. this.add( object );
  18168. return this;
  18169. }
  18170. /**
  18171. * Removes an existing level, based on the distance from the camera.
  18172. * Returns `true` when the level has been removed. Otherwise `false`.
  18173. *
  18174. * @param {number} distance - Distance of the level to remove.
  18175. * @return {boolean} Whether the level has been removed or not.
  18176. */
  18177. removeLevel( distance ) {
  18178. const levels = this.levels;
  18179. for ( let i = 0; i < levels.length; i ++ ) {
  18180. if ( levels[ i ].distance === distance ) {
  18181. const removedElements = levels.splice( i, 1 );
  18182. this.remove( removedElements[ 0 ].object );
  18183. return true;
  18184. }
  18185. }
  18186. return false;
  18187. }
  18188. /**
  18189. * Returns the currently active LOD level index.
  18190. *
  18191. * @return {number} The current active LOD level index.
  18192. */
  18193. getCurrentLevel() {
  18194. return this._currentLevel;
  18195. }
  18196. /**
  18197. * Returns a reference to the first 3D object that is greater than
  18198. * the given distance.
  18199. *
  18200. * @param {number} distance - The LOD distance.
  18201. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18202. */
  18203. getObjectForDistance( distance ) {
  18204. const levels = this.levels;
  18205. if ( levels.length > 0 ) {
  18206. let i, l;
  18207. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18208. let levelDistance = levels[ i ].distance;
  18209. if ( levels[ i ].object.visible ) {
  18210. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18211. }
  18212. if ( distance < levelDistance ) {
  18213. break;
  18214. }
  18215. }
  18216. return levels[ i - 1 ].object;
  18217. }
  18218. return null;
  18219. }
  18220. /**
  18221. * Computes intersection points between a casted ray and this LOD.
  18222. *
  18223. * @param {Raycaster} raycaster - The raycaster.
  18224. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18225. */
  18226. raycast( raycaster, intersects ) {
  18227. const levels = this.levels;
  18228. if ( levels.length > 0 ) {
  18229. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18230. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18231. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18232. }
  18233. }
  18234. /**
  18235. * Updates the LOD by computing which LOD level should be visible according
  18236. * to the current distance of the given camera.
  18237. *
  18238. * @param {Camera} camera - The camera the scene is rendered with.
  18239. */
  18240. update( camera ) {
  18241. const levels = this.levels;
  18242. if ( levels.length > 1 ) {
  18243. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18244. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18245. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18246. levels[ 0 ].object.visible = true;
  18247. let i, l;
  18248. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18249. let levelDistance = levels[ i ].distance;
  18250. if ( levels[ i ].object.visible ) {
  18251. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18252. }
  18253. if ( distance >= levelDistance ) {
  18254. levels[ i - 1 ].object.visible = false;
  18255. levels[ i ].object.visible = true;
  18256. } else {
  18257. break;
  18258. }
  18259. }
  18260. this._currentLevel = i - 1;
  18261. for ( ; i < l; i ++ ) {
  18262. levels[ i ].object.visible = false;
  18263. }
  18264. }
  18265. }
  18266. toJSON( meta ) {
  18267. const data = super.toJSON( meta );
  18268. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18269. data.object.levels = [];
  18270. const levels = this.levels;
  18271. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18272. const level = levels[ i ];
  18273. data.object.levels.push( {
  18274. object: level.object.uuid,
  18275. distance: level.distance,
  18276. hysteresis: level.hysteresis
  18277. } );
  18278. }
  18279. return data;
  18280. }
  18281. }
  18282. const _basePosition = /*@__PURE__*/ new Vector3();
  18283. const _skinIndex = /*@__PURE__*/ new Vector4();
  18284. const _skinWeight = /*@__PURE__*/ new Vector4();
  18285. const _vector3 = /*@__PURE__*/ new Vector3();
  18286. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18287. const _vertex = /*@__PURE__*/ new Vector3();
  18288. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18289. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18290. const _ray$2 = /*@__PURE__*/ new Ray();
  18291. /**
  18292. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18293. * vertices of the geometry with skinning/skeleton animation.
  18294. *
  18295. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18296. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18297. * vertex to a certain extend.
  18298. *
  18299. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18300. * or {@link FBXLoader } import respective models.
  18301. *
  18302. * @augments Mesh
  18303. */
  18304. class SkinnedMesh extends Mesh {
  18305. /**
  18306. * Constructs a new skinned mesh.
  18307. *
  18308. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18309. * @param {Material|Array<Material>} [material] - The mesh material.
  18310. */
  18311. constructor( geometry, material ) {
  18312. super( geometry, material );
  18313. /**
  18314. * This flag can be used for type testing.
  18315. *
  18316. * @type {boolean}
  18317. * @readonly
  18318. * @default true
  18319. */
  18320. this.isSkinnedMesh = true;
  18321. this.type = 'SkinnedMesh';
  18322. /**
  18323. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18324. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18325. * across multiple skinned meshes.
  18326. *
  18327. * @type {(AttachedBindMode|DetachedBindMode)}
  18328. * @default AttachedBindMode
  18329. */
  18330. this.bindMode = AttachedBindMode;
  18331. /**
  18332. * The base matrix that is used for the bound bone transforms.
  18333. *
  18334. * @type {Matrix4}
  18335. */
  18336. this.bindMatrix = new Matrix4();
  18337. /**
  18338. * The base matrix that is used for resetting the bound bone transforms.
  18339. *
  18340. * @type {Matrix4}
  18341. */
  18342. this.bindMatrixInverse = new Matrix4();
  18343. /**
  18344. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18345. *
  18346. * @type {?Box3}
  18347. * @default null
  18348. */
  18349. this.boundingBox = null;
  18350. /**
  18351. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18352. *
  18353. * @type {?Sphere}
  18354. * @default null
  18355. */
  18356. this.boundingSphere = null;
  18357. }
  18358. /**
  18359. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18360. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18361. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18362. * the current animation state.
  18363. */
  18364. computeBoundingBox() {
  18365. const geometry = this.geometry;
  18366. if ( this.boundingBox === null ) {
  18367. this.boundingBox = new Box3();
  18368. }
  18369. this.boundingBox.makeEmpty();
  18370. const positionAttribute = geometry.getAttribute( 'position' );
  18371. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18372. this.getVertexPosition( i, _vertex );
  18373. this.boundingBox.expandByPoint( _vertex );
  18374. }
  18375. }
  18376. /**
  18377. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18378. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18379. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18380. * per frame in order to reflect the current animation state.
  18381. */
  18382. computeBoundingSphere() {
  18383. const geometry = this.geometry;
  18384. if ( this.boundingSphere === null ) {
  18385. this.boundingSphere = new Sphere();
  18386. }
  18387. this.boundingSphere.makeEmpty();
  18388. const positionAttribute = geometry.getAttribute( 'position' );
  18389. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18390. this.getVertexPosition( i, _vertex );
  18391. this.boundingSphere.expandByPoint( _vertex );
  18392. }
  18393. }
  18394. copy( source, recursive ) {
  18395. super.copy( source, recursive );
  18396. this.bindMode = source.bindMode;
  18397. this.bindMatrix.copy( source.bindMatrix );
  18398. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18399. this.skeleton = source.skeleton;
  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. raycast( raycaster, intersects ) {
  18405. const material = this.material;
  18406. const matrixWorld = this.matrixWorld;
  18407. if ( material === undefined ) return;
  18408. // test with bounding sphere in world space
  18409. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18410. _sphere$5.copy( this.boundingSphere );
  18411. _sphere$5.applyMatrix4( matrixWorld );
  18412. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18413. // convert ray to local space of skinned mesh
  18414. _inverseMatrix$2.copy( matrixWorld ).invert();
  18415. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18416. // test with bounding box in local space
  18417. if ( this.boundingBox !== null ) {
  18418. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18419. }
  18420. // test for intersections with geometry
  18421. this._computeIntersections( raycaster, intersects, _ray$2 );
  18422. }
  18423. getVertexPosition( index, target ) {
  18424. super.getVertexPosition( index, target );
  18425. this.applyBoneTransform( index, target );
  18426. return target;
  18427. }
  18428. /**
  18429. * Binds the given skeleton to the skinned mesh.
  18430. *
  18431. * @param {Skeleton} skeleton - The skeleton to bind.
  18432. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18433. * the skinned mesh's world matrix will be used instead.
  18434. */
  18435. bind( skeleton, bindMatrix ) {
  18436. this.skeleton = skeleton;
  18437. if ( bindMatrix === undefined ) {
  18438. this.updateMatrixWorld( true );
  18439. this.skeleton.calculateInverses();
  18440. bindMatrix = this.matrixWorld;
  18441. }
  18442. this.bindMatrix.copy( bindMatrix );
  18443. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18444. }
  18445. /**
  18446. * This method sets the skinned mesh in the rest pose).
  18447. */
  18448. pose() {
  18449. this.skeleton.pose();
  18450. }
  18451. /**
  18452. * Normalizes the skin weights which are defined as a buffer attribute
  18453. * in the skinned mesh's geometry.
  18454. */
  18455. normalizeSkinWeights() {
  18456. const vector = new Vector4();
  18457. const skinWeight = this.geometry.attributes.skinWeight;
  18458. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18459. vector.fromBufferAttribute( skinWeight, i );
  18460. const scale = 1.0 / vector.manhattanLength();
  18461. if ( scale !== Infinity ) {
  18462. vector.multiplyScalar( scale );
  18463. } else {
  18464. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18465. }
  18466. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18467. }
  18468. }
  18469. updateMatrixWorld( force ) {
  18470. super.updateMatrixWorld( force );
  18471. if ( this.bindMode === AttachedBindMode ) {
  18472. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18473. } else if ( this.bindMode === DetachedBindMode ) {
  18474. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18475. } else {
  18476. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18477. }
  18478. }
  18479. /**
  18480. * Applies the bone transform associated with the given index to the given
  18481. * vertex position. Returns the updated vector.
  18482. *
  18483. * @param {number} index - The vertex index.
  18484. * @param {Vector3} target - The target object that is used to store the method's result.
  18485. * the skinned mesh's world matrix will be used instead.
  18486. * @return {Vector3} The updated vertex position.
  18487. */
  18488. applyBoneTransform( index, target ) {
  18489. const skeleton = this.skeleton;
  18490. const geometry = this.geometry;
  18491. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18492. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18493. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18494. target.set( 0, 0, 0 );
  18495. for ( let i = 0; i < 4; i ++ ) {
  18496. const weight = _skinWeight.getComponent( i );
  18497. if ( weight !== 0 ) {
  18498. const boneIndex = _skinIndex.getComponent( i );
  18499. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18500. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18501. }
  18502. }
  18503. return target.applyMatrix4( this.bindMatrixInverse );
  18504. }
  18505. }
  18506. /**
  18507. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18508. * the {@link SkinnedMesh}.
  18509. *
  18510. * ```js
  18511. * const root = new THREE.Bone();
  18512. * const child = new THREE.Bone();
  18513. *
  18514. * root.add( child );
  18515. * child.position.y = 5;
  18516. * ```
  18517. *
  18518. * @augments Object3D
  18519. */
  18520. class Bone extends Object3D {
  18521. /**
  18522. * Constructs a new bone.
  18523. */
  18524. constructor() {
  18525. super();
  18526. /**
  18527. * This flag can be used for type testing.
  18528. *
  18529. * @type {boolean}
  18530. * @readonly
  18531. * @default true
  18532. */
  18533. this.isBone = true;
  18534. this.type = 'Bone';
  18535. }
  18536. }
  18537. /**
  18538. * Creates a texture directly from raw buffer data.
  18539. *
  18540. * The interpretation of the data depends on type and format: If the type is
  18541. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18542. * texel data. If the format is `RGBAFormat`, data needs four values for
  18543. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18544. *
  18545. * @augments Texture
  18546. */
  18547. class DataTexture extends Texture {
  18548. /**
  18549. * Constructs a new data texture.
  18550. *
  18551. * @param {?TypedArray} [data=null] - The buffer data.
  18552. * @param {number} [width=1] - The width of the texture.
  18553. * @param {number} [height=1] - The height of the texture.
  18554. * @param {number} [format=RGBAFormat] - The texture format.
  18555. * @param {number} [type=UnsignedByteType] - The texture type.
  18556. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18557. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18558. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18559. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18560. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18561. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18562. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18563. */
  18564. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18565. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18566. /**
  18567. * This flag can be used for type testing.
  18568. *
  18569. * @type {boolean}
  18570. * @readonly
  18571. * @default true
  18572. */
  18573. this.isDataTexture = true;
  18574. /**
  18575. * The image definition of a data texture.
  18576. *
  18577. * @type {{data:TypedArray,width:number,height:number}}
  18578. */
  18579. this.image = { data: data, width: width, height: height };
  18580. /**
  18581. * Whether to generate mipmaps (if possible) for a texture.
  18582. *
  18583. * Overwritten and set to `false` by default.
  18584. *
  18585. * @type {boolean}
  18586. * @default false
  18587. */
  18588. this.generateMipmaps = false;
  18589. /**
  18590. * If set to `true`, the texture is flipped along the vertical axis when
  18591. * uploaded to the GPU.
  18592. *
  18593. * Overwritten and set to `false` by default.
  18594. *
  18595. * @type {boolean}
  18596. * @default false
  18597. */
  18598. this.flipY = false;
  18599. /**
  18600. * Specifies the alignment requirements for the start of each pixel row in memory.
  18601. *
  18602. * Overwritten and set to `1` by default.
  18603. *
  18604. * @type {boolean}
  18605. * @default 1
  18606. */
  18607. this.unpackAlignment = 1;
  18608. }
  18609. }
  18610. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18611. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18612. /**
  18613. * Class for representing the armatures in `three.js`. The skeleton
  18614. * is defined by a hierarchy of bones.
  18615. *
  18616. * ```js
  18617. * const bones = [];
  18618. *
  18619. * const shoulder = new THREE.Bone();
  18620. * const elbow = new THREE.Bone();
  18621. * const hand = new THREE.Bone();
  18622. *
  18623. * shoulder.add( elbow );
  18624. * elbow.add( hand );
  18625. *
  18626. * bones.push( shoulder , elbow, hand);
  18627. *
  18628. * shoulder.position.y = -5;
  18629. * elbow.position.y = 0;
  18630. * hand.position.y = 5;
  18631. *
  18632. * const armSkeleton = new THREE.Skeleton( bones );
  18633. * ```
  18634. */
  18635. class Skeleton {
  18636. /**
  18637. * Constructs a new skeleton.
  18638. *
  18639. * @param {Array<Bone>} [bones] - An array of bones.
  18640. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18641. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18642. */
  18643. constructor( bones = [], boneInverses = [] ) {
  18644. this.uuid = generateUUID();
  18645. /**
  18646. * An array of bones defining the skeleton.
  18647. *
  18648. * @type {Array<Bone>}
  18649. */
  18650. this.bones = bones.slice( 0 );
  18651. /**
  18652. * An array of bone inverse matrices.
  18653. *
  18654. * @type {Array<Matrix4>}
  18655. */
  18656. this.boneInverses = boneInverses;
  18657. /**
  18658. * An array buffer holding the bone data.
  18659. * Input data for {@link Skeleton#boneTexture}.
  18660. *
  18661. * @type {?Float32Array}
  18662. * @default null
  18663. */
  18664. this.boneMatrices = null;
  18665. /**
  18666. * A texture holding the bone data for use
  18667. * in the vertex shader.
  18668. *
  18669. * @type {?DataTexture}
  18670. * @default null
  18671. */
  18672. this.boneTexture = null;
  18673. this.init();
  18674. }
  18675. /**
  18676. * Initializes the skeleton. This method gets automatically called by the constructor
  18677. * but depending on how the skeleton is created it might be necessary to call this method
  18678. * manually.
  18679. */
  18680. init() {
  18681. const bones = this.bones;
  18682. const boneInverses = this.boneInverses;
  18683. this.boneMatrices = new Float32Array( bones.length * 16 );
  18684. // calculate inverse bone matrices if necessary
  18685. if ( boneInverses.length === 0 ) {
  18686. this.calculateInverses();
  18687. } else {
  18688. // handle special case
  18689. if ( bones.length !== boneInverses.length ) {
  18690. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18691. this.boneInverses = [];
  18692. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18693. this.boneInverses.push( new Matrix4() );
  18694. }
  18695. }
  18696. }
  18697. }
  18698. /**
  18699. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18700. * and fills it with new matrices.
  18701. */
  18702. calculateInverses() {
  18703. this.boneInverses.length = 0;
  18704. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18705. const inverse = new Matrix4();
  18706. if ( this.bones[ i ] ) {
  18707. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18708. }
  18709. this.boneInverses.push( inverse );
  18710. }
  18711. }
  18712. /**
  18713. * Resets the skeleton to the base pose.
  18714. */
  18715. pose() {
  18716. // recover the bind-time world matrices
  18717. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18718. const bone = this.bones[ i ];
  18719. if ( bone ) {
  18720. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18721. }
  18722. }
  18723. // compute the local matrices, positions, rotations and scales
  18724. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18725. const bone = this.bones[ i ];
  18726. if ( bone ) {
  18727. if ( bone.parent && bone.parent.isBone ) {
  18728. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18729. bone.matrix.multiply( bone.matrixWorld );
  18730. } else {
  18731. bone.matrix.copy( bone.matrixWorld );
  18732. }
  18733. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18734. }
  18735. }
  18736. }
  18737. /**
  18738. * Resets the skeleton to the base pose.
  18739. */
  18740. update() {
  18741. const bones = this.bones;
  18742. const boneInverses = this.boneInverses;
  18743. const boneMatrices = this.boneMatrices;
  18744. const boneTexture = this.boneTexture;
  18745. // flatten bone matrices to array
  18746. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18747. // compute the offset between the current and the original transform
  18748. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18749. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18750. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18751. }
  18752. if ( boneTexture !== null ) {
  18753. boneTexture.needsUpdate = true;
  18754. }
  18755. }
  18756. /**
  18757. * Returns a new skeleton with copied values from this instance.
  18758. *
  18759. * @return {Skeleton} A clone of this instance.
  18760. */
  18761. clone() {
  18762. return new Skeleton( this.bones, this.boneInverses );
  18763. }
  18764. /**
  18765. * Computes a data texture for passing bone data to the vertex shader.
  18766. *
  18767. * @return {Skeleton} A reference of this instance.
  18768. */
  18769. computeBoneTexture() {
  18770. // layout (1 matrix = 4 pixels)
  18771. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18772. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18773. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18774. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18775. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18776. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18777. size = Math.ceil( size / 4 ) * 4;
  18778. size = Math.max( size, 4 );
  18779. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18780. boneMatrices.set( this.boneMatrices ); // copy current values
  18781. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18782. boneTexture.needsUpdate = true;
  18783. this.boneMatrices = boneMatrices;
  18784. this.boneTexture = boneTexture;
  18785. return this;
  18786. }
  18787. /**
  18788. * Searches through the skeleton's bone array and returns the first with a
  18789. * matching name.
  18790. *
  18791. * @param {string} name - The name of the bone.
  18792. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18793. */
  18794. getBoneByName( name ) {
  18795. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18796. const bone = this.bones[ i ];
  18797. if ( bone.name === name ) {
  18798. return bone;
  18799. }
  18800. }
  18801. return undefined;
  18802. }
  18803. /**
  18804. * Frees the GPU-related resources allocated by this instance. Call this
  18805. * method whenever this instance is no longer used in your app.
  18806. */
  18807. dispose( ) {
  18808. if ( this.boneTexture !== null ) {
  18809. this.boneTexture.dispose();
  18810. this.boneTexture = null;
  18811. }
  18812. }
  18813. /**
  18814. * Setups the skeleton by the given JSON and bones.
  18815. *
  18816. * @param {Object} json - The skeleton as serialized JSON.
  18817. * @param {Object<string, Bone>} bones - An array of bones.
  18818. * @return {Skeleton} A reference of this instance.
  18819. */
  18820. fromJSON( json, bones ) {
  18821. this.uuid = json.uuid;
  18822. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18823. const uuid = json.bones[ i ];
  18824. let bone = bones[ uuid ];
  18825. if ( bone === undefined ) {
  18826. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18827. bone = new Bone();
  18828. }
  18829. this.bones.push( bone );
  18830. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18831. }
  18832. this.init();
  18833. return this;
  18834. }
  18835. /**
  18836. * Serializes the skeleton into JSON.
  18837. *
  18838. * @return {Object} A JSON object representing the serialized skeleton.
  18839. * @see {@link ObjectLoader#parse}
  18840. */
  18841. toJSON() {
  18842. const data = {
  18843. metadata: {
  18844. version: 4.7,
  18845. type: 'Skeleton',
  18846. generator: 'Skeleton.toJSON'
  18847. },
  18848. bones: [],
  18849. boneInverses: []
  18850. };
  18851. data.uuid = this.uuid;
  18852. const bones = this.bones;
  18853. const boneInverses = this.boneInverses;
  18854. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18855. const bone = bones[ i ];
  18856. data.bones.push( bone.uuid );
  18857. const boneInverse = boneInverses[ i ];
  18858. data.boneInverses.push( boneInverse.toArray() );
  18859. }
  18860. return data;
  18861. }
  18862. }
  18863. /**
  18864. * An instanced version of a buffer attribute.
  18865. *
  18866. * @augments BufferAttribute
  18867. */
  18868. class InstancedBufferAttribute extends BufferAttribute {
  18869. /**
  18870. * Constructs a new instanced buffer attribute.
  18871. *
  18872. * @param {TypedArray} array - The array holding the attribute data.
  18873. * @param {number} itemSize - The item size.
  18874. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18875. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18876. */
  18877. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18878. super( array, itemSize, normalized );
  18879. /**
  18880. * This flag can be used for type testing.
  18881. *
  18882. * @type {boolean}
  18883. * @readonly
  18884. * @default true
  18885. */
  18886. this.isInstancedBufferAttribute = true;
  18887. /**
  18888. * Defines how often a value of this buffer attribute should be repeated. A
  18889. * value of one means that each value of the instanced attribute is used for
  18890. * a single instance. A value of two means that each value is used for two
  18891. * consecutive instances (and so on).
  18892. *
  18893. * @type {number}
  18894. * @default 1
  18895. */
  18896. this.meshPerAttribute = meshPerAttribute;
  18897. }
  18898. copy( source ) {
  18899. super.copy( source );
  18900. this.meshPerAttribute = source.meshPerAttribute;
  18901. return this;
  18902. }
  18903. toJSON() {
  18904. const data = super.toJSON();
  18905. data.meshPerAttribute = this.meshPerAttribute;
  18906. data.isInstancedBufferAttribute = true;
  18907. return data;
  18908. }
  18909. }
  18910. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18911. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18912. const _instanceIntersects = [];
  18913. const _box3 = /*@__PURE__*/ new Box3();
  18914. const _identity = /*@__PURE__*/ new Matrix4();
  18915. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18916. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18917. /**
  18918. * A special version of a mesh with instanced rendering support. Use
  18919. * this class if you have to render a large number of objects with the same
  18920. * geometry and material(s) but with different world transformations. The usage
  18921. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18922. * improve the overall rendering performance in your application.
  18923. *
  18924. * @augments Mesh
  18925. */
  18926. class InstancedMesh extends Mesh {
  18927. /**
  18928. * Constructs a new instanced mesh.
  18929. *
  18930. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18931. * @param {Material|Array<Material>} [material] - The mesh material.
  18932. * @param {number} count - The number of instances.
  18933. */
  18934. constructor( geometry, material, count ) {
  18935. super( geometry, material );
  18936. /**
  18937. * This flag can be used for type testing.
  18938. *
  18939. * @type {boolean}
  18940. * @readonly
  18941. * @default true
  18942. */
  18943. this.isInstancedMesh = true;
  18944. /**
  18945. * Represents the local transformation of all instances. You have to set its
  18946. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18947. * via {@link InstancedMesh#setMatrixAt}.
  18948. *
  18949. * @type {InstancedBufferAttribute}
  18950. */
  18951. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18952. /**
  18953. * Represents the color of all instances. You have to set its
  18954. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18955. * via {@link InstancedMesh#setColorAt}.
  18956. *
  18957. * @type {?InstancedBufferAttribute}
  18958. * @default null
  18959. */
  18960. this.instanceColor = null;
  18961. /**
  18962. * Represents the morph target weights of all instances. You have to set its
  18963. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18964. * via {@link InstancedMesh#setMorphAt}.
  18965. *
  18966. * @type {?DataTexture}
  18967. * @default null
  18968. */
  18969. this.morphTexture = null;
  18970. /**
  18971. * The number of instances.
  18972. *
  18973. * @type {number}
  18974. */
  18975. this.count = count;
  18976. /**
  18977. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18978. *
  18979. * @type {?Box3}
  18980. * @default null
  18981. */
  18982. this.boundingBox = null;
  18983. /**
  18984. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18985. *
  18986. * @type {?Sphere}
  18987. * @default null
  18988. */
  18989. this.boundingSphere = null;
  18990. for ( let i = 0; i < count; i ++ ) {
  18991. this.setMatrixAt( i, _identity );
  18992. }
  18993. }
  18994. /**
  18995. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18996. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18997. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18998. */
  18999. computeBoundingBox() {
  19000. const geometry = this.geometry;
  19001. const count = this.count;
  19002. if ( this.boundingBox === null ) {
  19003. this.boundingBox = new Box3();
  19004. }
  19005. if ( geometry.boundingBox === null ) {
  19006. geometry.computeBoundingBox();
  19007. }
  19008. this.boundingBox.makeEmpty();
  19009. for ( let i = 0; i < count; i ++ ) {
  19010. this.getMatrixAt( i, _instanceLocalMatrix );
  19011. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19012. this.boundingBox.union( _box3 );
  19013. }
  19014. }
  19015. /**
  19016. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19017. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19018. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19019. */
  19020. computeBoundingSphere() {
  19021. const geometry = this.geometry;
  19022. const count = this.count;
  19023. if ( this.boundingSphere === null ) {
  19024. this.boundingSphere = new Sphere();
  19025. }
  19026. if ( geometry.boundingSphere === null ) {
  19027. geometry.computeBoundingSphere();
  19028. }
  19029. this.boundingSphere.makeEmpty();
  19030. for ( let i = 0; i < count; i ++ ) {
  19031. this.getMatrixAt( i, _instanceLocalMatrix );
  19032. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19033. this.boundingSphere.union( _sphere$4 );
  19034. }
  19035. }
  19036. copy( source, recursive ) {
  19037. super.copy( source, recursive );
  19038. this.instanceMatrix.copy( source.instanceMatrix );
  19039. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19040. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19041. this.count = source.count;
  19042. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19043. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19044. return this;
  19045. }
  19046. /**
  19047. * Gets the color of the defined instance.
  19048. *
  19049. * @param {number} index - The instance index.
  19050. * @param {Color} color - The target object that is used to store the method's result.
  19051. */
  19052. getColorAt( index, color ) {
  19053. color.fromArray( this.instanceColor.array, index * 3 );
  19054. }
  19055. /**
  19056. * Gets the local transformation matrix of the defined instance.
  19057. *
  19058. * @param {number} index - The instance index.
  19059. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19060. */
  19061. getMatrixAt( index, matrix ) {
  19062. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19063. }
  19064. /**
  19065. * Gets the morph target weights of the defined instance.
  19066. *
  19067. * @param {number} index - The instance index.
  19068. * @param {Mesh} object - The target object that is used to store the method's result.
  19069. */
  19070. getMorphAt( index, object ) {
  19071. const objectInfluences = object.morphTargetInfluences;
  19072. const array = this.morphTexture.source.data.data;
  19073. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19074. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19075. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19076. objectInfluences[ i ] = array[ dataIndex + i ];
  19077. }
  19078. }
  19079. raycast( raycaster, intersects ) {
  19080. const matrixWorld = this.matrixWorld;
  19081. const raycastTimes = this.count;
  19082. _mesh$1.geometry = this.geometry;
  19083. _mesh$1.material = this.material;
  19084. if ( _mesh$1.material === undefined ) return;
  19085. // test with bounding sphere first
  19086. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19087. _sphere$4.copy( this.boundingSphere );
  19088. _sphere$4.applyMatrix4( matrixWorld );
  19089. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19090. // now test each instance
  19091. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19092. // calculate the world matrix for each instance
  19093. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19094. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19095. // the mesh represents this single instance
  19096. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19097. _mesh$1.raycast( raycaster, _instanceIntersects );
  19098. // process the result of raycast
  19099. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19100. const intersect = _instanceIntersects[ i ];
  19101. intersect.instanceId = instanceId;
  19102. intersect.object = this;
  19103. intersects.push( intersect );
  19104. }
  19105. _instanceIntersects.length = 0;
  19106. }
  19107. }
  19108. /**
  19109. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19110. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19111. *
  19112. * @param {number} index - The instance index.
  19113. * @param {Color} color - The instance color.
  19114. */
  19115. setColorAt( index, color ) {
  19116. if ( this.instanceColor === null ) {
  19117. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19118. }
  19119. color.toArray( this.instanceColor.array, index * 3 );
  19120. }
  19121. /**
  19122. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19123. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19124. *
  19125. * @param {number} index - The instance index.
  19126. * @param {Matrix4} matrix - The local transformation.
  19127. */
  19128. setMatrixAt( index, matrix ) {
  19129. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19130. }
  19131. /**
  19132. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19133. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19134. *
  19135. * @param {number} index - The instance index.
  19136. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19137. * of a single instance.
  19138. */
  19139. setMorphAt( index, object ) {
  19140. const objectInfluences = object.morphTargetInfluences;
  19141. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19142. if ( this.morphTexture === null ) {
  19143. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19144. }
  19145. const array = this.morphTexture.source.data.data;
  19146. let morphInfluencesSum = 0;
  19147. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19148. morphInfluencesSum += objectInfluences[ i ];
  19149. }
  19150. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19151. const dataIndex = len * index;
  19152. array[ dataIndex ] = morphBaseInfluence;
  19153. array.set( objectInfluences, dataIndex + 1 );
  19154. }
  19155. updateMorphTargets() {
  19156. }
  19157. /**
  19158. * Frees the GPU-related resources allocated by this instance. Call this
  19159. * method whenever this instance is no longer used in your app.
  19160. */
  19161. dispose() {
  19162. this.dispatchEvent( { type: 'dispose' } );
  19163. if ( this.morphTexture !== null ) {
  19164. this.morphTexture.dispose();
  19165. this.morphTexture = null;
  19166. }
  19167. }
  19168. }
  19169. const _vector1 = /*@__PURE__*/ new Vector3();
  19170. const _vector2 = /*@__PURE__*/ new Vector3();
  19171. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19172. /**
  19173. * A two dimensional surface that extends infinitely in 3D space, represented
  19174. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19175. * by a unit length normal vector and a constant.
  19176. */
  19177. class Plane {
  19178. /**
  19179. * Constructs a new plane.
  19180. *
  19181. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19182. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19183. */
  19184. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19185. /**
  19186. * This flag can be used for type testing.
  19187. *
  19188. * @type {boolean}
  19189. * @readonly
  19190. * @default true
  19191. */
  19192. this.isPlane = true;
  19193. /**
  19194. * A unit length vector defining the normal of the plane.
  19195. *
  19196. * @type {Vector3}
  19197. */
  19198. this.normal = normal;
  19199. /**
  19200. * The signed distance from the origin to the plane.
  19201. *
  19202. * @type {number}
  19203. * @default 0
  19204. */
  19205. this.constant = constant;
  19206. }
  19207. /**
  19208. * Sets the plane components by copying the given values.
  19209. *
  19210. * @param {Vector3} normal - The normal.
  19211. * @param {number} constant - The constant.
  19212. * @return {Plane} A reference to this plane.
  19213. */
  19214. set( normal, constant ) {
  19215. this.normal.copy( normal );
  19216. this.constant = constant;
  19217. return this;
  19218. }
  19219. /**
  19220. * Sets the plane components by defining `x`, `y`, `z` as the
  19221. * plane normal and `w` as the constant.
  19222. *
  19223. * @param {number} x - The value for the normal's x component.
  19224. * @param {number} y - The value for the normal's y component.
  19225. * @param {number} z - The value for the normal's z component.
  19226. * @param {number} w - The constant value.
  19227. * @return {Plane} A reference to this plane.
  19228. */
  19229. setComponents( x, y, z, w ) {
  19230. this.normal.set( x, y, z );
  19231. this.constant = w;
  19232. return this;
  19233. }
  19234. /**
  19235. * Sets the plane from the given normal and coplanar point (that is a point
  19236. * that lies onto the plane).
  19237. *
  19238. * @param {Vector3} normal - The normal.
  19239. * @param {Vector3} point - A coplanar point.
  19240. * @return {Plane} A reference to this plane.
  19241. */
  19242. setFromNormalAndCoplanarPoint( normal, point ) {
  19243. this.normal.copy( normal );
  19244. this.constant = - point.dot( this.normal );
  19245. return this;
  19246. }
  19247. /**
  19248. * Sets the plane from three coplanar points. The winding order is
  19249. * assumed to be counter-clockwise, and determines the direction of
  19250. * the plane normal.
  19251. *
  19252. * @param {Vector3} a - The first coplanar point.
  19253. * @param {Vector3} b - The second coplanar point.
  19254. * @param {Vector3} c - The third coplanar point.
  19255. * @return {Plane} A reference to this plane.
  19256. */
  19257. setFromCoplanarPoints( a, b, c ) {
  19258. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19259. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19260. this.setFromNormalAndCoplanarPoint( normal, a );
  19261. return this;
  19262. }
  19263. /**
  19264. * Copies the values of the given plane to this instance.
  19265. *
  19266. * @param {Plane} plane - The plane to copy.
  19267. * @return {Plane} A reference to this plane.
  19268. */
  19269. copy( plane ) {
  19270. this.normal.copy( plane.normal );
  19271. this.constant = plane.constant;
  19272. return this;
  19273. }
  19274. /**
  19275. * Normalizes the plane normal and adjusts the constant accordingly.
  19276. *
  19277. * @return {Plane} A reference to this plane.
  19278. */
  19279. normalize() {
  19280. // Note: will lead to a divide by zero if the plane is invalid.
  19281. const inverseNormalLength = 1.0 / this.normal.length();
  19282. this.normal.multiplyScalar( inverseNormalLength );
  19283. this.constant *= inverseNormalLength;
  19284. return this;
  19285. }
  19286. /**
  19287. * Negates both the plane normal and the constant.
  19288. *
  19289. * @return {Plane} A reference to this plane.
  19290. */
  19291. negate() {
  19292. this.constant *= -1;
  19293. this.normal.negate();
  19294. return this;
  19295. }
  19296. /**
  19297. * Returns the signed distance from the given point to this plane.
  19298. *
  19299. * @param {Vector3} point - The point to compute the distance for.
  19300. * @return {number} The signed distance.
  19301. */
  19302. distanceToPoint( point ) {
  19303. return this.normal.dot( point ) + this.constant;
  19304. }
  19305. /**
  19306. * Returns the signed distance from the given sphere to this plane.
  19307. *
  19308. * @param {Sphere} sphere - The sphere to compute the distance for.
  19309. * @return {number} The signed distance.
  19310. */
  19311. distanceToSphere( sphere ) {
  19312. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19313. }
  19314. /**
  19315. * Projects a the given point onto the plane.
  19316. *
  19317. * @param {Vector3} point - The point to project.
  19318. * @param {Vector3} target - The target vector that is used to store the method's result.
  19319. * @return {Vector3} The projected point on the plane.
  19320. */
  19321. projectPoint( point, target ) {
  19322. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19323. }
  19324. /**
  19325. * Returns the intersection point of the passed line and the plane. Returns
  19326. * `null` if the line does not intersect. Returns the line's starting point if
  19327. * the line is coplanar with the plane.
  19328. *
  19329. * @param {Line3} line - The line to compute the intersection for.
  19330. * @param {Vector3} target - The target vector that is used to store the method's result.
  19331. * @return {?Vector3} The intersection point.
  19332. */
  19333. intersectLine( line, target ) {
  19334. const direction = line.delta( _vector1 );
  19335. const denominator = this.normal.dot( direction );
  19336. if ( denominator === 0 ) {
  19337. // line is coplanar, return origin
  19338. if ( this.distanceToPoint( line.start ) === 0 ) {
  19339. return target.copy( line.start );
  19340. }
  19341. // Unsure if this is the correct method to handle this case.
  19342. return null;
  19343. }
  19344. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19345. if ( t < 0 || t > 1 ) {
  19346. return null;
  19347. }
  19348. return target.copy( line.start ).addScaledVector( direction, t );
  19349. }
  19350. /**
  19351. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19352. *
  19353. * @param {Line3} line - The line to test.
  19354. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19355. */
  19356. intersectsLine( line ) {
  19357. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19358. const startSign = this.distanceToPoint( line.start );
  19359. const endSign = this.distanceToPoint( line.end );
  19360. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19361. }
  19362. /**
  19363. * Returns `true` if the given bounding box intersects with the plane.
  19364. *
  19365. * @param {Box3} box - The bounding box to test.
  19366. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19367. */
  19368. intersectsBox( box ) {
  19369. return box.intersectsPlane( this );
  19370. }
  19371. /**
  19372. * Returns `true` if the given bounding sphere intersects with the plane.
  19373. *
  19374. * @param {Sphere} sphere - The bounding sphere to test.
  19375. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19376. */
  19377. intersectsSphere( sphere ) {
  19378. return sphere.intersectsPlane( this );
  19379. }
  19380. /**
  19381. * Returns a coplanar vector to the plane, by calculating the
  19382. * projection of the normal at the origin onto the plane.
  19383. *
  19384. * @param {Vector3} target - The target vector that is used to store the method's result.
  19385. * @return {Vector3} The coplanar point.
  19386. */
  19387. coplanarPoint( target ) {
  19388. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19389. }
  19390. /**
  19391. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19392. *
  19393. * The optional normal matrix can be pre-computed like so:
  19394. * ```js
  19395. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19396. * ```
  19397. *
  19398. * @param {Matrix4} matrix - The transformation matrix.
  19399. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19400. * @return {Plane} A reference to this plane.
  19401. */
  19402. applyMatrix4( matrix, optionalNormalMatrix ) {
  19403. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19404. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19405. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19406. this.constant = - referencePoint.dot( normal );
  19407. return this;
  19408. }
  19409. /**
  19410. * Translates the plane by the distance defined by the given offset vector.
  19411. * Note that this only affects the plane constant and will not affect the normal vector.
  19412. *
  19413. * @param {Vector3} offset - The offset vector.
  19414. * @return {Plane} A reference to this plane.
  19415. */
  19416. translate( offset ) {
  19417. this.constant -= offset.dot( this.normal );
  19418. return this;
  19419. }
  19420. /**
  19421. * Returns `true` if this plane is equal with the given one.
  19422. *
  19423. * @param {Plane} plane - The plane to test for equality.
  19424. * @return {boolean} Whether this plane is equal with the given one.
  19425. */
  19426. equals( plane ) {
  19427. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19428. }
  19429. /**
  19430. * Returns a new plane with copied values from this instance.
  19431. *
  19432. * @return {Plane} A clone of this instance.
  19433. */
  19434. clone() {
  19435. return new this.constructor().copy( this );
  19436. }
  19437. }
  19438. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19439. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19440. const _vector$6 = /*@__PURE__*/ new Vector3();
  19441. /**
  19442. * Frustums are used to determine what is inside the camera's field of view.
  19443. * They help speed up the rendering process - objects which lie outside a camera's
  19444. * frustum can safely be excluded from rendering.
  19445. *
  19446. * This class is mainly intended for use internally by a renderer.
  19447. */
  19448. class Frustum {
  19449. /**
  19450. * Constructs a new frustum.
  19451. *
  19452. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19453. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19454. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19455. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19456. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19457. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19458. */
  19459. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19460. /**
  19461. * This array holds the planes that enclose the frustum.
  19462. *
  19463. * @type {Array<Plane>}
  19464. */
  19465. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19466. }
  19467. /**
  19468. * Sets the frustum planes by copying the given planes.
  19469. *
  19470. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19471. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19472. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19473. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19474. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19475. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19476. * @return {Frustum} A reference to this frustum.
  19477. */
  19478. set( p0, p1, p2, p3, p4, p5 ) {
  19479. const planes = this.planes;
  19480. planes[ 0 ].copy( p0 );
  19481. planes[ 1 ].copy( p1 );
  19482. planes[ 2 ].copy( p2 );
  19483. planes[ 3 ].copy( p3 );
  19484. planes[ 4 ].copy( p4 );
  19485. planes[ 5 ].copy( p5 );
  19486. return this;
  19487. }
  19488. /**
  19489. * Copies the values of the given frustum to this instance.
  19490. *
  19491. * @param {Frustum} frustum - The frustum to copy.
  19492. * @return {Frustum} A reference to this frustum.
  19493. */
  19494. copy( frustum ) {
  19495. const planes = this.planes;
  19496. for ( let i = 0; i < 6; i ++ ) {
  19497. planes[ i ].copy( frustum.planes[ i ] );
  19498. }
  19499. return this;
  19500. }
  19501. /**
  19502. * Sets the frustum planes from the given projection matrix.
  19503. *
  19504. * @param {Matrix4} m - The projection matrix.
  19505. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19506. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19507. * @return {Frustum} A reference to this frustum.
  19508. */
  19509. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19510. const planes = this.planes;
  19511. const me = m.elements;
  19512. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19513. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19514. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19515. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19516. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19517. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19518. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19519. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19520. if ( reversedDepth ) {
  19521. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19522. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19523. } else {
  19524. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19525. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19526. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19527. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19528. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19529. } else {
  19530. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19531. }
  19532. }
  19533. return this;
  19534. }
  19535. /**
  19536. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19537. *
  19538. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19539. *
  19540. * @param {Object3D} object - The 3D object to test.
  19541. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19542. */
  19543. intersectsObject( object ) {
  19544. if ( object.boundingSphere !== undefined ) {
  19545. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19546. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19547. } else {
  19548. const geometry = object.geometry;
  19549. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19550. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19551. }
  19552. return this.intersectsSphere( _sphere$3 );
  19553. }
  19554. /**
  19555. * Returns `true` if the given sprite is intersecting this frustum.
  19556. *
  19557. * @param {Sprite} sprite - The sprite to test.
  19558. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19559. */
  19560. intersectsSprite( sprite ) {
  19561. _sphere$3.center.set( 0, 0, 0 );
  19562. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19563. _sphere$3.radius = 0.7071067811865476 + offset;
  19564. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19565. return this.intersectsSphere( _sphere$3 );
  19566. }
  19567. /**
  19568. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19569. *
  19570. * @param {Sphere} sphere - The bounding sphere to test.
  19571. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19572. */
  19573. intersectsSphere( sphere ) {
  19574. const planes = this.planes;
  19575. const center = sphere.center;
  19576. const negRadius = - sphere.radius;
  19577. for ( let i = 0; i < 6; i ++ ) {
  19578. const distance = planes[ i ].distanceToPoint( center );
  19579. if ( distance < negRadius ) {
  19580. return false;
  19581. }
  19582. }
  19583. return true;
  19584. }
  19585. /**
  19586. * Returns `true` if the given bounding box is intersecting this frustum.
  19587. *
  19588. * @param {Box3} box - The bounding box to test.
  19589. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19590. */
  19591. intersectsBox( box ) {
  19592. const planes = this.planes;
  19593. for ( let i = 0; i < 6; i ++ ) {
  19594. const plane = planes[ i ];
  19595. // corner at max distance
  19596. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19597. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19598. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19599. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19600. return false;
  19601. }
  19602. }
  19603. return true;
  19604. }
  19605. /**
  19606. * Returns `true` if the given point lies within the frustum.
  19607. *
  19608. * @param {Vector3} point - The point to test.
  19609. * @return {boolean} Whether the point lies within this frustum or not.
  19610. */
  19611. containsPoint( point ) {
  19612. const planes = this.planes;
  19613. for ( let i = 0; i < 6; i ++ ) {
  19614. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19615. return false;
  19616. }
  19617. }
  19618. return true;
  19619. }
  19620. /**
  19621. * Returns a new frustum with copied values from this instance.
  19622. *
  19623. * @return {Frustum} A clone of this instance.
  19624. */
  19625. clone() {
  19626. return new this.constructor().copy( this );
  19627. }
  19628. }
  19629. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19630. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19631. /**
  19632. * FrustumArray is used to determine if an object is visible in at least one camera
  19633. * from an array of cameras. This is particularly useful for multi-view renderers.
  19634. */
  19635. class FrustumArray {
  19636. /**
  19637. * Constructs a new frustum array.
  19638. *
  19639. */
  19640. constructor() {
  19641. /**
  19642. * The coordinate system to use.
  19643. *
  19644. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19645. * @default WebGLCoordinateSystem
  19646. */
  19647. this.coordinateSystem = WebGLCoordinateSystem;
  19648. }
  19649. /**
  19650. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19651. * from the camera array.
  19652. *
  19653. * @param {Object3D} object - The 3D object to test.
  19654. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19655. * @return {boolean} Whether the 3D object is visible in any camera.
  19656. */
  19657. intersectsObject( object, cameraArray ) {
  19658. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19659. return false;
  19660. }
  19661. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19662. const camera = cameraArray.cameras[ i ];
  19663. _projScreenMatrix$2.multiplyMatrices(
  19664. camera.projectionMatrix,
  19665. camera.matrixWorldInverse
  19666. );
  19667. _frustum$1.setFromProjectionMatrix(
  19668. _projScreenMatrix$2,
  19669. this.coordinateSystem
  19670. );
  19671. if ( _frustum$1.intersectsObject( object ) ) {
  19672. return true; // Object is visible in at least one camera
  19673. }
  19674. }
  19675. return false; // Not visible in any camera
  19676. }
  19677. /**
  19678. * Returns `true` if the given sprite is intersecting any frustum
  19679. * from the camera array.
  19680. *
  19681. * @param {Sprite} sprite - The sprite to test.
  19682. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19683. * @return {boolean} Whether the sprite is visible in any camera.
  19684. */
  19685. intersectsSprite( sprite, cameraArray ) {
  19686. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19687. return false;
  19688. }
  19689. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19690. const camera = cameraArray.cameras[ i ];
  19691. _projScreenMatrix$2.multiplyMatrices(
  19692. camera.projectionMatrix,
  19693. camera.matrixWorldInverse
  19694. );
  19695. _frustum$1.setFromProjectionMatrix(
  19696. _projScreenMatrix$2,
  19697. this.coordinateSystem
  19698. );
  19699. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19700. return true; // Sprite is visible in at least one camera
  19701. }
  19702. }
  19703. return false; // Not visible in any camera
  19704. }
  19705. /**
  19706. * Returns `true` if the given bounding sphere is intersecting any frustum
  19707. * from the camera array.
  19708. *
  19709. * @param {Sphere} sphere - The bounding sphere to test.
  19710. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19711. * @return {boolean} Whether the sphere is visible in any camera.
  19712. */
  19713. intersectsSphere( sphere, cameraArray ) {
  19714. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19715. return false;
  19716. }
  19717. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19718. const camera = cameraArray.cameras[ i ];
  19719. _projScreenMatrix$2.multiplyMatrices(
  19720. camera.projectionMatrix,
  19721. camera.matrixWorldInverse
  19722. );
  19723. _frustum$1.setFromProjectionMatrix(
  19724. _projScreenMatrix$2,
  19725. this.coordinateSystem
  19726. );
  19727. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19728. return true; // Sphere is visible in at least one camera
  19729. }
  19730. }
  19731. return false; // Not visible in any camera
  19732. }
  19733. /**
  19734. * Returns `true` if the given bounding box is intersecting any frustum
  19735. * from the camera array.
  19736. *
  19737. * @param {Box3} box - The bounding box to test.
  19738. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19739. * @return {boolean} Whether the box is visible in any camera.
  19740. */
  19741. intersectsBox( box, cameraArray ) {
  19742. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19743. return false;
  19744. }
  19745. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19746. const camera = cameraArray.cameras[ i ];
  19747. _projScreenMatrix$2.multiplyMatrices(
  19748. camera.projectionMatrix,
  19749. camera.matrixWorldInverse
  19750. );
  19751. _frustum$1.setFromProjectionMatrix(
  19752. _projScreenMatrix$2,
  19753. this.coordinateSystem
  19754. );
  19755. if ( _frustum$1.intersectsBox( box ) ) {
  19756. return true; // Box is visible in at least one camera
  19757. }
  19758. }
  19759. return false; // Not visible in any camera
  19760. }
  19761. /**
  19762. * Returns `true` if the given point lies within any frustum
  19763. * from the camera array.
  19764. *
  19765. * @param {Vector3} point - The point to test.
  19766. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19767. * @return {boolean} Whether the point is visible in any camera.
  19768. */
  19769. containsPoint( point, cameraArray ) {
  19770. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19771. return false;
  19772. }
  19773. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19774. const camera = cameraArray.cameras[ i ];
  19775. _projScreenMatrix$2.multiplyMatrices(
  19776. camera.projectionMatrix,
  19777. camera.matrixWorldInverse
  19778. );
  19779. _frustum$1.setFromProjectionMatrix(
  19780. _projScreenMatrix$2,
  19781. this.coordinateSystem
  19782. );
  19783. if ( _frustum$1.containsPoint( point ) ) {
  19784. return true; // Point is visible in at least one camera
  19785. }
  19786. }
  19787. return false; // Not visible in any camera
  19788. }
  19789. /**
  19790. * Returns a new frustum array with copied values from this instance.
  19791. *
  19792. * @return {FrustumArray} A clone of this instance.
  19793. */
  19794. clone() {
  19795. return new FrustumArray();
  19796. }
  19797. }
  19798. function ascIdSort( a, b ) {
  19799. return a - b;
  19800. }
  19801. function sortOpaque( a, b ) {
  19802. return a.z - b.z;
  19803. }
  19804. function sortTransparent( a, b ) {
  19805. return b.z - a.z;
  19806. }
  19807. class MultiDrawRenderList {
  19808. constructor() {
  19809. this.index = 0;
  19810. this.pool = [];
  19811. this.list = [];
  19812. }
  19813. push( start, count, z, index ) {
  19814. const pool = this.pool;
  19815. const list = this.list;
  19816. if ( this.index >= pool.length ) {
  19817. pool.push( {
  19818. start: -1,
  19819. count: -1,
  19820. z: -1,
  19821. index: -1,
  19822. } );
  19823. }
  19824. const item = pool[ this.index ];
  19825. list.push( item );
  19826. this.index ++;
  19827. item.start = start;
  19828. item.count = count;
  19829. item.z = z;
  19830. item.index = index;
  19831. }
  19832. reset() {
  19833. this.list.length = 0;
  19834. this.index = 0;
  19835. }
  19836. }
  19837. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19838. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19839. const _frustum = /*@__PURE__*/ new Frustum();
  19840. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19841. const _box$1 = /*@__PURE__*/ new Box3();
  19842. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19843. const _vector$5 = /*@__PURE__*/ new Vector3();
  19844. const _forward$1 = /*@__PURE__*/ new Vector3();
  19845. const _temp = /*@__PURE__*/ new Vector3();
  19846. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19847. const _mesh = /*@__PURE__*/ new Mesh();
  19848. const _batchIntersects = [];
  19849. // copies data from attribute "src" into "target" starting at "targetOffset"
  19850. function copyAttributeData( src, target, targetOffset = 0 ) {
  19851. const itemSize = target.itemSize;
  19852. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19853. // use the component getters and setters if the array data cannot
  19854. // be copied directly
  19855. const vertexCount = src.count;
  19856. for ( let i = 0; i < vertexCount; i ++ ) {
  19857. for ( let c = 0; c < itemSize; c ++ ) {
  19858. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19859. }
  19860. }
  19861. } else {
  19862. // faster copy approach using typed array set function
  19863. target.array.set( src.array, targetOffset * itemSize );
  19864. }
  19865. target.needsUpdate = true;
  19866. }
  19867. // safely copies array contents to a potentially smaller array
  19868. function copyArrayContents( src, target ) {
  19869. if ( src.constructor !== target.constructor ) {
  19870. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19871. const len = Math.min( src.length, target.length );
  19872. for ( let i = 0; i < len; i ++ ) {
  19873. target[ i ] = src[ i ];
  19874. }
  19875. } else {
  19876. // if the arrays use the same data layout we can use a fast block copy
  19877. const len = Math.min( src.length, target.length );
  19878. target.set( new src.constructor( src.buffer, 0, len ) );
  19879. }
  19880. }
  19881. /**
  19882. * A special version of a mesh with multi draw batch rendering support. Use
  19883. * this class if you have to render a large number of objects with the same
  19884. * material but with different geometries or world transformations. The usage of
  19885. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19886. * rendering performance in your application.
  19887. *
  19888. * ```js
  19889. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19890. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19891. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19892. *
  19893. * // initialize and add geometries into the batched mesh
  19894. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19895. * const boxGeometryId = batchedMesh.addGeometry( box );
  19896. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19897. *
  19898. * // create instances of those geometries
  19899. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19900. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19901. *
  19902. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19903. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19904. *
  19905. * // position the geometries
  19906. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19907. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19908. *
  19909. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19910. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19911. *
  19912. * scene.add( batchedMesh );
  19913. * ```
  19914. *
  19915. * @augments Mesh
  19916. */
  19917. class BatchedMesh extends Mesh {
  19918. /**
  19919. * Constructs a new batched mesh.
  19920. *
  19921. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19922. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19923. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19924. * @param {Material|Array<Material>} [material] - The mesh material.
  19925. */
  19926. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19927. super( new BufferGeometry(), material );
  19928. /**
  19929. * This flag can be used for type testing.
  19930. *
  19931. * @type {boolean}
  19932. * @readonly
  19933. * @default true
  19934. */
  19935. this.isBatchedMesh = true;
  19936. /**
  19937. * When set ot `true`, the individual objects of a batch are frustum culled.
  19938. *
  19939. * @type {boolean}
  19940. * @default true
  19941. */
  19942. this.perObjectFrustumCulled = true;
  19943. /**
  19944. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19945. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19946. * rendered front to back.
  19947. *
  19948. * @type {boolean}
  19949. * @default true
  19950. */
  19951. this.sortObjects = true;
  19952. /**
  19953. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19954. *
  19955. * @type {?Box3}
  19956. * @default null
  19957. */
  19958. this.boundingBox = null;
  19959. /**
  19960. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19961. *
  19962. * @type {?Sphere}
  19963. * @default null
  19964. */
  19965. this.boundingSphere = null;
  19966. /**
  19967. * Takes a sort a function that is run before render. The function takes a list of instances to
  19968. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19969. * sort with.
  19970. *
  19971. * @type {?Function}
  19972. * @default null
  19973. */
  19974. this.customSort = null;
  19975. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19976. this._instanceInfo = [];
  19977. this._geometryInfo = [];
  19978. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19979. this._availableInstanceIds = [];
  19980. this._availableGeometryIds = [];
  19981. // used to track where the next point is that geometry should be inserted
  19982. this._nextIndexStart = 0;
  19983. this._nextVertexStart = 0;
  19984. this._geometryCount = 0;
  19985. // flags
  19986. this._visibilityChanged = true;
  19987. this._geometryInitialized = false;
  19988. // cached user options
  19989. this._maxInstanceCount = maxInstanceCount;
  19990. this._maxVertexCount = maxVertexCount;
  19991. this._maxIndexCount = maxIndexCount;
  19992. // buffers for multi draw
  19993. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19994. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19995. this._multiDrawCount = 0;
  19996. this._multiDrawInstances = null;
  19997. // Local matrix per geometry by using data texture
  19998. this._matricesTexture = null;
  19999. this._indirectTexture = null;
  20000. this._colorsTexture = null;
  20001. this._initMatricesTexture();
  20002. this._initIndirectTexture();
  20003. }
  20004. /**
  20005. * The maximum number of individual instances that can be stored in the batch.
  20006. *
  20007. * @type {number}
  20008. * @readonly
  20009. */
  20010. get maxInstanceCount() {
  20011. return this._maxInstanceCount;
  20012. }
  20013. /**
  20014. * The instance count.
  20015. *
  20016. * @type {number}
  20017. * @readonly
  20018. */
  20019. get instanceCount() {
  20020. return this._instanceInfo.length - this._availableInstanceIds.length;
  20021. }
  20022. /**
  20023. * The number of unused vertices.
  20024. *
  20025. * @type {number}
  20026. * @readonly
  20027. */
  20028. get unusedVertexCount() {
  20029. return this._maxVertexCount - this._nextVertexStart;
  20030. }
  20031. /**
  20032. * The number of unused indices.
  20033. *
  20034. * @type {number}
  20035. * @readonly
  20036. */
  20037. get unusedIndexCount() {
  20038. return this._maxIndexCount - this._nextIndexStart;
  20039. }
  20040. _initMatricesTexture() {
  20041. // layout (1 matrix = 4 pixels)
  20042. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20043. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20044. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20045. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20046. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20047. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20048. size = Math.ceil( size / 4 ) * 4;
  20049. size = Math.max( size, 4 );
  20050. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20051. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20052. this._matricesTexture = matricesTexture;
  20053. }
  20054. _initIndirectTexture() {
  20055. let size = Math.sqrt( this._maxInstanceCount );
  20056. size = Math.ceil( size );
  20057. const indirectArray = new Uint32Array( size * size );
  20058. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20059. this._indirectTexture = indirectTexture;
  20060. }
  20061. _initColorsTexture() {
  20062. let size = Math.sqrt( this._maxInstanceCount );
  20063. size = Math.ceil( size );
  20064. // 4 floats per RGBA pixel initialized to white
  20065. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20066. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20067. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20068. this._colorsTexture = colorsTexture;
  20069. }
  20070. _initializeGeometry( reference ) {
  20071. const geometry = this.geometry;
  20072. const maxVertexCount = this._maxVertexCount;
  20073. const maxIndexCount = this._maxIndexCount;
  20074. if ( this._geometryInitialized === false ) {
  20075. for ( const attributeName in reference.attributes ) {
  20076. const srcAttribute = reference.getAttribute( attributeName );
  20077. const { array, itemSize, normalized } = srcAttribute;
  20078. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20079. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20080. geometry.setAttribute( attributeName, dstAttribute );
  20081. }
  20082. if ( reference.getIndex() !== null ) {
  20083. // Reserve last u16 index for primitive restart.
  20084. const indexArray = maxVertexCount > 65535
  20085. ? new Uint32Array( maxIndexCount )
  20086. : new Uint16Array( maxIndexCount );
  20087. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20088. }
  20089. this._geometryInitialized = true;
  20090. }
  20091. }
  20092. // Make sure the geometry is compatible with the existing combined geometry attributes
  20093. _validateGeometry( geometry ) {
  20094. // check to ensure the geometries are using consistent attributes and indices
  20095. const batchGeometry = this.geometry;
  20096. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20097. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20098. }
  20099. for ( const attributeName in batchGeometry.attributes ) {
  20100. if ( ! geometry.hasAttribute( attributeName ) ) {
  20101. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20102. }
  20103. const srcAttribute = geometry.getAttribute( attributeName );
  20104. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20105. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20106. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20107. }
  20108. }
  20109. }
  20110. /**
  20111. * Validates the instance defined by the given ID.
  20112. *
  20113. * @param {number} instanceId - The instance to validate.
  20114. */
  20115. validateInstanceId( instanceId ) {
  20116. const instanceInfo = this._instanceInfo;
  20117. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20118. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20119. }
  20120. }
  20121. /**
  20122. * Validates the geometry defined by the given ID.
  20123. *
  20124. * @param {number} geometryId - The geometry to validate.
  20125. */
  20126. validateGeometryId( geometryId ) {
  20127. const geometryInfoList = this._geometryInfo;
  20128. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20129. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20130. }
  20131. }
  20132. /**
  20133. * Takes a sort a function that is run before render. The function takes a list of instances to
  20134. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20135. *
  20136. * @param {Function} func - The custom sort function.
  20137. * @return {BatchedMesh} A reference to this batched mesh.
  20138. */
  20139. setCustomSort( func ) {
  20140. this.customSort = func;
  20141. return this;
  20142. }
  20143. /**
  20144. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20145. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20146. * otherwise they are `null`.
  20147. */
  20148. computeBoundingBox() {
  20149. if ( this.boundingBox === null ) {
  20150. this.boundingBox = new Box3();
  20151. }
  20152. const boundingBox = this.boundingBox;
  20153. const instanceInfo = this._instanceInfo;
  20154. boundingBox.makeEmpty();
  20155. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20156. if ( instanceInfo[ i ].active === false ) continue;
  20157. const geometryId = instanceInfo[ i ].geometryIndex;
  20158. this.getMatrixAt( i, _matrix$1 );
  20159. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20160. boundingBox.union( _box$1 );
  20161. }
  20162. }
  20163. /**
  20164. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20165. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20166. * otherwise they are `null`.
  20167. */
  20168. computeBoundingSphere() {
  20169. if ( this.boundingSphere === null ) {
  20170. this.boundingSphere = new Sphere();
  20171. }
  20172. const boundingSphere = this.boundingSphere;
  20173. const instanceInfo = this._instanceInfo;
  20174. boundingSphere.makeEmpty();
  20175. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20176. if ( instanceInfo[ i ].active === false ) continue;
  20177. const geometryId = instanceInfo[ i ].geometryIndex;
  20178. this.getMatrixAt( i, _matrix$1 );
  20179. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20180. boundingSphere.union( _sphere$2 );
  20181. }
  20182. }
  20183. /**
  20184. * Adds a new instance to the batch using the geometry of the given ID and returns
  20185. * a new id referring to the new instance to be used by other functions.
  20186. *
  20187. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20188. * @return {number} The instance ID.
  20189. */
  20190. addInstance( geometryId ) {
  20191. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20192. // ensure we're not over geometry
  20193. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20194. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20195. }
  20196. const instanceInfo = {
  20197. visible: true,
  20198. active: true,
  20199. geometryIndex: geometryId,
  20200. };
  20201. let drawId = null;
  20202. // Prioritize using previously freed instance ids
  20203. if ( this._availableInstanceIds.length > 0 ) {
  20204. this._availableInstanceIds.sort( ascIdSort );
  20205. drawId = this._availableInstanceIds.shift();
  20206. this._instanceInfo[ drawId ] = instanceInfo;
  20207. } else {
  20208. drawId = this._instanceInfo.length;
  20209. this._instanceInfo.push( instanceInfo );
  20210. }
  20211. const matricesTexture = this._matricesTexture;
  20212. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20213. matricesTexture.needsUpdate = true;
  20214. const colorsTexture = this._colorsTexture;
  20215. if ( colorsTexture ) {
  20216. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20217. colorsTexture.needsUpdate = true;
  20218. }
  20219. this._visibilityChanged = true;
  20220. return drawId;
  20221. }
  20222. /**
  20223. * Adds the given geometry to the batch and returns the associated
  20224. * geometry id referring to it to be used in other functions.
  20225. *
  20226. * @param {BufferGeometry} geometry - The geometry to add.
  20227. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20228. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20229. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20230. * Defaults to the length of the given geometry vertex buffer.
  20231. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20232. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20233. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20234. * the length of the given geometry index buffer.
  20235. * @return {number} The geometry ID.
  20236. */
  20237. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20238. this._initializeGeometry( geometry );
  20239. this._validateGeometry( geometry );
  20240. const geometryInfo = {
  20241. // geometry information
  20242. vertexStart: -1,
  20243. vertexCount: -1,
  20244. reservedVertexCount: -1,
  20245. indexStart: -1,
  20246. indexCount: -1,
  20247. reservedIndexCount: -1,
  20248. // draw range information
  20249. start: -1,
  20250. count: -1,
  20251. // state
  20252. boundingBox: null,
  20253. boundingSphere: null,
  20254. active: true,
  20255. };
  20256. const geometryInfoList = this._geometryInfo;
  20257. geometryInfo.vertexStart = this._nextVertexStart;
  20258. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20259. const index = geometry.getIndex();
  20260. const hasIndex = index !== null;
  20261. if ( hasIndex ) {
  20262. geometryInfo.indexStart = this._nextIndexStart;
  20263. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20264. }
  20265. if (
  20266. geometryInfo.indexStart !== -1 &&
  20267. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20268. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20269. ) {
  20270. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20271. }
  20272. // update id
  20273. let geometryId;
  20274. if ( this._availableGeometryIds.length > 0 ) {
  20275. this._availableGeometryIds.sort( ascIdSort );
  20276. geometryId = this._availableGeometryIds.shift();
  20277. geometryInfoList[ geometryId ] = geometryInfo;
  20278. } else {
  20279. geometryId = this._geometryCount;
  20280. this._geometryCount ++;
  20281. geometryInfoList.push( geometryInfo );
  20282. }
  20283. // update the geometry
  20284. this.setGeometryAt( geometryId, geometry );
  20285. // increment the next geometry position
  20286. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20287. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20288. return geometryId;
  20289. }
  20290. /**
  20291. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20292. * is not enough space reserved for geometry. Calling this will change all instances that are
  20293. * rendering that geometry.
  20294. *
  20295. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20296. * @param {BufferGeometry} geometry - The new geometry.
  20297. * @return {number} The geometry ID.
  20298. */
  20299. setGeometryAt( geometryId, geometry ) {
  20300. if ( geometryId >= this._geometryCount ) {
  20301. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20302. }
  20303. this._validateGeometry( geometry );
  20304. const batchGeometry = this.geometry;
  20305. const hasIndex = batchGeometry.getIndex() !== null;
  20306. const dstIndex = batchGeometry.getIndex();
  20307. const srcIndex = geometry.getIndex();
  20308. const geometryInfo = this._geometryInfo[ geometryId ];
  20309. if (
  20310. hasIndex &&
  20311. srcIndex.count > geometryInfo.reservedIndexCount ||
  20312. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20313. ) {
  20314. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20315. }
  20316. // copy geometry buffer data over
  20317. const vertexStart = geometryInfo.vertexStart;
  20318. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20319. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20320. for ( const attributeName in batchGeometry.attributes ) {
  20321. // copy attribute data
  20322. const srcAttribute = geometry.getAttribute( attributeName );
  20323. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20324. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20325. // fill the rest in with zeroes
  20326. const itemSize = srcAttribute.itemSize;
  20327. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20328. const index = vertexStart + i;
  20329. for ( let c = 0; c < itemSize; c ++ ) {
  20330. dstAttribute.setComponent( index, c, 0 );
  20331. }
  20332. }
  20333. dstAttribute.needsUpdate = true;
  20334. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20335. }
  20336. // copy index
  20337. if ( hasIndex ) {
  20338. const indexStart = geometryInfo.indexStart;
  20339. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20340. geometryInfo.indexCount = geometry.getIndex().count;
  20341. // copy index data over
  20342. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20343. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20344. }
  20345. // fill the rest in with zeroes
  20346. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20347. dstIndex.setX( indexStart + i, vertexStart );
  20348. }
  20349. dstIndex.needsUpdate = true;
  20350. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20351. }
  20352. // update the draw range
  20353. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20354. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20355. // store the bounding boxes
  20356. geometryInfo.boundingBox = null;
  20357. if ( geometry.boundingBox !== null ) {
  20358. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20359. }
  20360. geometryInfo.boundingSphere = null;
  20361. if ( geometry.boundingSphere !== null ) {
  20362. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20363. }
  20364. this._visibilityChanged = true;
  20365. return geometryId;
  20366. }
  20367. /**
  20368. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20369. * this geometry will also be removed as a side effect.
  20370. *
  20371. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20372. * @return {BatchedMesh} A reference to this batched mesh.
  20373. */
  20374. deleteGeometry( geometryId ) {
  20375. const geometryInfoList = this._geometryInfo;
  20376. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20377. return this;
  20378. }
  20379. // delete any instances associated with this geometry
  20380. const instanceInfo = this._instanceInfo;
  20381. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20382. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20383. this.deleteInstance( i );
  20384. }
  20385. }
  20386. geometryInfoList[ geometryId ].active = false;
  20387. this._availableGeometryIds.push( geometryId );
  20388. this._visibilityChanged = true;
  20389. return this;
  20390. }
  20391. /**
  20392. * Deletes an existing instance from the batch using the given ID.
  20393. *
  20394. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20395. * @return {BatchedMesh} A reference to this batched mesh.
  20396. */
  20397. deleteInstance( instanceId ) {
  20398. this.validateInstanceId( instanceId );
  20399. this._instanceInfo[ instanceId ].active = false;
  20400. this._availableInstanceIds.push( instanceId );
  20401. this._visibilityChanged = true;
  20402. return this;
  20403. }
  20404. /**
  20405. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20406. * previously deleted geometry, freeing up space to add new geometry.
  20407. *
  20408. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20409. * @return {BatchedMesh} A reference to this batched mesh.
  20410. */
  20411. optimize() {
  20412. // track the next indices to copy data to
  20413. let nextVertexStart = 0;
  20414. let nextIndexStart = 0;
  20415. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20416. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20417. const geometryInfoList = this._geometryInfo;
  20418. const indices = geometryInfoList
  20419. .map( ( e, i ) => i )
  20420. .sort( ( a, b ) => {
  20421. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20422. } );
  20423. const geometry = this.geometry;
  20424. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20425. // if a geometry range is inactive then don't copy anything
  20426. const index = indices[ i ];
  20427. const geometryInfo = geometryInfoList[ index ];
  20428. if ( geometryInfo.active === false ) {
  20429. continue;
  20430. }
  20431. // if a geometry contains an index buffer then shift it, as well
  20432. if ( geometry.index !== null ) {
  20433. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20434. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20435. const index = geometry.index;
  20436. const array = index.array;
  20437. // shift the index pointers based on how the vertex data will shift
  20438. // adjusting the index must happen first so the original vertex start value is available
  20439. const elementDelta = nextVertexStart - vertexStart;
  20440. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20441. array[ j ] = array[ j ] + elementDelta;
  20442. }
  20443. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20444. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20445. geometryInfo.indexStart = nextIndexStart;
  20446. }
  20447. nextIndexStart += geometryInfo.reservedIndexCount;
  20448. }
  20449. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20450. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20451. const { vertexStart, reservedVertexCount } = geometryInfo;
  20452. const attributes = geometry.attributes;
  20453. for ( const key in attributes ) {
  20454. const attribute = attributes[ key ];
  20455. const { array, itemSize } = attribute;
  20456. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20457. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20458. }
  20459. geometryInfo.vertexStart = nextVertexStart;
  20460. }
  20461. nextVertexStart += geometryInfo.reservedVertexCount;
  20462. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20463. // step the next geometry points to the shifted position
  20464. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20465. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20466. }
  20467. return this;
  20468. }
  20469. /**
  20470. * Returns the bounding box for the given geometry.
  20471. *
  20472. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20473. * @param {Box3} target - The target object that is used to store the method's result.
  20474. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20475. */
  20476. getBoundingBoxAt( geometryId, target ) {
  20477. if ( geometryId >= this._geometryCount ) {
  20478. return null;
  20479. }
  20480. // compute bounding box
  20481. const geometry = this.geometry;
  20482. const geometryInfo = this._geometryInfo[ geometryId ];
  20483. if ( geometryInfo.boundingBox === null ) {
  20484. const box = new Box3();
  20485. const index = geometry.index;
  20486. const position = geometry.attributes.position;
  20487. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20488. let iv = i;
  20489. if ( index ) {
  20490. iv = index.getX( iv );
  20491. }
  20492. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20493. }
  20494. geometryInfo.boundingBox = box;
  20495. }
  20496. target.copy( geometryInfo.boundingBox );
  20497. return target;
  20498. }
  20499. /**
  20500. * Returns the bounding sphere for the given geometry.
  20501. *
  20502. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20503. * @param {Sphere} target - The target object that is used to store the method's result.
  20504. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20505. */
  20506. getBoundingSphereAt( geometryId, target ) {
  20507. if ( geometryId >= this._geometryCount ) {
  20508. return null;
  20509. }
  20510. // compute bounding sphere
  20511. const geometry = this.geometry;
  20512. const geometryInfo = this._geometryInfo[ geometryId ];
  20513. if ( geometryInfo.boundingSphere === null ) {
  20514. const sphere = new Sphere();
  20515. this.getBoundingBoxAt( geometryId, _box$1 );
  20516. _box$1.getCenter( sphere.center );
  20517. const index = geometry.index;
  20518. const position = geometry.attributes.position;
  20519. let maxRadiusSq = 0;
  20520. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20521. let iv = i;
  20522. if ( index ) {
  20523. iv = index.getX( iv );
  20524. }
  20525. _vector$5.fromBufferAttribute( position, iv );
  20526. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20527. }
  20528. sphere.radius = Math.sqrt( maxRadiusSq );
  20529. geometryInfo.boundingSphere = sphere;
  20530. }
  20531. target.copy( geometryInfo.boundingSphere );
  20532. return target;
  20533. }
  20534. /**
  20535. * Sets the given local transformation matrix to the defined instance.
  20536. * Negatively scaled matrices are not supported.
  20537. *
  20538. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20539. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20540. * @return {BatchedMesh} A reference to this batched mesh.
  20541. */
  20542. setMatrixAt( instanceId, matrix ) {
  20543. this.validateInstanceId( instanceId );
  20544. const matricesTexture = this._matricesTexture;
  20545. const matricesArray = this._matricesTexture.image.data;
  20546. matrix.toArray( matricesArray, instanceId * 16 );
  20547. matricesTexture.needsUpdate = true;
  20548. return this;
  20549. }
  20550. /**
  20551. * Returns the local transformation matrix of the defined instance.
  20552. *
  20553. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20554. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20555. * @return {Matrix4} The instance's local transformation matrix.
  20556. */
  20557. getMatrixAt( instanceId, matrix ) {
  20558. this.validateInstanceId( instanceId );
  20559. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20560. }
  20561. /**
  20562. * Sets the given color to the defined instance.
  20563. *
  20564. * @param {number} instanceId - The ID of an instance to set the color of.
  20565. * @param {Color} color - The color to set the instance to.
  20566. * @return {BatchedMesh} A reference to this batched mesh.
  20567. */
  20568. setColorAt( instanceId, color ) {
  20569. this.validateInstanceId( instanceId );
  20570. if ( this._colorsTexture === null ) {
  20571. this._initColorsTexture();
  20572. }
  20573. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20574. this._colorsTexture.needsUpdate = true;
  20575. return this;
  20576. }
  20577. /**
  20578. * Returns the color of the defined instance.
  20579. *
  20580. * @param {number} instanceId - The ID of an instance to get the color of.
  20581. * @param {Color} color - The target object that is used to store the method's result.
  20582. * @return {Color} The instance's color.
  20583. */
  20584. getColorAt( instanceId, color ) {
  20585. this.validateInstanceId( instanceId );
  20586. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20587. }
  20588. /**
  20589. * Sets the visibility of the instance.
  20590. *
  20591. * @param {number} instanceId - The id of the instance to set the visibility of.
  20592. * @param {boolean} visible - Whether the instance is visible or not.
  20593. * @return {BatchedMesh} A reference to this batched mesh.
  20594. */
  20595. setVisibleAt( instanceId, visible ) {
  20596. this.validateInstanceId( instanceId );
  20597. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20598. return this;
  20599. }
  20600. this._instanceInfo[ instanceId ].visible = visible;
  20601. this._visibilityChanged = true;
  20602. return this;
  20603. }
  20604. /**
  20605. * Returns the visibility state of the defined instance.
  20606. *
  20607. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20608. * @return {boolean} Whether the instance is visible or not.
  20609. */
  20610. getVisibleAt( instanceId ) {
  20611. this.validateInstanceId( instanceId );
  20612. return this._instanceInfo[ instanceId ].visible;
  20613. }
  20614. /**
  20615. * Sets the geometry ID of the instance at the given index.
  20616. *
  20617. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20618. * @param {number} geometryId - The geometry ID to be use by the instance.
  20619. * @return {BatchedMesh} A reference to this batched mesh.
  20620. */
  20621. setGeometryIdAt( instanceId, geometryId ) {
  20622. this.validateInstanceId( instanceId );
  20623. this.validateGeometryId( geometryId );
  20624. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20625. return this;
  20626. }
  20627. /**
  20628. * Returns the geometry ID of the defined instance.
  20629. *
  20630. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20631. * @return {number} The instance's geometry ID.
  20632. */
  20633. getGeometryIdAt( instanceId ) {
  20634. this.validateInstanceId( instanceId );
  20635. return this._instanceInfo[ instanceId ].geometryIndex;
  20636. }
  20637. /**
  20638. * Get the range representing the subset of triangles related to the attached geometry,
  20639. * indicating the starting offset and count, or `null` if invalid.
  20640. *
  20641. * @param {number} geometryId - The id of the geometry to get the range of.
  20642. * @param {Object} [target] - The target object that is used to store the method's result.
  20643. * @return {{
  20644. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20645. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20646. * start:number,count:number
  20647. * }} The result object with range data.
  20648. */
  20649. getGeometryRangeAt( geometryId, target = {} ) {
  20650. this.validateGeometryId( geometryId );
  20651. const geometryInfo = this._geometryInfo[ geometryId ];
  20652. target.vertexStart = geometryInfo.vertexStart;
  20653. target.vertexCount = geometryInfo.vertexCount;
  20654. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20655. target.indexStart = geometryInfo.indexStart;
  20656. target.indexCount = geometryInfo.indexCount;
  20657. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20658. target.start = geometryInfo.start;
  20659. target.count = geometryInfo.count;
  20660. return target;
  20661. }
  20662. /**
  20663. * Resizes the necessary buffers to support the provided number of instances.
  20664. * If the provided arguments shrink the number of instances but there are not enough
  20665. * unused Ids at the end of the list then an error is thrown.
  20666. *
  20667. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20668. */
  20669. setInstanceCount( maxInstanceCount ) {
  20670. // shrink the available instances as much as possible
  20671. const availableInstanceIds = this._availableInstanceIds;
  20672. const instanceInfo = this._instanceInfo;
  20673. availableInstanceIds.sort( ascIdSort );
  20674. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20675. instanceInfo.pop();
  20676. availableInstanceIds.pop();
  20677. }
  20678. // throw an error if it can't be shrunk to the desired size
  20679. if ( maxInstanceCount < instanceInfo.length ) {
  20680. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20681. }
  20682. // copy the multi draw counts
  20683. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20684. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20685. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20686. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20687. this._multiDrawCounts = multiDrawCounts;
  20688. this._multiDrawStarts = multiDrawStarts;
  20689. this._maxInstanceCount = maxInstanceCount;
  20690. // update texture data for instance sampling
  20691. const indirectTexture = this._indirectTexture;
  20692. const matricesTexture = this._matricesTexture;
  20693. const colorsTexture = this._colorsTexture;
  20694. indirectTexture.dispose();
  20695. this._initIndirectTexture();
  20696. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20697. matricesTexture.dispose();
  20698. this._initMatricesTexture();
  20699. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20700. if ( colorsTexture ) {
  20701. colorsTexture.dispose();
  20702. this._initColorsTexture();
  20703. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20704. }
  20705. }
  20706. /**
  20707. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20708. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20709. * end of the geometry attributes then an error is thrown.
  20710. *
  20711. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20712. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20713. */
  20714. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20715. // Check if we can shrink to the requested vertex attribute size
  20716. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20717. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20718. if ( requiredVertexLength > maxVertexCount ) {
  20719. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20720. }
  20721. // Check if we can shrink to the requested index attribute size
  20722. if ( this.geometry.index ) {
  20723. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20724. if ( requiredIndexLength > maxIndexCount ) {
  20725. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20726. }
  20727. }
  20728. //
  20729. // dispose of the previous geometry
  20730. const oldGeometry = this.geometry;
  20731. oldGeometry.dispose();
  20732. // recreate the geometry needed based on the previous variant
  20733. this._maxVertexCount = maxVertexCount;
  20734. this._maxIndexCount = maxIndexCount;
  20735. if ( this._geometryInitialized ) {
  20736. this._geometryInitialized = false;
  20737. this.geometry = new BufferGeometry();
  20738. this._initializeGeometry( oldGeometry );
  20739. }
  20740. // copy data from the previous geometry
  20741. const geometry = this.geometry;
  20742. if ( oldGeometry.index ) {
  20743. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20744. }
  20745. for ( const key in oldGeometry.attributes ) {
  20746. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20747. }
  20748. }
  20749. raycast( raycaster, intersects ) {
  20750. const instanceInfo = this._instanceInfo;
  20751. const geometryInfoList = this._geometryInfo;
  20752. const matrixWorld = this.matrixWorld;
  20753. const batchGeometry = this.geometry;
  20754. // iterate over each geometry
  20755. _mesh.material = this.material;
  20756. _mesh.geometry.index = batchGeometry.index;
  20757. _mesh.geometry.attributes = batchGeometry.attributes;
  20758. if ( _mesh.geometry.boundingBox === null ) {
  20759. _mesh.geometry.boundingBox = new Box3();
  20760. }
  20761. if ( _mesh.geometry.boundingSphere === null ) {
  20762. _mesh.geometry.boundingSphere = new Sphere();
  20763. }
  20764. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20765. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20766. continue;
  20767. }
  20768. const geometryId = instanceInfo[ i ].geometryIndex;
  20769. const geometryInfo = geometryInfoList[ geometryId ];
  20770. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20771. // get the intersects
  20772. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20773. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20774. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20775. _mesh.raycast( raycaster, _batchIntersects );
  20776. // add batch id to the intersects
  20777. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20778. const intersect = _batchIntersects[ j ];
  20779. intersect.object = this;
  20780. intersect.batchId = i;
  20781. intersects.push( intersect );
  20782. }
  20783. _batchIntersects.length = 0;
  20784. }
  20785. _mesh.material = null;
  20786. _mesh.geometry.index = null;
  20787. _mesh.geometry.attributes = {};
  20788. _mesh.geometry.setDrawRange( 0, Infinity );
  20789. }
  20790. copy( source ) {
  20791. super.copy( source );
  20792. this.geometry = source.geometry.clone();
  20793. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20794. this.sortObjects = source.sortObjects;
  20795. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20796. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20797. this._geometryInfo = source._geometryInfo.map( info => ( {
  20798. ...info,
  20799. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20800. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20801. } ) );
  20802. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20803. this._availableInstanceIds = source._availableInstanceIds.slice();
  20804. this._availableGeometryIds = source._availableGeometryIds.slice();
  20805. this._nextIndexStart = source._nextIndexStart;
  20806. this._nextVertexStart = source._nextVertexStart;
  20807. this._geometryCount = source._geometryCount;
  20808. this._maxInstanceCount = source._maxInstanceCount;
  20809. this._maxVertexCount = source._maxVertexCount;
  20810. this._maxIndexCount = source._maxIndexCount;
  20811. this._geometryInitialized = source._geometryInitialized;
  20812. this._multiDrawCounts = source._multiDrawCounts.slice();
  20813. this._multiDrawStarts = source._multiDrawStarts.slice();
  20814. this._indirectTexture = source._indirectTexture.clone();
  20815. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20816. this._matricesTexture = source._matricesTexture.clone();
  20817. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20818. if ( this._colorsTexture !== null ) {
  20819. this._colorsTexture = source._colorsTexture.clone();
  20820. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20821. }
  20822. return this;
  20823. }
  20824. /**
  20825. * Frees the GPU-related resources allocated by this instance. Call this
  20826. * method whenever this instance is no longer used in your app.
  20827. */
  20828. dispose() {
  20829. // Assuming the geometry is not shared with other meshes
  20830. this.geometry.dispose();
  20831. this._matricesTexture.dispose();
  20832. this._matricesTexture = null;
  20833. this._indirectTexture.dispose();
  20834. this._indirectTexture = null;
  20835. if ( this._colorsTexture !== null ) {
  20836. this._colorsTexture.dispose();
  20837. this._colorsTexture = null;
  20838. }
  20839. }
  20840. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20841. // if visibility has not changed and frustum culling and object sorting is not required
  20842. // then skip iterating over all items
  20843. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20844. return;
  20845. }
  20846. // the indexed version of the multi draw function requires specifying the start
  20847. // offset in bytes.
  20848. const index = geometry.getIndex();
  20849. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20850. const instanceInfo = this._instanceInfo;
  20851. const multiDrawStarts = this._multiDrawStarts;
  20852. const multiDrawCounts = this._multiDrawCounts;
  20853. const geometryInfoList = this._geometryInfo;
  20854. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20855. const indirectTexture = this._indirectTexture;
  20856. const indirectArray = indirectTexture.image.data;
  20857. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20858. // prepare the frustum in the local frame
  20859. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20860. _matrix$1
  20861. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20862. .multiply( this.matrixWorld );
  20863. _frustum.setFromProjectionMatrix(
  20864. _matrix$1,
  20865. renderer.coordinateSystem
  20866. );
  20867. }
  20868. let multiDrawCount = 0;
  20869. if ( this.sortObjects ) {
  20870. // get the camera position in the local frame
  20871. _matrix$1.copy( this.matrixWorld ).invert();
  20872. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20873. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20874. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20875. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20876. const geometryId = instanceInfo[ i ].geometryIndex;
  20877. // get the bounds in world space
  20878. this.getMatrixAt( i, _matrix$1 );
  20879. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20880. // determine whether the batched geometry is within the frustum
  20881. let culled = false;
  20882. if ( perObjectFrustumCulled ) {
  20883. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20884. }
  20885. if ( ! culled ) {
  20886. // get the distance from camera used for sorting
  20887. const geometryInfo = geometryInfoList[ geometryId ];
  20888. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20889. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20890. }
  20891. }
  20892. }
  20893. // Sort the draw ranges and prep for rendering
  20894. const list = _renderList.list;
  20895. const customSort = this.customSort;
  20896. if ( customSort === null ) {
  20897. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20898. } else {
  20899. customSort.call( this, list, camera );
  20900. }
  20901. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20902. const item = list[ i ];
  20903. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20904. multiDrawCounts[ multiDrawCount ] = item.count;
  20905. indirectArray[ multiDrawCount ] = item.index;
  20906. multiDrawCount ++;
  20907. }
  20908. _renderList.reset();
  20909. } else {
  20910. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20911. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20912. const geometryId = instanceInfo[ i ].geometryIndex;
  20913. // determine whether the batched geometry is within the frustum
  20914. let culled = false;
  20915. if ( perObjectFrustumCulled ) {
  20916. // get the bounds in world space
  20917. this.getMatrixAt( i, _matrix$1 );
  20918. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20919. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20920. }
  20921. if ( ! culled ) {
  20922. const geometryInfo = geometryInfoList[ geometryId ];
  20923. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20924. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20925. indirectArray[ multiDrawCount ] = i;
  20926. multiDrawCount ++;
  20927. }
  20928. }
  20929. }
  20930. }
  20931. indirectTexture.needsUpdate = true;
  20932. this._multiDrawCount = multiDrawCount;
  20933. this._visibilityChanged = false;
  20934. }
  20935. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20936. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20937. }
  20938. }
  20939. /**
  20940. * A material for rendering line primitives.
  20941. *
  20942. * Materials define the appearance of renderable 3D objects.
  20943. *
  20944. * ```js
  20945. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20946. * ```
  20947. *
  20948. * @augments Material
  20949. */
  20950. class LineBasicMaterial extends Material {
  20951. /**
  20952. * Constructs a new line basic material.
  20953. *
  20954. * @param {Object} [parameters] - An object with one or more properties
  20955. * defining the material's appearance. Any property of the material
  20956. * (including any property from inherited materials) can be passed
  20957. * in here. Color values can be passed any type of value accepted
  20958. * by {@link Color#set}.
  20959. */
  20960. constructor( parameters ) {
  20961. super();
  20962. /**
  20963. * This flag can be used for type testing.
  20964. *
  20965. * @type {boolean}
  20966. * @readonly
  20967. * @default true
  20968. */
  20969. this.isLineBasicMaterial = true;
  20970. this.type = 'LineBasicMaterial';
  20971. /**
  20972. * Color of the material.
  20973. *
  20974. * @type {Color}
  20975. * @default (1,1,1)
  20976. */
  20977. this.color = new Color( 0xffffff );
  20978. /**
  20979. * Sets the color of the lines using data from a texture. The texture map
  20980. * color is modulated by the diffuse `color`.
  20981. *
  20982. * @type {?Texture}
  20983. * @default null
  20984. */
  20985. this.map = null;
  20986. /**
  20987. * Controls line thickness or lines.
  20988. *
  20989. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20990. * ignore this setting and always render line primitives with a
  20991. * width of one pixel.
  20992. *
  20993. * @type {number}
  20994. * @default 1
  20995. */
  20996. this.linewidth = 1;
  20997. /**
  20998. * Defines appearance of line ends.
  20999. *
  21000. * Can only be used with {@link SVGRenderer}.
  21001. *
  21002. * @type {('butt'|'round'|'square')}
  21003. * @default 'round'
  21004. */
  21005. this.linecap = 'round';
  21006. /**
  21007. * Defines appearance of line joints.
  21008. *
  21009. * Can only be used with {@link SVGRenderer}.
  21010. *
  21011. * @type {('round'|'bevel'|'miter')}
  21012. * @default 'round'
  21013. */
  21014. this.linejoin = 'round';
  21015. /**
  21016. * Whether the material is affected by fog or not.
  21017. *
  21018. * @type {boolean}
  21019. * @default true
  21020. */
  21021. this.fog = true;
  21022. this.setValues( parameters );
  21023. }
  21024. copy( source ) {
  21025. super.copy( source );
  21026. this.color.copy( source.color );
  21027. this.map = source.map;
  21028. this.linewidth = source.linewidth;
  21029. this.linecap = source.linecap;
  21030. this.linejoin = source.linejoin;
  21031. this.fog = source.fog;
  21032. return this;
  21033. }
  21034. }
  21035. const _vStart = /*@__PURE__*/ new Vector3();
  21036. const _vEnd = /*@__PURE__*/ new Vector3();
  21037. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21038. const _ray$1 = /*@__PURE__*/ new Ray();
  21039. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21040. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21041. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21042. /**
  21043. * A continuous line. The line are rendered by connecting consecutive
  21044. * vertices with straight lines.
  21045. *
  21046. * ```js
  21047. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21048. *
  21049. * const points = [];
  21050. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21051. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21052. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21053. *
  21054. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21055. *
  21056. * const line = new THREE.Line( geometry, material );
  21057. * scene.add( line );
  21058. * ```
  21059. *
  21060. * @augments Object3D
  21061. */
  21062. class Line extends Object3D {
  21063. /**
  21064. * Constructs a new line.
  21065. *
  21066. * @param {BufferGeometry} [geometry] - The line geometry.
  21067. * @param {Material|Array<Material>} [material] - The line material.
  21068. */
  21069. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21070. super();
  21071. /**
  21072. * This flag can be used for type testing.
  21073. *
  21074. * @type {boolean}
  21075. * @readonly
  21076. * @default true
  21077. */
  21078. this.isLine = true;
  21079. this.type = 'Line';
  21080. /**
  21081. * The line geometry.
  21082. *
  21083. * @type {BufferGeometry}
  21084. */
  21085. this.geometry = geometry;
  21086. /**
  21087. * The line material.
  21088. *
  21089. * @type {Material|Array<Material>}
  21090. * @default LineBasicMaterial
  21091. */
  21092. this.material = material;
  21093. /**
  21094. * A dictionary representing the morph targets in the geometry. The key is the
  21095. * morph targets name, the value its attribute index. This member is `undefined`
  21096. * by default and only set when morph targets are detected in the geometry.
  21097. *
  21098. * @type {Object<String,number>|undefined}
  21099. * @default undefined
  21100. */
  21101. this.morphTargetDictionary = undefined;
  21102. /**
  21103. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21104. * is applied. This member is `undefined` by default and only set when morph targets are
  21105. * detected in the geometry.
  21106. *
  21107. * @type {Array<number>|undefined}
  21108. * @default undefined
  21109. */
  21110. this.morphTargetInfluences = undefined;
  21111. this.updateMorphTargets();
  21112. }
  21113. copy( source, recursive ) {
  21114. super.copy( source, recursive );
  21115. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21116. this.geometry = source.geometry;
  21117. return this;
  21118. }
  21119. /**
  21120. * Computes an array of distance values which are necessary for rendering dashed lines.
  21121. * For each vertex in the geometry, the method calculates the cumulative length from the
  21122. * current point to the very beginning of the line.
  21123. *
  21124. * @return {Line} A reference to this line.
  21125. */
  21126. computeLineDistances() {
  21127. const geometry = this.geometry;
  21128. // we assume non-indexed geometry
  21129. if ( geometry.index === null ) {
  21130. const positionAttribute = geometry.attributes.position;
  21131. const lineDistances = [ 0 ];
  21132. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21133. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21134. _vEnd.fromBufferAttribute( positionAttribute, i );
  21135. lineDistances[ i ] = lineDistances[ i - 1 ];
  21136. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21137. }
  21138. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21139. } else {
  21140. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21141. }
  21142. return this;
  21143. }
  21144. /**
  21145. * Computes intersection points between a casted ray and this line.
  21146. *
  21147. * @param {Raycaster} raycaster - The raycaster.
  21148. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21149. */
  21150. raycast( raycaster, intersects ) {
  21151. const geometry = this.geometry;
  21152. const matrixWorld = this.matrixWorld;
  21153. const threshold = raycaster.params.Line.threshold;
  21154. const drawRange = geometry.drawRange;
  21155. // Checking boundingSphere distance to ray
  21156. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21157. _sphere$1.copy( geometry.boundingSphere );
  21158. _sphere$1.applyMatrix4( matrixWorld );
  21159. _sphere$1.radius += threshold;
  21160. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21161. //
  21162. _inverseMatrix$1.copy( matrixWorld ).invert();
  21163. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21164. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21165. const localThresholdSq = localThreshold * localThreshold;
  21166. const step = this.isLineSegments ? 2 : 1;
  21167. const index = geometry.index;
  21168. const attributes = geometry.attributes;
  21169. const positionAttribute = attributes.position;
  21170. if ( index !== null ) {
  21171. const start = Math.max( 0, drawRange.start );
  21172. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21173. for ( let i = start, l = end - 1; i < l; i += step ) {
  21174. const a = index.getX( i );
  21175. const b = index.getX( i + 1 );
  21176. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21177. if ( intersect ) {
  21178. intersects.push( intersect );
  21179. }
  21180. }
  21181. if ( this.isLineLoop ) {
  21182. const a = index.getX( end - 1 );
  21183. const b = index.getX( start );
  21184. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21185. if ( intersect ) {
  21186. intersects.push( intersect );
  21187. }
  21188. }
  21189. } else {
  21190. const start = Math.max( 0, drawRange.start );
  21191. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21192. for ( let i = start, l = end - 1; i < l; i += step ) {
  21193. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21194. if ( intersect ) {
  21195. intersects.push( intersect );
  21196. }
  21197. }
  21198. if ( this.isLineLoop ) {
  21199. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21200. if ( intersect ) {
  21201. intersects.push( intersect );
  21202. }
  21203. }
  21204. }
  21205. }
  21206. /**
  21207. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21208. * to make sure existing morph targets can influence this 3D object.
  21209. */
  21210. updateMorphTargets() {
  21211. const geometry = this.geometry;
  21212. const morphAttributes = geometry.morphAttributes;
  21213. const keys = Object.keys( morphAttributes );
  21214. if ( keys.length > 0 ) {
  21215. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21216. if ( morphAttribute !== undefined ) {
  21217. this.morphTargetInfluences = [];
  21218. this.morphTargetDictionary = {};
  21219. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21220. const name = morphAttribute[ m ].name || String( m );
  21221. this.morphTargetInfluences.push( 0 );
  21222. this.morphTargetDictionary[ name ] = m;
  21223. }
  21224. }
  21225. }
  21226. }
  21227. }
  21228. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21229. const positionAttribute = object.geometry.attributes.position;
  21230. _vStart.fromBufferAttribute( positionAttribute, a );
  21231. _vEnd.fromBufferAttribute( positionAttribute, b );
  21232. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21233. if ( distSq > thresholdSq ) return;
  21234. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21235. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21236. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21237. return {
  21238. distance: distance,
  21239. // What do we want? intersection point on the ray or on the segment??
  21240. // point: raycaster.ray.at( distance ),
  21241. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21242. index: i,
  21243. face: null,
  21244. faceIndex: null,
  21245. barycoord: null,
  21246. object: object
  21247. };
  21248. }
  21249. const _start = /*@__PURE__*/ new Vector3();
  21250. const _end = /*@__PURE__*/ new Vector3();
  21251. /**
  21252. * A series of lines drawn between pairs of vertices.
  21253. *
  21254. * @augments Line
  21255. */
  21256. class LineSegments extends Line {
  21257. /**
  21258. * Constructs a new line segments.
  21259. *
  21260. * @param {BufferGeometry} [geometry] - The line geometry.
  21261. * @param {Material|Array<Material>} [material] - The line material.
  21262. */
  21263. constructor( geometry, material ) {
  21264. super( geometry, material );
  21265. /**
  21266. * This flag can be used for type testing.
  21267. *
  21268. * @type {boolean}
  21269. * @readonly
  21270. * @default true
  21271. */
  21272. this.isLineSegments = true;
  21273. this.type = 'LineSegments';
  21274. }
  21275. computeLineDistances() {
  21276. const geometry = this.geometry;
  21277. // we assume non-indexed geometry
  21278. if ( geometry.index === null ) {
  21279. const positionAttribute = geometry.attributes.position;
  21280. const lineDistances = [];
  21281. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21282. _start.fromBufferAttribute( positionAttribute, i );
  21283. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21284. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21285. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21286. }
  21287. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21288. } else {
  21289. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21290. }
  21291. return this;
  21292. }
  21293. }
  21294. /**
  21295. * A continuous line. This is nearly the same as {@link Line} the only difference
  21296. * is that the last vertex is connected with the first vertex in order to close
  21297. * the line to form a loop.
  21298. *
  21299. * @augments Line
  21300. */
  21301. class LineLoop extends Line {
  21302. /**
  21303. * Constructs a new line loop.
  21304. *
  21305. * @param {BufferGeometry} [geometry] - The line geometry.
  21306. * @param {Material|Array<Material>} [material] - The line material.
  21307. */
  21308. constructor( geometry, material ) {
  21309. super( geometry, material );
  21310. /**
  21311. * This flag can be used for type testing.
  21312. *
  21313. * @type {boolean}
  21314. * @readonly
  21315. * @default true
  21316. */
  21317. this.isLineLoop = true;
  21318. this.type = 'LineLoop';
  21319. }
  21320. }
  21321. /**
  21322. * A material for rendering point primitives.
  21323. *
  21324. * Materials define the appearance of renderable 3D objects.
  21325. *
  21326. * ```js
  21327. * const vertices = [];
  21328. *
  21329. * for ( let i = 0; i < 10000; i ++ ) {
  21330. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21331. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21332. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21333. *
  21334. * vertices.push( x, y, z );
  21335. * }
  21336. *
  21337. * const geometry = new THREE.BufferGeometry();
  21338. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21339. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21340. * const points = new THREE.Points( geometry, material );
  21341. * scene.add( points );
  21342. * ```
  21343. *
  21344. * @augments Material
  21345. */
  21346. class PointsMaterial extends Material {
  21347. /**
  21348. * Constructs a new points material.
  21349. *
  21350. * @param {Object} [parameters] - An object with one or more properties
  21351. * defining the material's appearance. Any property of the material
  21352. * (including any property from inherited materials) can be passed
  21353. * in here. Color values can be passed any type of value accepted
  21354. * by {@link Color#set}.
  21355. */
  21356. constructor( parameters ) {
  21357. super();
  21358. /**
  21359. * This flag can be used for type testing.
  21360. *
  21361. * @type {boolean}
  21362. * @readonly
  21363. * @default true
  21364. */
  21365. this.isPointsMaterial = true;
  21366. this.type = 'PointsMaterial';
  21367. /**
  21368. * Color of the material.
  21369. *
  21370. * @type {Color}
  21371. * @default (1,1,1)
  21372. */
  21373. this.color = new Color( 0xffffff );
  21374. /**
  21375. * The color map. May optionally include an alpha channel, typically combined
  21376. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21377. * color is modulated by the diffuse `color`.
  21378. *
  21379. * @type {?Texture}
  21380. * @default null
  21381. */
  21382. this.map = null;
  21383. /**
  21384. * The alpha map is a grayscale texture that controls the opacity across the
  21385. * surface (black: fully transparent; white: fully opaque).
  21386. *
  21387. * Only the color of the texture is used, ignoring the alpha channel if one
  21388. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21389. * when sampling this texture due to the extra bit of precision provided for
  21390. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21391. * luminance/alpha textures will also still work as expected.
  21392. *
  21393. * @type {?Texture}
  21394. * @default null
  21395. */
  21396. this.alphaMap = null;
  21397. /**
  21398. * Defines the size of the points in pixels.
  21399. *
  21400. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete}.
  21401. *
  21402. * @type {number}
  21403. * @default 1
  21404. */
  21405. this.size = 1;
  21406. /**
  21407. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21408. *
  21409. * @type {boolean}
  21410. * @default true
  21411. */
  21412. this.sizeAttenuation = true;
  21413. /**
  21414. * Whether the material is affected by fog or not.
  21415. *
  21416. * @type {boolean}
  21417. * @default true
  21418. */
  21419. this.fog = true;
  21420. this.setValues( parameters );
  21421. }
  21422. copy( source ) {
  21423. super.copy( source );
  21424. this.color.copy( source.color );
  21425. this.map = source.map;
  21426. this.alphaMap = source.alphaMap;
  21427. this.size = source.size;
  21428. this.sizeAttenuation = source.sizeAttenuation;
  21429. this.fog = source.fog;
  21430. return this;
  21431. }
  21432. }
  21433. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21434. const _ray = /*@__PURE__*/ new Ray();
  21435. const _sphere = /*@__PURE__*/ new Sphere();
  21436. const _position$2 = /*@__PURE__*/ new Vector3();
  21437. /**
  21438. * A class for displaying points or point clouds.
  21439. *
  21440. * @augments Object3D
  21441. */
  21442. class Points extends Object3D {
  21443. /**
  21444. * Constructs a new point cloud.
  21445. *
  21446. * @param {BufferGeometry} [geometry] - The points geometry.
  21447. * @param {Material|Array<Material>} [material] - The points material.
  21448. */
  21449. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21450. super();
  21451. /**
  21452. * This flag can be used for type testing.
  21453. *
  21454. * @type {boolean}
  21455. * @readonly
  21456. * @default true
  21457. */
  21458. this.isPoints = true;
  21459. this.type = 'Points';
  21460. /**
  21461. * The points geometry.
  21462. *
  21463. * @type {BufferGeometry}
  21464. */
  21465. this.geometry = geometry;
  21466. /**
  21467. * The line material.
  21468. *
  21469. * @type {Material|Array<Material>}
  21470. * @default PointsMaterial
  21471. */
  21472. this.material = material;
  21473. /**
  21474. * A dictionary representing the morph targets in the geometry. The key is the
  21475. * morph targets name, the value its attribute index. This member is `undefined`
  21476. * by default and only set when morph targets are detected in the geometry.
  21477. *
  21478. * @type {Object<String,number>|undefined}
  21479. * @default undefined
  21480. */
  21481. this.morphTargetDictionary = undefined;
  21482. /**
  21483. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21484. * is applied. This member is `undefined` by default and only set when morph targets are
  21485. * detected in the geometry.
  21486. *
  21487. * @type {Array<number>|undefined}
  21488. * @default undefined
  21489. */
  21490. this.morphTargetInfluences = undefined;
  21491. this.updateMorphTargets();
  21492. }
  21493. copy( source, recursive ) {
  21494. super.copy( source, recursive );
  21495. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21496. this.geometry = source.geometry;
  21497. return this;
  21498. }
  21499. /**
  21500. * Computes intersection points between a casted ray and this point cloud.
  21501. *
  21502. * @param {Raycaster} raycaster - The raycaster.
  21503. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21504. */
  21505. raycast( raycaster, intersects ) {
  21506. const geometry = this.geometry;
  21507. const matrixWorld = this.matrixWorld;
  21508. const threshold = raycaster.params.Points.threshold;
  21509. const drawRange = geometry.drawRange;
  21510. // Checking boundingSphere distance to ray
  21511. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21512. _sphere.copy( geometry.boundingSphere );
  21513. _sphere.applyMatrix4( matrixWorld );
  21514. _sphere.radius += threshold;
  21515. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21516. //
  21517. _inverseMatrix.copy( matrixWorld ).invert();
  21518. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21519. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21520. const localThresholdSq = localThreshold * localThreshold;
  21521. const index = geometry.index;
  21522. const attributes = geometry.attributes;
  21523. const positionAttribute = attributes.position;
  21524. if ( index !== null ) {
  21525. const start = Math.max( 0, drawRange.start );
  21526. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21527. for ( let i = start, il = end; i < il; i ++ ) {
  21528. const a = index.getX( i );
  21529. _position$2.fromBufferAttribute( positionAttribute, a );
  21530. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21531. }
  21532. } else {
  21533. const start = Math.max( 0, drawRange.start );
  21534. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21535. for ( let i = start, l = end; i < l; i ++ ) {
  21536. _position$2.fromBufferAttribute( positionAttribute, i );
  21537. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21538. }
  21539. }
  21540. }
  21541. /**
  21542. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21543. * to make sure existing morph targets can influence this 3D object.
  21544. */
  21545. updateMorphTargets() {
  21546. const geometry = this.geometry;
  21547. const morphAttributes = geometry.morphAttributes;
  21548. const keys = Object.keys( morphAttributes );
  21549. if ( keys.length > 0 ) {
  21550. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21551. if ( morphAttribute !== undefined ) {
  21552. this.morphTargetInfluences = [];
  21553. this.morphTargetDictionary = {};
  21554. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21555. const name = morphAttribute[ m ].name || String( m );
  21556. this.morphTargetInfluences.push( 0 );
  21557. this.morphTargetDictionary[ name ] = m;
  21558. }
  21559. }
  21560. }
  21561. }
  21562. }
  21563. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21564. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21565. if ( rayPointDistanceSq < localThresholdSq ) {
  21566. const intersectPoint = new Vector3();
  21567. _ray.closestPointToPoint( point, intersectPoint );
  21568. intersectPoint.applyMatrix4( matrixWorld );
  21569. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21570. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21571. intersects.push( {
  21572. distance: distance,
  21573. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21574. point: intersectPoint,
  21575. index: index,
  21576. face: null,
  21577. faceIndex: null,
  21578. barycoord: null,
  21579. object: object
  21580. } );
  21581. }
  21582. }
  21583. /**
  21584. * A texture for use with a video.
  21585. *
  21586. * ```js
  21587. * // assuming you have created a HTML video element with id="video"
  21588. * const video = document.getElementById( 'video' );
  21589. * const texture = new THREE.VideoTexture( video );
  21590. * ```
  21591. *
  21592. * Note: After the initial use of a texture, its dimensions, format, and type
  21593. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21594. *
  21595. * @augments Texture
  21596. */
  21597. class VideoTexture extends Texture {
  21598. /**
  21599. * Constructs a new video texture.
  21600. *
  21601. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21602. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21603. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21604. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21605. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21606. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21607. * @param {number} [format=RGBAFormat] - The texture format.
  21608. * @param {number} [type=UnsignedByteType] - The texture type.
  21609. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21610. */
  21611. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21612. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21613. /**
  21614. * This flag can be used for type testing.
  21615. *
  21616. * @type {boolean}
  21617. * @readonly
  21618. * @default true
  21619. */
  21620. this.isVideoTexture = true;
  21621. /**
  21622. * Whether to generate mipmaps (if possible) for a texture.
  21623. *
  21624. * Overwritten and set to `false` by default.
  21625. *
  21626. * @type {boolean}
  21627. * @default false
  21628. */
  21629. this.generateMipmaps = false;
  21630. /**
  21631. * The video frame request callback identifier, which is a positive integer.
  21632. *
  21633. * Value of 0 represents no scheduled rVFC.
  21634. *
  21635. * @private
  21636. * @type {number}
  21637. */
  21638. this._requestVideoFrameCallbackId = 0;
  21639. const scope = this;
  21640. function updateVideo() {
  21641. scope.needsUpdate = true;
  21642. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21643. }
  21644. if ( 'requestVideoFrameCallback' in video ) {
  21645. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21646. }
  21647. }
  21648. clone() {
  21649. return new this.constructor( this.image ).copy( this );
  21650. }
  21651. /**
  21652. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21653. * to `true` every time a new frame is available.
  21654. *
  21655. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21656. */
  21657. update() {
  21658. const video = this.image;
  21659. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21660. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21661. this.needsUpdate = true;
  21662. }
  21663. }
  21664. /**
  21665. * @override
  21666. */
  21667. dispose() {
  21668. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21669. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21670. }
  21671. super.dispose();
  21672. }
  21673. }
  21674. /**
  21675. * This class can be used as an alternative way to define video data. Instead of using
  21676. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21677. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21678. * video frames are decoded with the WebCodecs API.
  21679. *
  21680. * ```js
  21681. * const texture = new THREE.VideoFrameTexture();
  21682. * texture.setFrame( frame );
  21683. * ```
  21684. *
  21685. * @augments VideoTexture
  21686. */
  21687. class VideoFrameTexture extends VideoTexture {
  21688. /**
  21689. * Constructs a new video frame texture.
  21690. *
  21691. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21692. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21693. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21694. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21695. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21696. * @param {number} [format=RGBAFormat] - The texture format.
  21697. * @param {number} [type=UnsignedByteType] - The texture type.
  21698. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21699. */
  21700. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21701. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21702. /**
  21703. * This flag can be used for type testing.
  21704. *
  21705. * @type {boolean}
  21706. * @readonly
  21707. * @default true
  21708. */
  21709. this.isVideoFrameTexture = true;
  21710. }
  21711. /**
  21712. * This method overwritten with an empty implementation since
  21713. * this type of texture is updated via `setFrame()`.
  21714. */
  21715. update() {}
  21716. clone() {
  21717. return new this.constructor().copy( this ); // restoring Texture.clone()
  21718. }
  21719. /**
  21720. * Sets the current frame of the video. This will automatically update the texture
  21721. * so the data can be used for rendering.
  21722. *
  21723. * @param {VideoFrame} frame - The video frame.
  21724. */
  21725. setFrame( frame ) {
  21726. this.image = frame;
  21727. this.needsUpdate = true;
  21728. }
  21729. }
  21730. /**
  21731. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21732. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21733. * as a texture for further usage.
  21734. *
  21735. * ```js
  21736. * const pixelRatio = window.devicePixelRatio;
  21737. * const textureSize = 128 * pixelRatio;
  21738. *
  21739. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21740. *
  21741. * // calculate start position for copying part of the frame data
  21742. * const vector = new Vector2();
  21743. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21744. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21745. *
  21746. * renderer.render( scene, camera );
  21747. *
  21748. * // copy part of the rendered frame into the framebuffer texture
  21749. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21750. * ```
  21751. *
  21752. * @augments Texture
  21753. */
  21754. class FramebufferTexture extends Texture {
  21755. /**
  21756. * Constructs a new framebuffer texture.
  21757. *
  21758. * @param {number} [width] - The width of the texture.
  21759. * @param {number} [height] - The height of the texture.
  21760. */
  21761. constructor( width, height ) {
  21762. super( { width, height } );
  21763. /**
  21764. * This flag can be used for type testing.
  21765. *
  21766. * @type {boolean}
  21767. * @readonly
  21768. * @default true
  21769. */
  21770. this.isFramebufferTexture = true;
  21771. /**
  21772. * How the texture is sampled when a texel covers more than one pixel.
  21773. *
  21774. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21775. *
  21776. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21777. * @default NearestFilter
  21778. */
  21779. this.magFilter = NearestFilter;
  21780. /**
  21781. * How the texture is sampled when a texel covers less than one pixel.
  21782. *
  21783. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21784. *
  21785. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21786. * @default NearestFilter
  21787. */
  21788. this.minFilter = NearestFilter;
  21789. /**
  21790. * Whether to generate mipmaps (if possible) for a texture.
  21791. *
  21792. * Overwritten and set to `false` by default.
  21793. *
  21794. * @type {boolean}
  21795. * @default false
  21796. */
  21797. this.generateMipmaps = false;
  21798. this.needsUpdate = true;
  21799. }
  21800. }
  21801. /**
  21802. * Creates a texture based on data in compressed form.
  21803. *
  21804. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21805. *
  21806. * @augments Texture
  21807. */
  21808. class CompressedTexture extends Texture {
  21809. /**
  21810. * Constructs a new compressed texture.
  21811. *
  21812. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21813. * the data and dimensions.
  21814. * @param {number} width - The width of the texture.
  21815. * @param {number} height - The height of the texture.
  21816. * @param {number} [format=RGBAFormat] - The texture format.
  21817. * @param {number} [type=UnsignedByteType] - The texture type.
  21818. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21819. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21820. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21821. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21822. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21823. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21824. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21825. */
  21826. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21827. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21828. /**
  21829. * This flag can be used for type testing.
  21830. *
  21831. * @type {boolean}
  21832. * @readonly
  21833. * @default true
  21834. */
  21835. this.isCompressedTexture = true;
  21836. /**
  21837. * The image property of a compressed texture just defines its dimensions.
  21838. *
  21839. * @type {{width:number,height:number}}
  21840. */
  21841. this.image = { width: width, height: height };
  21842. /**
  21843. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21844. *
  21845. * @type {Array<Object>}
  21846. */
  21847. this.mipmaps = mipmaps;
  21848. /**
  21849. * If set to `true`, the texture is flipped along the vertical axis when
  21850. * uploaded to the GPU.
  21851. *
  21852. * Overwritten and set to `false` by default since it is not possible to
  21853. * flip compressed textures.
  21854. *
  21855. * @type {boolean}
  21856. * @default false
  21857. * @readonly
  21858. */
  21859. this.flipY = false;
  21860. /**
  21861. * Whether to generate mipmaps (if possible) for a texture.
  21862. *
  21863. * Overwritten and set to `false` by default since it is not
  21864. * possible to generate mipmaps for compressed data. Mipmaps
  21865. * must be embedded in the compressed texture file.
  21866. *
  21867. * @type {boolean}
  21868. * @default false
  21869. * @readonly
  21870. */
  21871. this.generateMipmaps = false;
  21872. }
  21873. }
  21874. /**
  21875. * Creates a texture 2D array based on data in compressed form.
  21876. *
  21877. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21878. *
  21879. * @augments CompressedTexture
  21880. */
  21881. class CompressedArrayTexture extends CompressedTexture {
  21882. /**
  21883. * Constructs a new compressed array texture.
  21884. *
  21885. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21886. * the data and dimensions.
  21887. * @param {number} width - The width of the texture.
  21888. * @param {number} height - The height of the texture.
  21889. * @param {number} depth - The depth of the texture.
  21890. * @param {number} [format=RGBAFormat] - The min filter value.
  21891. * @param {number} [type=UnsignedByteType] - The min filter value.
  21892. */
  21893. constructor( mipmaps, width, height, depth, format, type ) {
  21894. super( mipmaps, width, height, format, type );
  21895. /**
  21896. * This flag can be used for type testing.
  21897. *
  21898. * @type {boolean}
  21899. * @readonly
  21900. * @default true
  21901. */
  21902. this.isCompressedArrayTexture = true;
  21903. /**
  21904. * The image property of a compressed texture just defines its dimensions.
  21905. *
  21906. * @name CompressedArrayTexture#image
  21907. * @type {{width:number,height:number,depth:number}}
  21908. */
  21909. this.image.depth = depth;
  21910. /**
  21911. * This defines how the texture is wrapped in the depth and corresponds to
  21912. * *W* in UVW mapping.
  21913. *
  21914. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21915. * @default ClampToEdgeWrapping
  21916. */
  21917. this.wrapR = ClampToEdgeWrapping;
  21918. /**
  21919. * A set of all layers which need to be updated in the texture.
  21920. *
  21921. * @type {Set<number>}
  21922. */
  21923. this.layerUpdates = new Set();
  21924. }
  21925. /**
  21926. * Describes that a specific layer of the texture needs to be updated.
  21927. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21928. * entire compressed texture array is sent to the GPU. Marking specific
  21929. * layers will only transmit subsets of all mipmaps associated with a
  21930. * specific depth in the array which is often much more performant.
  21931. *
  21932. * @param {number} layerIndex - The layer index that should be updated.
  21933. */
  21934. addLayerUpdate( layerIndex ) {
  21935. this.layerUpdates.add( layerIndex );
  21936. }
  21937. /**
  21938. * Resets the layer updates registry.
  21939. */
  21940. clearLayerUpdates() {
  21941. this.layerUpdates.clear();
  21942. }
  21943. }
  21944. /**
  21945. * Creates a cube texture based on data in compressed form.
  21946. *
  21947. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21948. *
  21949. * @augments CompressedTexture
  21950. */
  21951. class CompressedCubeTexture extends CompressedTexture {
  21952. /**
  21953. * Constructs a new compressed texture.
  21954. *
  21955. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21956. * @param {number} [format=RGBAFormat] - The texture format.
  21957. * @param {number} [type=UnsignedByteType] - The texture type.
  21958. */
  21959. constructor( images, format, type ) {
  21960. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21961. /**
  21962. * This flag can be used for type testing.
  21963. *
  21964. * @type {boolean}
  21965. * @readonly
  21966. * @default true
  21967. */
  21968. this.isCompressedCubeTexture = true;
  21969. /**
  21970. * This flag can be used for type testing.
  21971. *
  21972. * @type {boolean}
  21973. * @readonly
  21974. * @default true
  21975. */
  21976. this.isCubeTexture = true;
  21977. this.image = images;
  21978. }
  21979. }
  21980. /**
  21981. * Creates a texture from a canvas element.
  21982. *
  21983. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21984. * to `true` immediately since a canvas can directly be used for rendering.
  21985. *
  21986. * @augments Texture
  21987. */
  21988. class CanvasTexture extends Texture {
  21989. /**
  21990. * Constructs a new texture.
  21991. *
  21992. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21993. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21994. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21995. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21996. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21997. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21998. * @param {number} [format=RGBAFormat] - The texture format.
  21999. * @param {number} [type=UnsignedByteType] - The texture type.
  22000. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22001. */
  22002. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22003. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22004. /**
  22005. * This flag can be used for type testing.
  22006. *
  22007. * @type {boolean}
  22008. * @readonly
  22009. * @default true
  22010. */
  22011. this.isCanvasTexture = true;
  22012. this.needsUpdate = true;
  22013. }
  22014. }
  22015. /**
  22016. * This class can be used to automatically save the depth information of a
  22017. * rendering into a texture.
  22018. *
  22019. * @augments Texture
  22020. */
  22021. class DepthTexture extends Texture {
  22022. /**
  22023. * Constructs a new depth texture.
  22024. *
  22025. * @param {number} width - The width of the texture.
  22026. * @param {number} height - The height of the texture.
  22027. * @param {number} [type=UnsignedIntType] - The texture type.
  22028. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22029. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22030. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22031. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22032. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22033. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22034. * @param {number} [format=DepthFormat] - The texture format.
  22035. * @param {number} [depth=1] - The depth of the texture.
  22036. */
  22037. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22038. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22039. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22040. }
  22041. const image = { width: width, height: height, depth: depth };
  22042. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22043. /**
  22044. * This flag can be used for type testing.
  22045. *
  22046. * @type {boolean}
  22047. * @readonly
  22048. * @default true
  22049. */
  22050. this.isDepthTexture = true;
  22051. /**
  22052. * If set to `true`, the texture is flipped along the vertical axis when
  22053. * uploaded to the GPU.
  22054. *
  22055. * Overwritten and set to `false` by default.
  22056. *
  22057. * @type {boolean}
  22058. * @default false
  22059. */
  22060. this.flipY = false;
  22061. /**
  22062. * Whether to generate mipmaps (if possible) for a texture.
  22063. *
  22064. * Overwritten and set to `false` by default.
  22065. *
  22066. * @type {boolean}
  22067. * @default false
  22068. */
  22069. this.generateMipmaps = false;
  22070. /**
  22071. * Code corresponding to the depth compare function.
  22072. *
  22073. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22074. * @default null
  22075. */
  22076. this.compareFunction = null;
  22077. }
  22078. copy( source ) {
  22079. super.copy( source );
  22080. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22081. this.compareFunction = source.compareFunction;
  22082. return this;
  22083. }
  22084. toJSON( meta ) {
  22085. const data = super.toJSON( meta );
  22086. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22087. return data;
  22088. }
  22089. }
  22090. /**
  22091. * A geometry class for representing a capsule.
  22092. *
  22093. * ```js
  22094. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22095. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22096. * const capsule = new THREE.Mesh( geometry, material );
  22097. * scene.add( capsule );
  22098. * ```
  22099. *
  22100. * @augments BufferGeometry
  22101. */
  22102. class CapsuleGeometry extends BufferGeometry {
  22103. /**
  22104. * Constructs a new capsule geometry.
  22105. *
  22106. * @param {number} [radius=1] - Radius of the capsule.
  22107. * @param {number} [height=1] - Height of the middle section.
  22108. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22109. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22110. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22111. */
  22112. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22113. super();
  22114. this.type = 'CapsuleGeometry';
  22115. /**
  22116. * Holds the constructor parameters that have been
  22117. * used to generate the geometry. Any modification
  22118. * after instantiation does not change the geometry.
  22119. *
  22120. * @type {Object}
  22121. */
  22122. this.parameters = {
  22123. radius: radius,
  22124. height: height,
  22125. capSegments: capSegments,
  22126. radialSegments: radialSegments,
  22127. heightSegments: heightSegments,
  22128. };
  22129. height = Math.max( 0, height );
  22130. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22131. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22132. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22133. // buffers
  22134. const indices = [];
  22135. const vertices = [];
  22136. const normals = [];
  22137. const uvs = [];
  22138. // helper variables
  22139. const halfHeight = height / 2;
  22140. const capArcLength = ( Math.PI / 2 ) * radius;
  22141. const cylinderPartLength = height;
  22142. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22143. const numVerticalSegments = capSegments * 2 + heightSegments;
  22144. const verticesPerRow = radialSegments + 1;
  22145. const normal = new Vector3();
  22146. const vertex = new Vector3();
  22147. // generate vertices, normals, and uvs
  22148. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22149. let currentArcLength = 0;
  22150. let profileY = 0;
  22151. let profileRadius = 0;
  22152. let normalYComponent = 0;
  22153. if ( iy <= capSegments ) {
  22154. // bottom cap
  22155. const segmentProgress = iy / capSegments;
  22156. const angle = ( segmentProgress * Math.PI ) / 2;
  22157. profileY = - halfHeight - radius * Math.cos( angle );
  22158. profileRadius = radius * Math.sin( angle );
  22159. normalYComponent = - radius * Math.cos( angle );
  22160. currentArcLength = segmentProgress * capArcLength;
  22161. } else if ( iy <= capSegments + heightSegments ) {
  22162. // middle section
  22163. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22164. profileY = - halfHeight + segmentProgress * height;
  22165. profileRadius = radius;
  22166. normalYComponent = 0;
  22167. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22168. } else {
  22169. // top cap
  22170. const segmentProgress =
  22171. ( iy - capSegments - heightSegments ) / capSegments;
  22172. const angle = ( segmentProgress * Math.PI ) / 2;
  22173. profileY = halfHeight + radius * Math.sin( angle );
  22174. profileRadius = radius * Math.cos( angle );
  22175. normalYComponent = radius * Math.sin( angle );
  22176. currentArcLength =
  22177. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22178. }
  22179. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22180. // special case for the poles
  22181. let uOffset = 0;
  22182. if ( iy === 0 ) {
  22183. uOffset = 0.5 / radialSegments;
  22184. } else if ( iy === numVerticalSegments ) {
  22185. uOffset = -0.5 / radialSegments;
  22186. }
  22187. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22188. const u = ix / radialSegments;
  22189. const theta = u * Math.PI * 2;
  22190. const sinTheta = Math.sin( theta );
  22191. const cosTheta = Math.cos( theta );
  22192. // vertex
  22193. vertex.x = - profileRadius * cosTheta;
  22194. vertex.y = profileY;
  22195. vertex.z = profileRadius * sinTheta;
  22196. vertices.push( vertex.x, vertex.y, vertex.z );
  22197. // normal
  22198. normal.set(
  22199. - profileRadius * cosTheta,
  22200. normalYComponent,
  22201. profileRadius * sinTheta
  22202. );
  22203. normal.normalize();
  22204. normals.push( normal.x, normal.y, normal.z );
  22205. // uv
  22206. uvs.push( u + uOffset, v );
  22207. }
  22208. if ( iy > 0 ) {
  22209. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22210. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22211. const i1 = prevIndexRow + ix;
  22212. const i2 = prevIndexRow + ix + 1;
  22213. const i3 = iy * verticesPerRow + ix;
  22214. const i4 = iy * verticesPerRow + ix + 1;
  22215. indices.push( i1, i2, i3 );
  22216. indices.push( i2, i4, i3 );
  22217. }
  22218. }
  22219. }
  22220. // build geometry
  22221. this.setIndex( indices );
  22222. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22223. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22224. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22225. }
  22226. copy( source ) {
  22227. super.copy( source );
  22228. this.parameters = Object.assign( {}, source.parameters );
  22229. return this;
  22230. }
  22231. /**
  22232. * Factory method for creating an instance of this class from the given
  22233. * JSON object.
  22234. *
  22235. * @param {Object} data - A JSON object representing the serialized geometry.
  22236. * @return {CapsuleGeometry} A new instance.
  22237. */
  22238. static fromJSON( data ) {
  22239. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22240. }
  22241. }
  22242. /**
  22243. * A simple shape of Euclidean geometry. It is constructed from a
  22244. * number of triangular segments that are oriented around a central point and
  22245. * extend as far out as a given radius. It is built counter-clockwise from a
  22246. * start angle and a given central angle. It can also be used to create
  22247. * regular polygons, where the number of segments determines the number of
  22248. * sides.
  22249. *
  22250. * ```js
  22251. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22252. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22253. * const circle = new THREE.Mesh( geometry, material );
  22254. * scene.add( circle )
  22255. * ```
  22256. *
  22257. * @augments BufferGeometry
  22258. */
  22259. class CircleGeometry extends BufferGeometry {
  22260. /**
  22261. * Constructs a new circle geometry.
  22262. *
  22263. * @param {number} [radius=1] - Radius of the circle.
  22264. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22265. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22266. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22267. * of the circular sector in radians. The default value results in a complete circle.
  22268. */
  22269. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22270. super();
  22271. this.type = 'CircleGeometry';
  22272. /**
  22273. * Holds the constructor parameters that have been
  22274. * used to generate the geometry. Any modification
  22275. * after instantiation does not change the geometry.
  22276. *
  22277. * @type {Object}
  22278. */
  22279. this.parameters = {
  22280. radius: radius,
  22281. segments: segments,
  22282. thetaStart: thetaStart,
  22283. thetaLength: thetaLength
  22284. };
  22285. segments = Math.max( 3, segments );
  22286. // buffers
  22287. const indices = [];
  22288. const vertices = [];
  22289. const normals = [];
  22290. const uvs = [];
  22291. // helper variables
  22292. const vertex = new Vector3();
  22293. const uv = new Vector2();
  22294. // center point
  22295. vertices.push( 0, 0, 0 );
  22296. normals.push( 0, 0, 1 );
  22297. uvs.push( 0.5, 0.5 );
  22298. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22299. const segment = thetaStart + s / segments * thetaLength;
  22300. // vertex
  22301. vertex.x = radius * Math.cos( segment );
  22302. vertex.y = radius * Math.sin( segment );
  22303. vertices.push( vertex.x, vertex.y, vertex.z );
  22304. // normal
  22305. normals.push( 0, 0, 1 );
  22306. // uvs
  22307. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22308. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22309. uvs.push( uv.x, uv.y );
  22310. }
  22311. // indices
  22312. for ( let i = 1; i <= segments; i ++ ) {
  22313. indices.push( i, i + 1, 0 );
  22314. }
  22315. // build geometry
  22316. this.setIndex( indices );
  22317. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22318. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22319. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22320. }
  22321. copy( source ) {
  22322. super.copy( source );
  22323. this.parameters = Object.assign( {}, source.parameters );
  22324. return this;
  22325. }
  22326. /**
  22327. * Factory method for creating an instance of this class from the given
  22328. * JSON object.
  22329. *
  22330. * @param {Object} data - A JSON object representing the serialized geometry.
  22331. * @return {CircleGeometry} A new instance.
  22332. */
  22333. static fromJSON( data ) {
  22334. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22335. }
  22336. }
  22337. /**
  22338. * A geometry class for representing a cylinder.
  22339. *
  22340. * ```js
  22341. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22342. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22343. * const cylinder = new THREE.Mesh( geometry, material );
  22344. * scene.add( cylinder );
  22345. * ```
  22346. *
  22347. * @augments BufferGeometry
  22348. */
  22349. class CylinderGeometry extends BufferGeometry {
  22350. /**
  22351. * Constructs a new cylinder geometry.
  22352. *
  22353. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22354. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22355. * @param {number} [height=1] - Height of the cylinder.
  22356. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22357. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22358. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22359. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22360. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22361. * The default value results in a complete cylinder.
  22362. */
  22363. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22364. super();
  22365. this.type = 'CylinderGeometry';
  22366. /**
  22367. * Holds the constructor parameters that have been
  22368. * used to generate the geometry. Any modification
  22369. * after instantiation does not change the geometry.
  22370. *
  22371. * @type {Object}
  22372. */
  22373. this.parameters = {
  22374. radiusTop: radiusTop,
  22375. radiusBottom: radiusBottom,
  22376. height: height,
  22377. radialSegments: radialSegments,
  22378. heightSegments: heightSegments,
  22379. openEnded: openEnded,
  22380. thetaStart: thetaStart,
  22381. thetaLength: thetaLength
  22382. };
  22383. const scope = this;
  22384. radialSegments = Math.floor( radialSegments );
  22385. heightSegments = Math.floor( heightSegments );
  22386. // buffers
  22387. const indices = [];
  22388. const vertices = [];
  22389. const normals = [];
  22390. const uvs = [];
  22391. // helper variables
  22392. let index = 0;
  22393. const indexArray = [];
  22394. const halfHeight = height / 2;
  22395. let groupStart = 0;
  22396. // generate geometry
  22397. generateTorso();
  22398. if ( openEnded === false ) {
  22399. if ( radiusTop > 0 ) generateCap( true );
  22400. if ( radiusBottom > 0 ) generateCap( false );
  22401. }
  22402. // build geometry
  22403. this.setIndex( indices );
  22404. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22405. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22406. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22407. function generateTorso() {
  22408. const normal = new Vector3();
  22409. const vertex = new Vector3();
  22410. let groupCount = 0;
  22411. // this will be used to calculate the normal
  22412. const slope = ( radiusBottom - radiusTop ) / height;
  22413. // generate vertices, normals and uvs
  22414. for ( let y = 0; y <= heightSegments; y ++ ) {
  22415. const indexRow = [];
  22416. const v = y / heightSegments;
  22417. // calculate the radius of the current row
  22418. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22419. for ( let x = 0; x <= radialSegments; x ++ ) {
  22420. const u = x / radialSegments;
  22421. const theta = u * thetaLength + thetaStart;
  22422. const sinTheta = Math.sin( theta );
  22423. const cosTheta = Math.cos( theta );
  22424. // vertex
  22425. vertex.x = radius * sinTheta;
  22426. vertex.y = - v * height + halfHeight;
  22427. vertex.z = radius * cosTheta;
  22428. vertices.push( vertex.x, vertex.y, vertex.z );
  22429. // normal
  22430. normal.set( sinTheta, slope, cosTheta ).normalize();
  22431. normals.push( normal.x, normal.y, normal.z );
  22432. // uv
  22433. uvs.push( u, 1 - v );
  22434. // save index of vertex in respective row
  22435. indexRow.push( index ++ );
  22436. }
  22437. // now save vertices of the row in our index array
  22438. indexArray.push( indexRow );
  22439. }
  22440. // generate indices
  22441. for ( let x = 0; x < radialSegments; x ++ ) {
  22442. for ( let y = 0; y < heightSegments; y ++ ) {
  22443. // we use the index array to access the correct indices
  22444. const a = indexArray[ y ][ x ];
  22445. const b = indexArray[ y + 1 ][ x ];
  22446. const c = indexArray[ y + 1 ][ x + 1 ];
  22447. const d = indexArray[ y ][ x + 1 ];
  22448. // faces
  22449. if ( radiusTop > 0 || y !== 0 ) {
  22450. indices.push( a, b, d );
  22451. groupCount += 3;
  22452. }
  22453. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22454. indices.push( b, c, d );
  22455. groupCount += 3;
  22456. }
  22457. }
  22458. }
  22459. // add a group to the geometry. this will ensure multi material support
  22460. scope.addGroup( groupStart, groupCount, 0 );
  22461. // calculate new start value for groups
  22462. groupStart += groupCount;
  22463. }
  22464. function generateCap( top ) {
  22465. // save the index of the first center vertex
  22466. const centerIndexStart = index;
  22467. const uv = new Vector2();
  22468. const vertex = new Vector3();
  22469. let groupCount = 0;
  22470. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22471. const sign = ( top === true ) ? 1 : -1;
  22472. // first we generate the center vertex data of the cap.
  22473. // because the geometry needs one set of uvs per face,
  22474. // we must generate a center vertex per face/segment
  22475. for ( let x = 1; x <= radialSegments; x ++ ) {
  22476. // vertex
  22477. vertices.push( 0, halfHeight * sign, 0 );
  22478. // normal
  22479. normals.push( 0, sign, 0 );
  22480. // uv
  22481. uvs.push( 0.5, 0.5 );
  22482. // increase index
  22483. index ++;
  22484. }
  22485. // save the index of the last center vertex
  22486. const centerIndexEnd = index;
  22487. // now we generate the surrounding vertices, normals and uvs
  22488. for ( let x = 0; x <= radialSegments; x ++ ) {
  22489. const u = x / radialSegments;
  22490. const theta = u * thetaLength + thetaStart;
  22491. const cosTheta = Math.cos( theta );
  22492. const sinTheta = Math.sin( theta );
  22493. // vertex
  22494. vertex.x = radius * sinTheta;
  22495. vertex.y = halfHeight * sign;
  22496. vertex.z = radius * cosTheta;
  22497. vertices.push( vertex.x, vertex.y, vertex.z );
  22498. // normal
  22499. normals.push( 0, sign, 0 );
  22500. // uv
  22501. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22502. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22503. uvs.push( uv.x, uv.y );
  22504. // increase index
  22505. index ++;
  22506. }
  22507. // generate indices
  22508. for ( let x = 0; x < radialSegments; x ++ ) {
  22509. const c = centerIndexStart + x;
  22510. const i = centerIndexEnd + x;
  22511. if ( top === true ) {
  22512. // face top
  22513. indices.push( i, i + 1, c );
  22514. } else {
  22515. // face bottom
  22516. indices.push( i + 1, i, c );
  22517. }
  22518. groupCount += 3;
  22519. }
  22520. // add a group to the geometry. this will ensure multi material support
  22521. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22522. // calculate new start value for groups
  22523. groupStart += groupCount;
  22524. }
  22525. }
  22526. copy( source ) {
  22527. super.copy( source );
  22528. this.parameters = Object.assign( {}, source.parameters );
  22529. return this;
  22530. }
  22531. /**
  22532. * Factory method for creating an instance of this class from the given
  22533. * JSON object.
  22534. *
  22535. * @param {Object} data - A JSON object representing the serialized geometry.
  22536. * @return {CylinderGeometry} A new instance.
  22537. */
  22538. static fromJSON( data ) {
  22539. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22540. }
  22541. }
  22542. /**
  22543. * A geometry class for representing a cone.
  22544. *
  22545. * ```js
  22546. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22547. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22548. * const cone = new THREE.Mesh(geometry, material );
  22549. * scene.add( cone );
  22550. * ```
  22551. *
  22552. * @augments CylinderGeometry
  22553. */
  22554. class ConeGeometry extends CylinderGeometry {
  22555. /**
  22556. * Constructs a new cone geometry.
  22557. *
  22558. * @param {number} [radius=1] - Radius of the cone base.
  22559. * @param {number} [height=1] - Height of the cone.
  22560. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22561. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22562. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22563. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22564. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22565. * The default value results in a complete cone.
  22566. */
  22567. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22568. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22569. this.type = 'ConeGeometry';
  22570. /**
  22571. * Holds the constructor parameters that have been
  22572. * used to generate the geometry. Any modification
  22573. * after instantiation does not change the geometry.
  22574. *
  22575. * @type {Object}
  22576. */
  22577. this.parameters = {
  22578. radius: radius,
  22579. height: height,
  22580. radialSegments: radialSegments,
  22581. heightSegments: heightSegments,
  22582. openEnded: openEnded,
  22583. thetaStart: thetaStart,
  22584. thetaLength: thetaLength
  22585. };
  22586. }
  22587. /**
  22588. * Factory method for creating an instance of this class from the given
  22589. * JSON object.
  22590. *
  22591. * @param {Object} data - A JSON object representing the serialized geometry.
  22592. * @return {ConeGeometry} A new instance.
  22593. */
  22594. static fromJSON( data ) {
  22595. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22596. }
  22597. }
  22598. /**
  22599. * A polyhedron is a solid in three dimensions with flat faces. This class
  22600. * will take an array of vertices, project them onto a sphere, and then
  22601. * divide them up to the desired level of detail.
  22602. *
  22603. * @augments BufferGeometry
  22604. */
  22605. class PolyhedronGeometry extends BufferGeometry {
  22606. /**
  22607. * Constructs a new polyhedron geometry.
  22608. *
  22609. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22610. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22611. * @param {number} [radius=1] - The radius of the shape.
  22612. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22613. */
  22614. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22615. super();
  22616. this.type = 'PolyhedronGeometry';
  22617. /**
  22618. * Holds the constructor parameters that have been
  22619. * used to generate the geometry. Any modification
  22620. * after instantiation does not change the geometry.
  22621. *
  22622. * @type {Object}
  22623. */
  22624. this.parameters = {
  22625. vertices: vertices,
  22626. indices: indices,
  22627. radius: radius,
  22628. detail: detail
  22629. };
  22630. // default buffer data
  22631. const vertexBuffer = [];
  22632. const uvBuffer = [];
  22633. // the subdivision creates the vertex buffer data
  22634. subdivide( detail );
  22635. // all vertices should lie on a conceptual sphere with a given radius
  22636. applyRadius( radius );
  22637. // finally, create the uv data
  22638. generateUVs();
  22639. // build non-indexed geometry
  22640. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22641. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22642. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22643. if ( detail === 0 ) {
  22644. this.computeVertexNormals(); // flat normals
  22645. } else {
  22646. this.normalizeNormals(); // smooth normals
  22647. }
  22648. // helper functions
  22649. function subdivide( detail ) {
  22650. const a = new Vector3();
  22651. const b = new Vector3();
  22652. const c = new Vector3();
  22653. // iterate over all faces and apply a subdivision with the given detail value
  22654. for ( let i = 0; i < indices.length; i += 3 ) {
  22655. // get the vertices of the face
  22656. getVertexByIndex( indices[ i + 0 ], a );
  22657. getVertexByIndex( indices[ i + 1 ], b );
  22658. getVertexByIndex( indices[ i + 2 ], c );
  22659. // perform subdivision
  22660. subdivideFace( a, b, c, detail );
  22661. }
  22662. }
  22663. function subdivideFace( a, b, c, detail ) {
  22664. const cols = detail + 1;
  22665. // we use this multidimensional array as a data structure for creating the subdivision
  22666. const v = [];
  22667. // construct all of the vertices for this subdivision
  22668. for ( let i = 0; i <= cols; i ++ ) {
  22669. v[ i ] = [];
  22670. const aj = a.clone().lerp( c, i / cols );
  22671. const bj = b.clone().lerp( c, i / cols );
  22672. const rows = cols - i;
  22673. for ( let j = 0; j <= rows; j ++ ) {
  22674. if ( j === 0 && i === cols ) {
  22675. v[ i ][ j ] = aj;
  22676. } else {
  22677. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22678. }
  22679. }
  22680. }
  22681. // construct all of the faces
  22682. for ( let i = 0; i < cols; i ++ ) {
  22683. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22684. const k = Math.floor( j / 2 );
  22685. if ( j % 2 === 0 ) {
  22686. pushVertex( v[ i ][ k + 1 ] );
  22687. pushVertex( v[ i + 1 ][ k ] );
  22688. pushVertex( v[ i ][ k ] );
  22689. } else {
  22690. pushVertex( v[ i ][ k + 1 ] );
  22691. pushVertex( v[ i + 1 ][ k + 1 ] );
  22692. pushVertex( v[ i + 1 ][ k ] );
  22693. }
  22694. }
  22695. }
  22696. }
  22697. function applyRadius( radius ) {
  22698. const vertex = new Vector3();
  22699. // iterate over the entire buffer and apply the radius to each vertex
  22700. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22701. vertex.x = vertexBuffer[ i + 0 ];
  22702. vertex.y = vertexBuffer[ i + 1 ];
  22703. vertex.z = vertexBuffer[ i + 2 ];
  22704. vertex.normalize().multiplyScalar( radius );
  22705. vertexBuffer[ i + 0 ] = vertex.x;
  22706. vertexBuffer[ i + 1 ] = vertex.y;
  22707. vertexBuffer[ i + 2 ] = vertex.z;
  22708. }
  22709. }
  22710. function generateUVs() {
  22711. const vertex = new Vector3();
  22712. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22713. vertex.x = vertexBuffer[ i + 0 ];
  22714. vertex.y = vertexBuffer[ i + 1 ];
  22715. vertex.z = vertexBuffer[ i + 2 ];
  22716. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22717. const v = inclination( vertex ) / Math.PI + 0.5;
  22718. uvBuffer.push( u, 1 - v );
  22719. }
  22720. correctUVs();
  22721. correctSeam();
  22722. }
  22723. function correctSeam() {
  22724. // handle case when face straddles the seam, see #3269
  22725. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22726. // uv data of a single face
  22727. const x0 = uvBuffer[ i + 0 ];
  22728. const x1 = uvBuffer[ i + 2 ];
  22729. const x2 = uvBuffer[ i + 4 ];
  22730. const max = Math.max( x0, x1, x2 );
  22731. const min = Math.min( x0, x1, x2 );
  22732. // 0.9 is somewhat arbitrary
  22733. if ( max > 0.9 && min < 0.1 ) {
  22734. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22735. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22736. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22737. }
  22738. }
  22739. }
  22740. function pushVertex( vertex ) {
  22741. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22742. }
  22743. function getVertexByIndex( index, vertex ) {
  22744. const stride = index * 3;
  22745. vertex.x = vertices[ stride + 0 ];
  22746. vertex.y = vertices[ stride + 1 ];
  22747. vertex.z = vertices[ stride + 2 ];
  22748. }
  22749. function correctUVs() {
  22750. const a = new Vector3();
  22751. const b = new Vector3();
  22752. const c = new Vector3();
  22753. const centroid = new Vector3();
  22754. const uvA = new Vector2();
  22755. const uvB = new Vector2();
  22756. const uvC = new Vector2();
  22757. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22758. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22759. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22760. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22761. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22762. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22763. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22764. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22765. const azi = azimuth( centroid );
  22766. correctUV( uvA, j + 0, a, azi );
  22767. correctUV( uvB, j + 2, b, azi );
  22768. correctUV( uvC, j + 4, c, azi );
  22769. }
  22770. }
  22771. function correctUV( uv, stride, vector, azimuth ) {
  22772. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22773. uvBuffer[ stride ] = uv.x - 1;
  22774. }
  22775. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22776. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22777. }
  22778. }
  22779. // Angle around the Y axis, counter-clockwise when looking from above.
  22780. function azimuth( vector ) {
  22781. return Math.atan2( vector.z, - vector.x );
  22782. }
  22783. // Angle above the XZ plane.
  22784. function inclination( vector ) {
  22785. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22786. }
  22787. }
  22788. copy( source ) {
  22789. super.copy( source );
  22790. this.parameters = Object.assign( {}, source.parameters );
  22791. return this;
  22792. }
  22793. /**
  22794. * Factory method for creating an instance of this class from the given
  22795. * JSON object.
  22796. *
  22797. * @param {Object} data - A JSON object representing the serialized geometry.
  22798. * @return {PolyhedronGeometry} A new instance.
  22799. */
  22800. static fromJSON( data ) {
  22801. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22802. }
  22803. }
  22804. /**
  22805. * A geometry class for representing a dodecahedron.
  22806. *
  22807. * ```js
  22808. * const geometry = new THREE.DodecahedronGeometry();
  22809. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22810. * const dodecahedron = new THREE.Mesh( geometry, material );
  22811. * scene.add( dodecahedron );
  22812. * ```
  22813. *
  22814. * @augments PolyhedronGeometry
  22815. */
  22816. class DodecahedronGeometry extends PolyhedronGeometry {
  22817. /**
  22818. * Constructs a new dodecahedron geometry.
  22819. *
  22820. * @param {number} [radius=1] - Radius of the dodecahedron.
  22821. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22822. */
  22823. constructor( radius = 1, detail = 0 ) {
  22824. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22825. const r = 1 / t;
  22826. const vertices = [
  22827. // (±1, ±1, ±1)
  22828. -1, -1, -1, -1, -1, 1,
  22829. -1, 1, -1, -1, 1, 1,
  22830. 1, -1, -1, 1, -1, 1,
  22831. 1, 1, -1, 1, 1, 1,
  22832. // (0, ±1/φ, ±φ)
  22833. 0, - r, - t, 0, - r, t,
  22834. 0, r, - t, 0, r, t,
  22835. // (±1/φ, ±φ, 0)
  22836. - r, - t, 0, - r, t, 0,
  22837. r, - t, 0, r, t, 0,
  22838. // (±φ, 0, ±1/φ)
  22839. - t, 0, - r, t, 0, - r,
  22840. - t, 0, r, t, 0, r
  22841. ];
  22842. const indices = [
  22843. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22844. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22845. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22846. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22847. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22848. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22849. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22850. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22851. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22852. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22853. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22854. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22855. ];
  22856. super( vertices, indices, radius, detail );
  22857. this.type = 'DodecahedronGeometry';
  22858. /**
  22859. * Holds the constructor parameters that have been
  22860. * used to generate the geometry. Any modification
  22861. * after instantiation does not change the geometry.
  22862. *
  22863. * @type {Object}
  22864. */
  22865. this.parameters = {
  22866. radius: radius,
  22867. detail: detail
  22868. };
  22869. }
  22870. /**
  22871. * Factory method for creating an instance of this class from the given
  22872. * JSON object.
  22873. *
  22874. * @param {Object} data - A JSON object representing the serialized geometry.
  22875. * @return {DodecahedronGeometry} A new instance.
  22876. */
  22877. static fromJSON( data ) {
  22878. return new DodecahedronGeometry( data.radius, data.detail );
  22879. }
  22880. }
  22881. const _v0 = /*@__PURE__*/ new Vector3();
  22882. const _v1$1 = /*@__PURE__*/ new Vector3();
  22883. const _normal = /*@__PURE__*/ new Vector3();
  22884. const _triangle = /*@__PURE__*/ new Triangle();
  22885. /**
  22886. * Can be used as a helper object to view the edges of a geometry.
  22887. *
  22888. * ```js
  22889. * const geometry = new THREE.BoxGeometry();
  22890. * const edges = new THREE.EdgesGeometry( geometry );
  22891. * const line = new THREE.LineSegments( edges );
  22892. * scene.add( line );
  22893. * ```
  22894. *
  22895. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22896. *
  22897. * @augments BufferGeometry
  22898. */
  22899. class EdgesGeometry extends BufferGeometry {
  22900. /**
  22901. * Constructs a new edges geometry.
  22902. *
  22903. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22904. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22905. * between the face normals of the adjoining faces exceeds this value.
  22906. */
  22907. constructor( geometry = null, thresholdAngle = 1 ) {
  22908. super();
  22909. this.type = 'EdgesGeometry';
  22910. /**
  22911. * Holds the constructor parameters that have been
  22912. * used to generate the geometry. Any modification
  22913. * after instantiation does not change the geometry.
  22914. *
  22915. * @type {Object}
  22916. */
  22917. this.parameters = {
  22918. geometry: geometry,
  22919. thresholdAngle: thresholdAngle
  22920. };
  22921. if ( geometry !== null ) {
  22922. const precisionPoints = 4;
  22923. const precision = Math.pow( 10, precisionPoints );
  22924. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22925. const indexAttr = geometry.getIndex();
  22926. const positionAttr = geometry.getAttribute( 'position' );
  22927. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22928. const indexArr = [ 0, 0, 0 ];
  22929. const vertKeys = [ 'a', 'b', 'c' ];
  22930. const hashes = new Array( 3 );
  22931. const edgeData = {};
  22932. const vertices = [];
  22933. for ( let i = 0; i < indexCount; i += 3 ) {
  22934. if ( indexAttr ) {
  22935. indexArr[ 0 ] = indexAttr.getX( i );
  22936. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22937. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22938. } else {
  22939. indexArr[ 0 ] = i;
  22940. indexArr[ 1 ] = i + 1;
  22941. indexArr[ 2 ] = i + 2;
  22942. }
  22943. const { a, b, c } = _triangle;
  22944. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22945. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22946. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22947. _triangle.getNormal( _normal );
  22948. // create hashes for the edge from the vertices
  22949. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22950. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22951. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22952. // skip degenerate triangles
  22953. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22954. continue;
  22955. }
  22956. // iterate over every edge
  22957. for ( let j = 0; j < 3; j ++ ) {
  22958. // get the first and next vertex making up the edge
  22959. const jNext = ( j + 1 ) % 3;
  22960. const vecHash0 = hashes[ j ];
  22961. const vecHash1 = hashes[ jNext ];
  22962. const v0 = _triangle[ vertKeys[ j ] ];
  22963. const v1 = _triangle[ vertKeys[ jNext ] ];
  22964. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22965. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22966. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22967. // if we found a sibling edge add it into the vertex array if
  22968. // it meets the angle threshold and delete the edge from the map.
  22969. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22970. vertices.push( v0.x, v0.y, v0.z );
  22971. vertices.push( v1.x, v1.y, v1.z );
  22972. }
  22973. edgeData[ reverseHash ] = null;
  22974. } else if ( ! ( hash in edgeData ) ) {
  22975. // if we've already got an edge here then skip adding a new one
  22976. edgeData[ hash ] = {
  22977. index0: indexArr[ j ],
  22978. index1: indexArr[ jNext ],
  22979. normal: _normal.clone(),
  22980. };
  22981. }
  22982. }
  22983. }
  22984. // iterate over all remaining, unmatched edges and add them to the vertex array
  22985. for ( const key in edgeData ) {
  22986. if ( edgeData[ key ] ) {
  22987. const { index0, index1 } = edgeData[ key ];
  22988. _v0.fromBufferAttribute( positionAttr, index0 );
  22989. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22990. vertices.push( _v0.x, _v0.y, _v0.z );
  22991. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22992. }
  22993. }
  22994. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22995. }
  22996. }
  22997. copy( source ) {
  22998. super.copy( source );
  22999. this.parameters = Object.assign( {}, source.parameters );
  23000. return this;
  23001. }
  23002. }
  23003. /**
  23004. * An abstract base class for creating an analytic curve object that contains methods
  23005. * for interpolation.
  23006. *
  23007. * @abstract
  23008. */
  23009. class Curve {
  23010. /**
  23011. * Constructs a new curve.
  23012. */
  23013. constructor() {
  23014. /**
  23015. * The type property is used for detecting the object type
  23016. * in context of serialization/deserialization.
  23017. *
  23018. * @type {string}
  23019. * @readonly
  23020. */
  23021. this.type = 'Curve';
  23022. /**
  23023. * This value determines the amount of divisions when calculating the
  23024. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23025. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23026. * recommended to increase the value of this property if the curve is very large.
  23027. *
  23028. * @type {number}
  23029. * @default 200
  23030. */
  23031. this.arcLengthDivisions = 200;
  23032. /**
  23033. * Must be set to `true` if the curve parameters have changed.
  23034. *
  23035. * @type {boolean}
  23036. * @default false
  23037. */
  23038. this.needsUpdate = false;
  23039. /**
  23040. * An internal cache that holds precomputed curve length values.
  23041. *
  23042. * @private
  23043. * @type {?Array<number>}
  23044. * @default null
  23045. */
  23046. this.cacheArcLengths = null;
  23047. }
  23048. /**
  23049. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23050. * for the given interpolation factor.
  23051. *
  23052. * @abstract
  23053. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23054. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23055. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23056. */
  23057. getPoint( /* t, optionalTarget */ ) {
  23058. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23059. }
  23060. /**
  23061. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23062. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23063. * of the curve which equidistant samples.
  23064. *
  23065. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23066. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23067. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23068. */
  23069. getPointAt( u, optionalTarget ) {
  23070. const t = this.getUtoTmapping( u );
  23071. return this.getPoint( t, optionalTarget );
  23072. }
  23073. /**
  23074. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23075. * the curve shape.
  23076. *
  23077. * @param {number} [divisions=5] - The number of divisions.
  23078. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23079. */
  23080. getPoints( divisions = 5 ) {
  23081. const points = [];
  23082. for ( let d = 0; d <= divisions; d ++ ) {
  23083. points.push( this.getPoint( d / divisions ) );
  23084. }
  23085. return points;
  23086. }
  23087. // Get sequence of points using getPointAt( u )
  23088. /**
  23089. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23090. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23091. * curve.
  23092. *
  23093. * @param {number} [divisions=5] - The number of divisions.
  23094. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23095. */
  23096. getSpacedPoints( divisions = 5 ) {
  23097. const points = [];
  23098. for ( let d = 0; d <= divisions; d ++ ) {
  23099. points.push( this.getPointAt( d / divisions ) );
  23100. }
  23101. return points;
  23102. }
  23103. /**
  23104. * Returns the total arc length of the curve.
  23105. *
  23106. * @return {number} The length of the curve.
  23107. */
  23108. getLength() {
  23109. const lengths = this.getLengths();
  23110. return lengths[ lengths.length - 1 ];
  23111. }
  23112. /**
  23113. * Returns an array of cumulative segment lengths of the curve.
  23114. *
  23115. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23116. * @return {Array<number>} An array holding the cumulative segment lengths.
  23117. */
  23118. getLengths( divisions = this.arcLengthDivisions ) {
  23119. if ( this.cacheArcLengths &&
  23120. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23121. ! this.needsUpdate ) {
  23122. return this.cacheArcLengths;
  23123. }
  23124. this.needsUpdate = false;
  23125. const cache = [];
  23126. let current, last = this.getPoint( 0 );
  23127. let sum = 0;
  23128. cache.push( 0 );
  23129. for ( let p = 1; p <= divisions; p ++ ) {
  23130. current = this.getPoint( p / divisions );
  23131. sum += current.distanceTo( last );
  23132. cache.push( sum );
  23133. last = current;
  23134. }
  23135. this.cacheArcLengths = cache;
  23136. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23137. }
  23138. /**
  23139. * Update the cumulative segment distance cache. The method must be called
  23140. * every time curve parameters are changed. If an updated curve is part of a
  23141. * composed curve like {@link CurvePath}, this method must be called on the
  23142. * composed curve, too.
  23143. */
  23144. updateArcLengths() {
  23145. this.needsUpdate = true;
  23146. this.getLengths();
  23147. }
  23148. /**
  23149. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23150. * interpolation factor in the same range that can be ued to sample equidistant points
  23151. * from a curve.
  23152. *
  23153. * @param {number} u - The interpolation factor.
  23154. * @param {?number} distance - An optional distance on the curve.
  23155. * @return {number} The updated interpolation factor.
  23156. */
  23157. getUtoTmapping( u, distance = null ) {
  23158. const arcLengths = this.getLengths();
  23159. let i = 0;
  23160. const il = arcLengths.length;
  23161. let targetArcLength; // The targeted u distance value to get
  23162. if ( distance ) {
  23163. targetArcLength = distance;
  23164. } else {
  23165. targetArcLength = u * arcLengths[ il - 1 ];
  23166. }
  23167. // binary search for the index with largest value smaller than target u distance
  23168. let low = 0, high = il - 1, comparison;
  23169. while ( low <= high ) {
  23170. 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
  23171. comparison = arcLengths[ i ] - targetArcLength;
  23172. if ( comparison < 0 ) {
  23173. low = i + 1;
  23174. } else if ( comparison > 0 ) {
  23175. high = i - 1;
  23176. } else {
  23177. high = i;
  23178. break;
  23179. // DONE
  23180. }
  23181. }
  23182. i = high;
  23183. if ( arcLengths[ i ] === targetArcLength ) {
  23184. return i / ( il - 1 );
  23185. }
  23186. // we could get finer grain at lengths, or use simple interpolation between two points
  23187. const lengthBefore = arcLengths[ i ];
  23188. const lengthAfter = arcLengths[ i + 1 ];
  23189. const segmentLength = lengthAfter - lengthBefore;
  23190. // determine where we are between the 'before' and 'after' points
  23191. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23192. // add that fractional amount to t
  23193. const t = ( i + segmentFraction ) / ( il - 1 );
  23194. return t;
  23195. }
  23196. /**
  23197. * Returns a unit vector tangent for the given interpolation factor.
  23198. * If the derived curve does not implement its tangent derivation,
  23199. * two points a small delta apart will be used to find its gradient
  23200. * which seems to give a reasonable approximation.
  23201. *
  23202. * @param {number} t - The interpolation factor.
  23203. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23204. * @return {(Vector2|Vector3)} The tangent vector.
  23205. */
  23206. getTangent( t, optionalTarget ) {
  23207. const delta = 0.0001;
  23208. let t1 = t - delta;
  23209. let t2 = t + delta;
  23210. // Capping in case of danger
  23211. if ( t1 < 0 ) t1 = 0;
  23212. if ( t2 > 1 ) t2 = 1;
  23213. const pt1 = this.getPoint( t1 );
  23214. const pt2 = this.getPoint( t2 );
  23215. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23216. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23217. return tangent;
  23218. }
  23219. /**
  23220. * Same as {@link Curve#getTangent} but with equidistant samples.
  23221. *
  23222. * @param {number} u - The interpolation factor.
  23223. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23224. * @return {(Vector2|Vector3)} The tangent vector.
  23225. * @see {@link Curve#getPointAt}
  23226. */
  23227. getTangentAt( u, optionalTarget ) {
  23228. const t = this.getUtoTmapping( u );
  23229. return this.getTangent( t, optionalTarget );
  23230. }
  23231. /**
  23232. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23233. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23234. *
  23235. * @param {number} segments - The number of segments.
  23236. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23237. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23238. */
  23239. computeFrenetFrames( segments, closed = false ) {
  23240. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23241. const normal = new Vector3();
  23242. const tangents = [];
  23243. const normals = [];
  23244. const binormals = [];
  23245. const vec = new Vector3();
  23246. const mat = new Matrix4();
  23247. // compute the tangent vectors for each segment on the curve
  23248. for ( let i = 0; i <= segments; i ++ ) {
  23249. const u = i / segments;
  23250. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23251. }
  23252. // select an initial normal vector perpendicular to the first tangent vector,
  23253. // and in the direction of the minimum tangent xyz component
  23254. normals[ 0 ] = new Vector3();
  23255. binormals[ 0 ] = new Vector3();
  23256. let min = Number.MAX_VALUE;
  23257. const tx = Math.abs( tangents[ 0 ].x );
  23258. const ty = Math.abs( tangents[ 0 ].y );
  23259. const tz = Math.abs( tangents[ 0 ].z );
  23260. if ( tx <= min ) {
  23261. min = tx;
  23262. normal.set( 1, 0, 0 );
  23263. }
  23264. if ( ty <= min ) {
  23265. min = ty;
  23266. normal.set( 0, 1, 0 );
  23267. }
  23268. if ( tz <= min ) {
  23269. normal.set( 0, 0, 1 );
  23270. }
  23271. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23272. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23273. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23274. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23275. for ( let i = 1; i <= segments; i ++ ) {
  23276. normals[ i ] = normals[ i - 1 ].clone();
  23277. binormals[ i ] = binormals[ i - 1 ].clone();
  23278. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23279. if ( vec.length() > Number.EPSILON ) {
  23280. vec.normalize();
  23281. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23282. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23283. }
  23284. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23285. }
  23286. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23287. if ( closed === true ) {
  23288. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23289. theta /= segments;
  23290. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23291. theta = - theta;
  23292. }
  23293. for ( let i = 1; i <= segments; i ++ ) {
  23294. // twist a little...
  23295. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23296. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23297. }
  23298. }
  23299. return {
  23300. tangents: tangents,
  23301. normals: normals,
  23302. binormals: binormals
  23303. };
  23304. }
  23305. /**
  23306. * Returns a new curve with copied values from this instance.
  23307. *
  23308. * @return {Curve} A clone of this instance.
  23309. */
  23310. clone() {
  23311. return new this.constructor().copy( this );
  23312. }
  23313. /**
  23314. * Copies the values of the given curve to this instance.
  23315. *
  23316. * @param {Curve} source - The curve to copy.
  23317. * @return {Curve} A reference to this curve.
  23318. */
  23319. copy( source ) {
  23320. this.arcLengthDivisions = source.arcLengthDivisions;
  23321. return this;
  23322. }
  23323. /**
  23324. * Serializes the curve into JSON.
  23325. *
  23326. * @return {Object} A JSON object representing the serialized curve.
  23327. * @see {@link ObjectLoader#parse}
  23328. */
  23329. toJSON() {
  23330. const data = {
  23331. metadata: {
  23332. version: 4.7,
  23333. type: 'Curve',
  23334. generator: 'Curve.toJSON'
  23335. }
  23336. };
  23337. data.arcLengthDivisions = this.arcLengthDivisions;
  23338. data.type = this.type;
  23339. return data;
  23340. }
  23341. /**
  23342. * Deserializes the curve from the given JSON.
  23343. *
  23344. * @param {Object} json - The JSON holding the serialized curve.
  23345. * @return {Curve} A reference to this curve.
  23346. */
  23347. fromJSON( json ) {
  23348. this.arcLengthDivisions = json.arcLengthDivisions;
  23349. return this;
  23350. }
  23351. }
  23352. /**
  23353. * A curve representing an ellipse.
  23354. *
  23355. * ```js
  23356. * const curve = new THREE.EllipseCurve(
  23357. * 0, 0,
  23358. * 10, 10,
  23359. * 0, 2 * Math.PI,
  23360. * false,
  23361. * 0
  23362. * );
  23363. *
  23364. * const points = curve.getPoints( 50 );
  23365. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23366. *
  23367. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23368. *
  23369. * // Create the final object to add to the scene
  23370. * const ellipse = new THREE.Line( geometry, material );
  23371. * ```
  23372. *
  23373. * @augments Curve
  23374. */
  23375. class EllipseCurve extends Curve {
  23376. /**
  23377. * Constructs a new ellipse curve.
  23378. *
  23379. * @param {number} [aX=0] - The X center of the ellipse.
  23380. * @param {number} [aY=0] - The Y center of the ellipse.
  23381. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23382. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23383. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23384. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23385. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23386. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23387. */
  23388. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23389. super();
  23390. /**
  23391. * This flag can be used for type testing.
  23392. *
  23393. * @type {boolean}
  23394. * @readonly
  23395. * @default true
  23396. */
  23397. this.isEllipseCurve = true;
  23398. this.type = 'EllipseCurve';
  23399. /**
  23400. * The X center of the ellipse.
  23401. *
  23402. * @type {number}
  23403. * @default 0
  23404. */
  23405. this.aX = aX;
  23406. /**
  23407. * The Y center of the ellipse.
  23408. *
  23409. * @type {number}
  23410. * @default 0
  23411. */
  23412. this.aY = aY;
  23413. /**
  23414. * The radius of the ellipse in the x direction.
  23415. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23416. *
  23417. * @type {number}
  23418. * @default 1
  23419. */
  23420. this.xRadius = xRadius;
  23421. /**
  23422. * The radius of the ellipse in the y direction.
  23423. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23424. *
  23425. * @type {number}
  23426. * @default 1
  23427. */
  23428. this.yRadius = yRadius;
  23429. /**
  23430. * The start angle of the curve in radians starting from the positive X axis.
  23431. *
  23432. * @type {number}
  23433. * @default 0
  23434. */
  23435. this.aStartAngle = aStartAngle;
  23436. /**
  23437. * The end angle of the curve in radians starting from the positive X axis.
  23438. *
  23439. * @type {number}
  23440. * @default Math.PI*2
  23441. */
  23442. this.aEndAngle = aEndAngle;
  23443. /**
  23444. * Whether the ellipse is drawn clockwise or not.
  23445. *
  23446. * @type {boolean}
  23447. * @default false
  23448. */
  23449. this.aClockwise = aClockwise;
  23450. /**
  23451. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23452. *
  23453. * @type {number}
  23454. * @default 0
  23455. */
  23456. this.aRotation = aRotation;
  23457. }
  23458. /**
  23459. * Returns a point on the curve.
  23460. *
  23461. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23462. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23463. * @return {Vector2} The position on the curve.
  23464. */
  23465. getPoint( t, optionalTarget = new Vector2() ) {
  23466. const point = optionalTarget;
  23467. const twoPi = Math.PI * 2;
  23468. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23469. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23470. // ensures that deltaAngle is 0 .. 2 PI
  23471. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23472. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23473. if ( deltaAngle < Number.EPSILON ) {
  23474. if ( samePoints ) {
  23475. deltaAngle = 0;
  23476. } else {
  23477. deltaAngle = twoPi;
  23478. }
  23479. }
  23480. if ( this.aClockwise === true && ! samePoints ) {
  23481. if ( deltaAngle === twoPi ) {
  23482. deltaAngle = - twoPi;
  23483. } else {
  23484. deltaAngle = deltaAngle - twoPi;
  23485. }
  23486. }
  23487. const angle = this.aStartAngle + t * deltaAngle;
  23488. let x = this.aX + this.xRadius * Math.cos( angle );
  23489. let y = this.aY + this.yRadius * Math.sin( angle );
  23490. if ( this.aRotation !== 0 ) {
  23491. const cos = Math.cos( this.aRotation );
  23492. const sin = Math.sin( this.aRotation );
  23493. const tx = x - this.aX;
  23494. const ty = y - this.aY;
  23495. // Rotate the point about the center of the ellipse.
  23496. x = tx * cos - ty * sin + this.aX;
  23497. y = tx * sin + ty * cos + this.aY;
  23498. }
  23499. return point.set( x, y );
  23500. }
  23501. copy( source ) {
  23502. super.copy( source );
  23503. this.aX = source.aX;
  23504. this.aY = source.aY;
  23505. this.xRadius = source.xRadius;
  23506. this.yRadius = source.yRadius;
  23507. this.aStartAngle = source.aStartAngle;
  23508. this.aEndAngle = source.aEndAngle;
  23509. this.aClockwise = source.aClockwise;
  23510. this.aRotation = source.aRotation;
  23511. return this;
  23512. }
  23513. toJSON() {
  23514. const data = super.toJSON();
  23515. data.aX = this.aX;
  23516. data.aY = this.aY;
  23517. data.xRadius = this.xRadius;
  23518. data.yRadius = this.yRadius;
  23519. data.aStartAngle = this.aStartAngle;
  23520. data.aEndAngle = this.aEndAngle;
  23521. data.aClockwise = this.aClockwise;
  23522. data.aRotation = this.aRotation;
  23523. return data;
  23524. }
  23525. fromJSON( json ) {
  23526. super.fromJSON( json );
  23527. this.aX = json.aX;
  23528. this.aY = json.aY;
  23529. this.xRadius = json.xRadius;
  23530. this.yRadius = json.yRadius;
  23531. this.aStartAngle = json.aStartAngle;
  23532. this.aEndAngle = json.aEndAngle;
  23533. this.aClockwise = json.aClockwise;
  23534. this.aRotation = json.aRotation;
  23535. return this;
  23536. }
  23537. }
  23538. /**
  23539. * A curve representing an arc.
  23540. *
  23541. * @augments EllipseCurve
  23542. */
  23543. class ArcCurve extends EllipseCurve {
  23544. /**
  23545. * Constructs a new arc curve.
  23546. *
  23547. * @param {number} [aX=0] - The X center of the ellipse.
  23548. * @param {number} [aY=0] - The Y center of the ellipse.
  23549. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23550. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23551. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23552. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23553. */
  23554. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23555. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23556. /**
  23557. * This flag can be used for type testing.
  23558. *
  23559. * @type {boolean}
  23560. * @readonly
  23561. * @default true
  23562. */
  23563. this.isArcCurve = true;
  23564. this.type = 'ArcCurve';
  23565. }
  23566. }
  23567. function CubicPoly() {
  23568. /**
  23569. * Centripetal CatmullRom Curve - which is useful for avoiding
  23570. * cusps and self-intersections in non-uniform catmull rom curves.
  23571. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23572. *
  23573. * curve.type accepts centripetal(default), chordal and catmullrom
  23574. * curve.tension is used for catmullrom which defaults to 0.5
  23575. */
  23576. /*
  23577. Based on an optimized c++ solution in
  23578. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23579. - http://ideone.com/NoEbVM
  23580. This CubicPoly class could be used for reusing some variables and calculations,
  23581. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23582. which can be placed in CurveUtils.
  23583. */
  23584. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23585. /*
  23586. * Compute coefficients for a cubic polynomial
  23587. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23588. * such that
  23589. * p(0) = x0, p(1) = x1
  23590. * and
  23591. * p'(0) = t0, p'(1) = t1.
  23592. */
  23593. function init( x0, x1, t0, t1 ) {
  23594. c0 = x0;
  23595. c1 = t0;
  23596. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23597. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23598. }
  23599. return {
  23600. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23601. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23602. },
  23603. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23604. // compute tangents when parameterized in [t1,t2]
  23605. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23606. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23607. // rescale tangents for parametrization in [0,1]
  23608. t1 *= dt1;
  23609. t2 *= dt1;
  23610. init( x1, x2, t1, t2 );
  23611. },
  23612. calc: function ( t ) {
  23613. const t2 = t * t;
  23614. const t3 = t2 * t;
  23615. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23616. }
  23617. };
  23618. }
  23619. //
  23620. const tmp = /*@__PURE__*/ new Vector3();
  23621. const px = /*@__PURE__*/ new CubicPoly();
  23622. const py = /*@__PURE__*/ new CubicPoly();
  23623. const pz = /*@__PURE__*/ new CubicPoly();
  23624. /**
  23625. * A curve representing a Catmull-Rom spline.
  23626. *
  23627. * ```js
  23628. * //Create a closed wavey loop
  23629. * const curve = new THREE.CatmullRomCurve3( [
  23630. * new THREE.Vector3( -10, 0, 10 ),
  23631. * new THREE.Vector3( -5, 5, 5 ),
  23632. * new THREE.Vector3( 0, 0, 0 ),
  23633. * new THREE.Vector3( 5, -5, 5 ),
  23634. * new THREE.Vector3( 10, 0, 10 )
  23635. * ] );
  23636. *
  23637. * const points = curve.getPoints( 50 );
  23638. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23639. *
  23640. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23641. *
  23642. * // Create the final object to add to the scene
  23643. * const curveObject = new THREE.Line( geometry, material );
  23644. * ```
  23645. *
  23646. * @augments Curve
  23647. */
  23648. class CatmullRomCurve3 extends Curve {
  23649. /**
  23650. * Constructs a new Catmull-Rom curve.
  23651. *
  23652. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23653. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23654. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23655. * @param {number} [tension=0.5] - Tension of the curve.
  23656. */
  23657. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23658. super();
  23659. /**
  23660. * This flag can be used for type testing.
  23661. *
  23662. * @type {boolean}
  23663. * @readonly
  23664. * @default true
  23665. */
  23666. this.isCatmullRomCurve3 = true;
  23667. this.type = 'CatmullRomCurve3';
  23668. /**
  23669. * An array of 3D points defining the curve.
  23670. *
  23671. * @type {Array<Vector3>}
  23672. */
  23673. this.points = points;
  23674. /**
  23675. * Whether the curve is closed or not.
  23676. *
  23677. * @type {boolean}
  23678. * @default false
  23679. */
  23680. this.closed = closed;
  23681. /**
  23682. * The curve type.
  23683. *
  23684. * @type {('centripetal'|'chordal'|'catmullrom')}
  23685. * @default 'centripetal'
  23686. */
  23687. this.curveType = curveType;
  23688. /**
  23689. * Tension of the curve.
  23690. *
  23691. * @type {number}
  23692. * @default 0.5
  23693. */
  23694. this.tension = tension;
  23695. }
  23696. /**
  23697. * Returns a point on the curve.
  23698. *
  23699. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23700. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23701. * @return {Vector3} The position on the curve.
  23702. */
  23703. getPoint( t, optionalTarget = new Vector3() ) {
  23704. const point = optionalTarget;
  23705. const points = this.points;
  23706. const l = points.length;
  23707. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23708. let intPoint = Math.floor( p );
  23709. let weight = p - intPoint;
  23710. if ( this.closed ) {
  23711. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23712. } else if ( weight === 0 && intPoint === l - 1 ) {
  23713. intPoint = l - 2;
  23714. weight = 1;
  23715. }
  23716. let p0, p3; // 4 points (p1 & p2 defined below)
  23717. if ( this.closed || intPoint > 0 ) {
  23718. p0 = points[ ( intPoint - 1 ) % l ];
  23719. } else {
  23720. // extrapolate first point
  23721. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23722. p0 = tmp;
  23723. }
  23724. const p1 = points[ intPoint % l ];
  23725. const p2 = points[ ( intPoint + 1 ) % l ];
  23726. if ( this.closed || intPoint + 2 < l ) {
  23727. p3 = points[ ( intPoint + 2 ) % l ];
  23728. } else {
  23729. // extrapolate last point
  23730. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23731. p3 = tmp;
  23732. }
  23733. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23734. // init Centripetal / Chordal Catmull-Rom
  23735. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23736. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23737. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23738. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23739. // safety check for repeated points
  23740. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23741. if ( dt0 < 1e-4 ) dt0 = dt1;
  23742. if ( dt2 < 1e-4 ) dt2 = dt1;
  23743. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23744. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23745. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23746. } else if ( this.curveType === 'catmullrom' ) {
  23747. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23748. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23749. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23750. }
  23751. point.set(
  23752. px.calc( weight ),
  23753. py.calc( weight ),
  23754. pz.calc( weight )
  23755. );
  23756. return point;
  23757. }
  23758. copy( source ) {
  23759. super.copy( source );
  23760. this.points = [];
  23761. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23762. const point = source.points[ i ];
  23763. this.points.push( point.clone() );
  23764. }
  23765. this.closed = source.closed;
  23766. this.curveType = source.curveType;
  23767. this.tension = source.tension;
  23768. return this;
  23769. }
  23770. toJSON() {
  23771. const data = super.toJSON();
  23772. data.points = [];
  23773. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23774. const point = this.points[ i ];
  23775. data.points.push( point.toArray() );
  23776. }
  23777. data.closed = this.closed;
  23778. data.curveType = this.curveType;
  23779. data.tension = this.tension;
  23780. return data;
  23781. }
  23782. fromJSON( json ) {
  23783. super.fromJSON( json );
  23784. this.points = [];
  23785. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23786. const point = json.points[ i ];
  23787. this.points.push( new Vector3().fromArray( point ) );
  23788. }
  23789. this.closed = json.closed;
  23790. this.curveType = json.curveType;
  23791. this.tension = json.tension;
  23792. return this;
  23793. }
  23794. }
  23795. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23796. /**
  23797. * Computes a point on a Catmull-Rom spline.
  23798. *
  23799. * @param {number} t - The interpolation factor.
  23800. * @param {number} p0 - The first control point.
  23801. * @param {number} p1 - The second control point.
  23802. * @param {number} p2 - The third control point.
  23803. * @param {number} p3 - The fourth control point.
  23804. * @return {number} The calculated point on a Catmull-Rom spline.
  23805. */
  23806. function CatmullRom( t, p0, p1, p2, p3 ) {
  23807. const v0 = ( p2 - p0 ) * 0.5;
  23808. const v1 = ( p3 - p1 ) * 0.5;
  23809. const t2 = t * t;
  23810. const t3 = t * t2;
  23811. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23812. }
  23813. //
  23814. function QuadraticBezierP0( t, p ) {
  23815. const k = 1 - t;
  23816. return k * k * p;
  23817. }
  23818. function QuadraticBezierP1( t, p ) {
  23819. return 2 * ( 1 - t ) * t * p;
  23820. }
  23821. function QuadraticBezierP2( t, p ) {
  23822. return t * t * p;
  23823. }
  23824. /**
  23825. * Computes a point on a Quadratic Bezier curve.
  23826. *
  23827. * @param {number} t - The interpolation factor.
  23828. * @param {number} p0 - The first control point.
  23829. * @param {number} p1 - The second control point.
  23830. * @param {number} p2 - The third control point.
  23831. * @return {number} The calculated point on a Quadratic Bezier curve.
  23832. */
  23833. function QuadraticBezier( t, p0, p1, p2 ) {
  23834. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23835. QuadraticBezierP2( t, p2 );
  23836. }
  23837. //
  23838. function CubicBezierP0( t, p ) {
  23839. const k = 1 - t;
  23840. return k * k * k * p;
  23841. }
  23842. function CubicBezierP1( t, p ) {
  23843. const k = 1 - t;
  23844. return 3 * k * k * t * p;
  23845. }
  23846. function CubicBezierP2( t, p ) {
  23847. return 3 * ( 1 - t ) * t * t * p;
  23848. }
  23849. function CubicBezierP3( t, p ) {
  23850. return t * t * t * p;
  23851. }
  23852. /**
  23853. * Computes a point on a Cubic Bezier curve.
  23854. *
  23855. * @param {number} t - The interpolation factor.
  23856. * @param {number} p0 - The first control point.
  23857. * @param {number} p1 - The second control point.
  23858. * @param {number} p2 - The third control point.
  23859. * @param {number} p3 - The fourth control point.
  23860. * @return {number} The calculated point on a Cubic Bezier curve.
  23861. */
  23862. function CubicBezier( t, p0, p1, p2, p3 ) {
  23863. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23864. CubicBezierP3( t, p3 );
  23865. }
  23866. /**
  23867. * A curve representing a 2D Cubic Bezier curve.
  23868. *
  23869. * ```js
  23870. * const curve = new THREE.CubicBezierCurve(
  23871. * new THREE.Vector2( - 0, 0 ),
  23872. * new THREE.Vector2( - 5, 15 ),
  23873. * new THREE.Vector2( 20, 15 ),
  23874. * new THREE.Vector2( 10, 0 )
  23875. * );
  23876. *
  23877. * const points = curve.getPoints( 50 );
  23878. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23879. *
  23880. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23881. *
  23882. * // Create the final object to add to the scene
  23883. * const curveObject = new THREE.Line( geometry, material );
  23884. * ```
  23885. *
  23886. * @augments Curve
  23887. */
  23888. class CubicBezierCurve extends Curve {
  23889. /**
  23890. * Constructs a new Cubic Bezier curve.
  23891. *
  23892. * @param {Vector2} [v0] - The start point.
  23893. * @param {Vector2} [v1] - The first control point.
  23894. * @param {Vector2} [v2] - The second control point.
  23895. * @param {Vector2} [v3] - The end point.
  23896. */
  23897. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23898. super();
  23899. /**
  23900. * This flag can be used for type testing.
  23901. *
  23902. * @type {boolean}
  23903. * @readonly
  23904. * @default true
  23905. */
  23906. this.isCubicBezierCurve = true;
  23907. this.type = 'CubicBezierCurve';
  23908. /**
  23909. * The start point.
  23910. *
  23911. * @type {Vector2}
  23912. */
  23913. this.v0 = v0;
  23914. /**
  23915. * The first control point.
  23916. *
  23917. * @type {Vector2}
  23918. */
  23919. this.v1 = v1;
  23920. /**
  23921. * The second control point.
  23922. *
  23923. * @type {Vector2}
  23924. */
  23925. this.v2 = v2;
  23926. /**
  23927. * The end point.
  23928. *
  23929. * @type {Vector2}
  23930. */
  23931. this.v3 = v3;
  23932. }
  23933. /**
  23934. * Returns a point on the curve.
  23935. *
  23936. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23937. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23938. * @return {Vector2} The position on the curve.
  23939. */
  23940. getPoint( t, optionalTarget = new Vector2() ) {
  23941. const point = optionalTarget;
  23942. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23943. point.set(
  23944. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23945. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23946. );
  23947. return point;
  23948. }
  23949. copy( source ) {
  23950. super.copy( source );
  23951. this.v0.copy( source.v0 );
  23952. this.v1.copy( source.v1 );
  23953. this.v2.copy( source.v2 );
  23954. this.v3.copy( source.v3 );
  23955. return this;
  23956. }
  23957. toJSON() {
  23958. const data = super.toJSON();
  23959. data.v0 = this.v0.toArray();
  23960. data.v1 = this.v1.toArray();
  23961. data.v2 = this.v2.toArray();
  23962. data.v3 = this.v3.toArray();
  23963. return data;
  23964. }
  23965. fromJSON( json ) {
  23966. super.fromJSON( json );
  23967. this.v0.fromArray( json.v0 );
  23968. this.v1.fromArray( json.v1 );
  23969. this.v2.fromArray( json.v2 );
  23970. this.v3.fromArray( json.v3 );
  23971. return this;
  23972. }
  23973. }
  23974. /**
  23975. * A curve representing a 3D Cubic Bezier curve.
  23976. *
  23977. * @augments Curve
  23978. */
  23979. class CubicBezierCurve3 extends Curve {
  23980. /**
  23981. * Constructs a new Cubic Bezier curve.
  23982. *
  23983. * @param {Vector3} [v0] - The start point.
  23984. * @param {Vector3} [v1] - The first control point.
  23985. * @param {Vector3} [v2] - The second control point.
  23986. * @param {Vector3} [v3] - The end point.
  23987. */
  23988. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23989. super();
  23990. /**
  23991. * This flag can be used for type testing.
  23992. *
  23993. * @type {boolean}
  23994. * @readonly
  23995. * @default true
  23996. */
  23997. this.isCubicBezierCurve3 = true;
  23998. this.type = 'CubicBezierCurve3';
  23999. /**
  24000. * The start point.
  24001. *
  24002. * @type {Vector3}
  24003. */
  24004. this.v0 = v0;
  24005. /**
  24006. * The first control point.
  24007. *
  24008. * @type {Vector3}
  24009. */
  24010. this.v1 = v1;
  24011. /**
  24012. * The second control point.
  24013. *
  24014. * @type {Vector3}
  24015. */
  24016. this.v2 = v2;
  24017. /**
  24018. * The end point.
  24019. *
  24020. * @type {Vector3}
  24021. */
  24022. this.v3 = v3;
  24023. }
  24024. /**
  24025. * Returns a point on the curve.
  24026. *
  24027. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24028. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24029. * @return {Vector3} The position on the curve.
  24030. */
  24031. getPoint( t, optionalTarget = new Vector3() ) {
  24032. const point = optionalTarget;
  24033. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24034. point.set(
  24035. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24036. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24037. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24038. );
  24039. return point;
  24040. }
  24041. copy( source ) {
  24042. super.copy( source );
  24043. this.v0.copy( source.v0 );
  24044. this.v1.copy( source.v1 );
  24045. this.v2.copy( source.v2 );
  24046. this.v3.copy( source.v3 );
  24047. return this;
  24048. }
  24049. toJSON() {
  24050. const data = super.toJSON();
  24051. data.v0 = this.v0.toArray();
  24052. data.v1 = this.v1.toArray();
  24053. data.v2 = this.v2.toArray();
  24054. data.v3 = this.v3.toArray();
  24055. return data;
  24056. }
  24057. fromJSON( json ) {
  24058. super.fromJSON( json );
  24059. this.v0.fromArray( json.v0 );
  24060. this.v1.fromArray( json.v1 );
  24061. this.v2.fromArray( json.v2 );
  24062. this.v3.fromArray( json.v3 );
  24063. return this;
  24064. }
  24065. }
  24066. /**
  24067. * A curve representing a 2D line segment.
  24068. *
  24069. * @augments Curve
  24070. */
  24071. class LineCurve extends Curve {
  24072. /**
  24073. * Constructs a new line curve.
  24074. *
  24075. * @param {Vector2} [v1] - The start point.
  24076. * @param {Vector2} [v2] - The end point.
  24077. */
  24078. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24079. super();
  24080. /**
  24081. * This flag can be used for type testing.
  24082. *
  24083. * @type {boolean}
  24084. * @readonly
  24085. * @default true
  24086. */
  24087. this.isLineCurve = true;
  24088. this.type = 'LineCurve';
  24089. /**
  24090. * The start point.
  24091. *
  24092. * @type {Vector2}
  24093. */
  24094. this.v1 = v1;
  24095. /**
  24096. * The end point.
  24097. *
  24098. * @type {Vector2}
  24099. */
  24100. this.v2 = v2;
  24101. }
  24102. /**
  24103. * Returns a point on the line.
  24104. *
  24105. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24106. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24107. * @return {Vector2} The position on the line.
  24108. */
  24109. getPoint( t, optionalTarget = new Vector2() ) {
  24110. const point = optionalTarget;
  24111. if ( t === 1 ) {
  24112. point.copy( this.v2 );
  24113. } else {
  24114. point.copy( this.v2 ).sub( this.v1 );
  24115. point.multiplyScalar( t ).add( this.v1 );
  24116. }
  24117. return point;
  24118. }
  24119. // Line curve is linear, so we can overwrite default getPointAt
  24120. getPointAt( u, optionalTarget ) {
  24121. return this.getPoint( u, optionalTarget );
  24122. }
  24123. getTangent( t, optionalTarget = new Vector2() ) {
  24124. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24125. }
  24126. getTangentAt( u, optionalTarget ) {
  24127. return this.getTangent( u, optionalTarget );
  24128. }
  24129. copy( source ) {
  24130. super.copy( source );
  24131. this.v1.copy( source.v1 );
  24132. this.v2.copy( source.v2 );
  24133. return this;
  24134. }
  24135. toJSON() {
  24136. const data = super.toJSON();
  24137. data.v1 = this.v1.toArray();
  24138. data.v2 = this.v2.toArray();
  24139. return data;
  24140. }
  24141. fromJSON( json ) {
  24142. super.fromJSON( json );
  24143. this.v1.fromArray( json.v1 );
  24144. this.v2.fromArray( json.v2 );
  24145. return this;
  24146. }
  24147. }
  24148. /**
  24149. * A curve representing a 3D line segment.
  24150. *
  24151. * @augments Curve
  24152. */
  24153. class LineCurve3 extends Curve {
  24154. /**
  24155. * Constructs a new line curve.
  24156. *
  24157. * @param {Vector3} [v1] - The start point.
  24158. * @param {Vector3} [v2] - The end point.
  24159. */
  24160. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24161. super();
  24162. /**
  24163. * This flag can be used for type testing.
  24164. *
  24165. * @type {boolean}
  24166. * @readonly
  24167. * @default true
  24168. */
  24169. this.isLineCurve3 = true;
  24170. this.type = 'LineCurve3';
  24171. /**
  24172. * The start point.
  24173. *
  24174. * @type {Vector3}
  24175. */
  24176. this.v1 = v1;
  24177. /**
  24178. * The end point.
  24179. *
  24180. * @type {Vector2}
  24181. */
  24182. this.v2 = v2;
  24183. }
  24184. /**
  24185. * Returns a point on the line.
  24186. *
  24187. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24188. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24189. * @return {Vector3} The position on the line.
  24190. */
  24191. getPoint( t, optionalTarget = new Vector3() ) {
  24192. const point = optionalTarget;
  24193. if ( t === 1 ) {
  24194. point.copy( this.v2 );
  24195. } else {
  24196. point.copy( this.v2 ).sub( this.v1 );
  24197. point.multiplyScalar( t ).add( this.v1 );
  24198. }
  24199. return point;
  24200. }
  24201. // Line curve is linear, so we can overwrite default getPointAt
  24202. getPointAt( u, optionalTarget ) {
  24203. return this.getPoint( u, optionalTarget );
  24204. }
  24205. getTangent( t, optionalTarget = new Vector3() ) {
  24206. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24207. }
  24208. getTangentAt( u, optionalTarget ) {
  24209. return this.getTangent( u, optionalTarget );
  24210. }
  24211. copy( source ) {
  24212. super.copy( source );
  24213. this.v1.copy( source.v1 );
  24214. this.v2.copy( source.v2 );
  24215. return this;
  24216. }
  24217. toJSON() {
  24218. const data = super.toJSON();
  24219. data.v1 = this.v1.toArray();
  24220. data.v2 = this.v2.toArray();
  24221. return data;
  24222. }
  24223. fromJSON( json ) {
  24224. super.fromJSON( json );
  24225. this.v1.fromArray( json.v1 );
  24226. this.v2.fromArray( json.v2 );
  24227. return this;
  24228. }
  24229. }
  24230. /**
  24231. * A curve representing a 2D Quadratic Bezier curve.
  24232. *
  24233. * ```js
  24234. * const curve = new THREE.QuadraticBezierCurve(
  24235. * new THREE.Vector2( - 10, 0 ),
  24236. * new THREE.Vector2( 20, 15 ),
  24237. * new THREE.Vector2( 10, 0 )
  24238. * )
  24239. *
  24240. * const points = curve.getPoints( 50 );
  24241. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24242. *
  24243. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24244. *
  24245. * // Create the final object to add to the scene
  24246. * const curveObject = new THREE.Line( geometry, material );
  24247. * ```
  24248. *
  24249. * @augments Curve
  24250. */
  24251. class QuadraticBezierCurve extends Curve {
  24252. /**
  24253. * Constructs a new Quadratic Bezier curve.
  24254. *
  24255. * @param {Vector2} [v0] - The start point.
  24256. * @param {Vector2} [v1] - The control point.
  24257. * @param {Vector2} [v2] - The end point.
  24258. */
  24259. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24260. super();
  24261. /**
  24262. * This flag can be used for type testing.
  24263. *
  24264. * @type {boolean}
  24265. * @readonly
  24266. * @default true
  24267. */
  24268. this.isQuadraticBezierCurve = true;
  24269. this.type = 'QuadraticBezierCurve';
  24270. /**
  24271. * The start point.
  24272. *
  24273. * @type {Vector2}
  24274. */
  24275. this.v0 = v0;
  24276. /**
  24277. * The control point.
  24278. *
  24279. * @type {Vector2}
  24280. */
  24281. this.v1 = v1;
  24282. /**
  24283. * The end point.
  24284. *
  24285. * @type {Vector2}
  24286. */
  24287. this.v2 = v2;
  24288. }
  24289. /**
  24290. * Returns a point on the curve.
  24291. *
  24292. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24293. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24294. * @return {Vector2} The position on the curve.
  24295. */
  24296. getPoint( t, optionalTarget = new Vector2() ) {
  24297. const point = optionalTarget;
  24298. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24299. point.set(
  24300. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24301. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24302. );
  24303. return point;
  24304. }
  24305. copy( source ) {
  24306. super.copy( source );
  24307. this.v0.copy( source.v0 );
  24308. this.v1.copy( source.v1 );
  24309. this.v2.copy( source.v2 );
  24310. return this;
  24311. }
  24312. toJSON() {
  24313. const data = super.toJSON();
  24314. data.v0 = this.v0.toArray();
  24315. data.v1 = this.v1.toArray();
  24316. data.v2 = this.v2.toArray();
  24317. return data;
  24318. }
  24319. fromJSON( json ) {
  24320. super.fromJSON( json );
  24321. this.v0.fromArray( json.v0 );
  24322. this.v1.fromArray( json.v1 );
  24323. this.v2.fromArray( json.v2 );
  24324. return this;
  24325. }
  24326. }
  24327. /**
  24328. * A curve representing a 3D Quadratic Bezier curve.
  24329. *
  24330. * @augments Curve
  24331. */
  24332. class QuadraticBezierCurve3 extends Curve {
  24333. /**
  24334. * Constructs a new Quadratic Bezier curve.
  24335. *
  24336. * @param {Vector3} [v0] - The start point.
  24337. * @param {Vector3} [v1] - The control point.
  24338. * @param {Vector3} [v2] - The end point.
  24339. */
  24340. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24341. super();
  24342. /**
  24343. * This flag can be used for type testing.
  24344. *
  24345. * @type {boolean}
  24346. * @readonly
  24347. * @default true
  24348. */
  24349. this.isQuadraticBezierCurve3 = true;
  24350. this.type = 'QuadraticBezierCurve3';
  24351. /**
  24352. * The start point.
  24353. *
  24354. * @type {Vector3}
  24355. */
  24356. this.v0 = v0;
  24357. /**
  24358. * The control point.
  24359. *
  24360. * @type {Vector3}
  24361. */
  24362. this.v1 = v1;
  24363. /**
  24364. * The end point.
  24365. *
  24366. * @type {Vector3}
  24367. */
  24368. this.v2 = v2;
  24369. }
  24370. /**
  24371. * Returns a point on the curve.
  24372. *
  24373. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24374. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24375. * @return {Vector3} The position on the curve.
  24376. */
  24377. getPoint( t, optionalTarget = new Vector3() ) {
  24378. const point = optionalTarget;
  24379. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24380. point.set(
  24381. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24382. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24383. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24384. );
  24385. return point;
  24386. }
  24387. copy( source ) {
  24388. super.copy( source );
  24389. this.v0.copy( source.v0 );
  24390. this.v1.copy( source.v1 );
  24391. this.v2.copy( source.v2 );
  24392. return this;
  24393. }
  24394. toJSON() {
  24395. const data = super.toJSON();
  24396. data.v0 = this.v0.toArray();
  24397. data.v1 = this.v1.toArray();
  24398. data.v2 = this.v2.toArray();
  24399. return data;
  24400. }
  24401. fromJSON( json ) {
  24402. super.fromJSON( json );
  24403. this.v0.fromArray( json.v0 );
  24404. this.v1.fromArray( json.v1 );
  24405. this.v2.fromArray( json.v2 );
  24406. return this;
  24407. }
  24408. }
  24409. /**
  24410. * A curve representing a 2D spline curve.
  24411. *
  24412. * ```js
  24413. * // Create a sine-like wave
  24414. * const curve = new THREE.SplineCurve( [
  24415. * new THREE.Vector2( -10, 0 ),
  24416. * new THREE.Vector2( -5, 5 ),
  24417. * new THREE.Vector2( 0, 0 ),
  24418. * new THREE.Vector2( 5, -5 ),
  24419. * new THREE.Vector2( 10, 0 )
  24420. * ] );
  24421. *
  24422. * const points = curve.getPoints( 50 );
  24423. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24424. *
  24425. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24426. *
  24427. * // Create the final object to add to the scene
  24428. * const splineObject = new THREE.Line( geometry, material );
  24429. * ```
  24430. *
  24431. * @augments Curve
  24432. */
  24433. class SplineCurve extends Curve {
  24434. /**
  24435. * Constructs a new 2D spline curve.
  24436. *
  24437. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24438. */
  24439. constructor( points = [] ) {
  24440. super();
  24441. /**
  24442. * This flag can be used for type testing.
  24443. *
  24444. * @type {boolean}
  24445. * @readonly
  24446. * @default true
  24447. */
  24448. this.isSplineCurve = true;
  24449. this.type = 'SplineCurve';
  24450. /**
  24451. * An array of 2D points defining the curve.
  24452. *
  24453. * @type {Array<Vector2>}
  24454. */
  24455. this.points = points;
  24456. }
  24457. /**
  24458. * Returns a point on the curve.
  24459. *
  24460. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24461. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24462. * @return {Vector2} The position on the curve.
  24463. */
  24464. getPoint( t, optionalTarget = new Vector2() ) {
  24465. const point = optionalTarget;
  24466. const points = this.points;
  24467. const p = ( points.length - 1 ) * t;
  24468. const intPoint = Math.floor( p );
  24469. const weight = p - intPoint;
  24470. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24471. const p1 = points[ intPoint ];
  24472. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24473. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24474. point.set(
  24475. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24476. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24477. );
  24478. return point;
  24479. }
  24480. copy( source ) {
  24481. super.copy( source );
  24482. this.points = [];
  24483. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24484. const point = source.points[ i ];
  24485. this.points.push( point.clone() );
  24486. }
  24487. return this;
  24488. }
  24489. toJSON() {
  24490. const data = super.toJSON();
  24491. data.points = [];
  24492. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24493. const point = this.points[ i ];
  24494. data.points.push( point.toArray() );
  24495. }
  24496. return data;
  24497. }
  24498. fromJSON( json ) {
  24499. super.fromJSON( json );
  24500. this.points = [];
  24501. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24502. const point = json.points[ i ];
  24503. this.points.push( new Vector2().fromArray( point ) );
  24504. }
  24505. return this;
  24506. }
  24507. }
  24508. var Curves = /*#__PURE__*/Object.freeze({
  24509. __proto__: null,
  24510. ArcCurve: ArcCurve,
  24511. CatmullRomCurve3: CatmullRomCurve3,
  24512. CubicBezierCurve: CubicBezierCurve,
  24513. CubicBezierCurve3: CubicBezierCurve3,
  24514. EllipseCurve: EllipseCurve,
  24515. LineCurve: LineCurve,
  24516. LineCurve3: LineCurve3,
  24517. QuadraticBezierCurve: QuadraticBezierCurve,
  24518. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24519. SplineCurve: SplineCurve
  24520. });
  24521. /**
  24522. * A base class extending {@link Curve}. `CurvePath` is simply an
  24523. * array of connected curves, but retains the API of a curve.
  24524. *
  24525. * @augments Curve
  24526. */
  24527. class CurvePath extends Curve {
  24528. /**
  24529. * Constructs a new curve path.
  24530. */
  24531. constructor() {
  24532. super();
  24533. this.type = 'CurvePath';
  24534. /**
  24535. * An array of curves defining the
  24536. * path.
  24537. *
  24538. * @type {Array<Curve>}
  24539. */
  24540. this.curves = [];
  24541. /**
  24542. * Whether the path should automatically be closed
  24543. * by a line curve.
  24544. *
  24545. * @type {boolean}
  24546. * @default false
  24547. */
  24548. this.autoClose = false;
  24549. }
  24550. /**
  24551. * Adds a curve to this curve path.
  24552. *
  24553. * @param {Curve} curve - The curve to add.
  24554. */
  24555. add( curve ) {
  24556. this.curves.push( curve );
  24557. }
  24558. /**
  24559. * Adds a line curve to close the path.
  24560. *
  24561. * @return {CurvePath} A reference to this curve path.
  24562. */
  24563. closePath() {
  24564. // Add a line curve if start and end of lines are not connected
  24565. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24566. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24567. if ( ! startPoint.equals( endPoint ) ) {
  24568. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24569. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24570. }
  24571. return this;
  24572. }
  24573. /**
  24574. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24575. * for the given interpolation factor.
  24576. *
  24577. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24578. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24579. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24580. */
  24581. getPoint( t, optionalTarget ) {
  24582. // To get accurate point with reference to
  24583. // entire path distance at time t,
  24584. // following has to be done:
  24585. // 1. Length of each sub path have to be known
  24586. // 2. Locate and identify type of curve
  24587. // 3. Get t for the curve
  24588. // 4. Return curve.getPointAt(t')
  24589. const d = t * this.getLength();
  24590. const curveLengths = this.getCurveLengths();
  24591. let i = 0;
  24592. // To think about boundaries points.
  24593. while ( i < curveLengths.length ) {
  24594. if ( curveLengths[ i ] >= d ) {
  24595. const diff = curveLengths[ i ] - d;
  24596. const curve = this.curves[ i ];
  24597. const segmentLength = curve.getLength();
  24598. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24599. return curve.getPointAt( u, optionalTarget );
  24600. }
  24601. i ++;
  24602. }
  24603. return null;
  24604. // loop where sum != 0, sum > d , sum+1 <d
  24605. }
  24606. getLength() {
  24607. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24608. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24609. // getPoint() depends on getLength
  24610. const lens = this.getCurveLengths();
  24611. return lens[ lens.length - 1 ];
  24612. }
  24613. updateArcLengths() {
  24614. // cacheLengths must be recalculated.
  24615. this.needsUpdate = true;
  24616. this.cacheLengths = null;
  24617. this.getCurveLengths();
  24618. }
  24619. /**
  24620. * Returns list of cumulative curve lengths of the defined curves.
  24621. *
  24622. * @return {Array<number>} The curve lengths.
  24623. */
  24624. getCurveLengths() {
  24625. // Compute lengths and cache them
  24626. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24627. // We use cache values if curves and cache array are same length
  24628. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24629. return this.cacheLengths;
  24630. }
  24631. // Get length of sub-curve
  24632. // Push sums into cached array
  24633. const lengths = [];
  24634. let sums = 0;
  24635. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24636. sums += this.curves[ i ].getLength();
  24637. lengths.push( sums );
  24638. }
  24639. this.cacheLengths = lengths;
  24640. return lengths;
  24641. }
  24642. getSpacedPoints( divisions = 40 ) {
  24643. const points = [];
  24644. for ( let i = 0; i <= divisions; i ++ ) {
  24645. points.push( this.getPoint( i / divisions ) );
  24646. }
  24647. if ( this.autoClose ) {
  24648. points.push( points[ 0 ] );
  24649. }
  24650. return points;
  24651. }
  24652. getPoints( divisions = 12 ) {
  24653. const points = [];
  24654. let last;
  24655. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24656. const curve = curves[ i ];
  24657. const resolution = curve.isEllipseCurve ? divisions * 2
  24658. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24659. : curve.isSplineCurve ? divisions * curve.points.length
  24660. : divisions;
  24661. const pts = curve.getPoints( resolution );
  24662. for ( let j = 0; j < pts.length; j ++ ) {
  24663. const point = pts[ j ];
  24664. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24665. points.push( point );
  24666. last = point;
  24667. }
  24668. }
  24669. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24670. points.push( points[ 0 ] );
  24671. }
  24672. return points;
  24673. }
  24674. copy( source ) {
  24675. super.copy( source );
  24676. this.curves = [];
  24677. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24678. const curve = source.curves[ i ];
  24679. this.curves.push( curve.clone() );
  24680. }
  24681. this.autoClose = source.autoClose;
  24682. return this;
  24683. }
  24684. toJSON() {
  24685. const data = super.toJSON();
  24686. data.autoClose = this.autoClose;
  24687. data.curves = [];
  24688. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24689. const curve = this.curves[ i ];
  24690. data.curves.push( curve.toJSON() );
  24691. }
  24692. return data;
  24693. }
  24694. fromJSON( json ) {
  24695. super.fromJSON( json );
  24696. this.autoClose = json.autoClose;
  24697. this.curves = [];
  24698. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24699. const curve = json.curves[ i ];
  24700. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24701. }
  24702. return this;
  24703. }
  24704. }
  24705. /**
  24706. * A 2D path representation. The class provides methods for creating paths
  24707. * and contours of 2D shapes similar to the 2D Canvas API.
  24708. *
  24709. * ```js
  24710. * const path = new THREE.Path();
  24711. *
  24712. * path.lineTo( 0, 0.8 );
  24713. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24714. * path.lineTo( 1, 1 );
  24715. *
  24716. * const points = path.getPoints();
  24717. *
  24718. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24719. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24720. *
  24721. * const line = new THREE.Line( geometry, material );
  24722. * scene.add( line );
  24723. * ```
  24724. *
  24725. * @augments CurvePath
  24726. */
  24727. class Path extends CurvePath {
  24728. /**
  24729. * Constructs a new path.
  24730. *
  24731. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24732. */
  24733. constructor( points ) {
  24734. super();
  24735. this.type = 'Path';
  24736. /**
  24737. * The current offset of the path. Any new curve added will start here.
  24738. *
  24739. * @type {Vector2}
  24740. */
  24741. this.currentPoint = new Vector2();
  24742. if ( points ) {
  24743. this.setFromPoints( points );
  24744. }
  24745. }
  24746. /**
  24747. * Creates a path from the given list of points. The points are added
  24748. * to the path as instances of {@link LineCurve}.
  24749. *
  24750. * @param {Array<Vector2>} points - An array of 2D points.
  24751. * @return {Path} A reference to this path.
  24752. */
  24753. setFromPoints( points ) {
  24754. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24755. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24756. this.lineTo( points[ i ].x, points[ i ].y );
  24757. }
  24758. return this;
  24759. }
  24760. /**
  24761. * Moves {@link Path#currentPoint} to the given point.
  24762. *
  24763. * @param {number} x - The x coordinate.
  24764. * @param {number} y - The y coordinate.
  24765. * @return {Path} A reference to this path.
  24766. */
  24767. moveTo( x, y ) {
  24768. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24769. return this;
  24770. }
  24771. /**
  24772. * Adds an instance of {@link LineCurve} to the path by connecting
  24773. * the current point with the given one.
  24774. *
  24775. * @param {number} x - The x coordinate of the end point.
  24776. * @param {number} y - The y coordinate of the end point.
  24777. * @return {Path} A reference to this path.
  24778. */
  24779. lineTo( x, y ) {
  24780. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24781. this.curves.push( curve );
  24782. this.currentPoint.set( x, y );
  24783. return this;
  24784. }
  24785. /**
  24786. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24787. * the current point with the given one.
  24788. *
  24789. * @param {number} aCPx - The x coordinate of the control point.
  24790. * @param {number} aCPy - The y coordinate of the control point.
  24791. * @param {number} aX - The x coordinate of the end point.
  24792. * @param {number} aY - The y coordinate of the end point.
  24793. * @return {Path} A reference to this path.
  24794. */
  24795. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24796. const curve = new QuadraticBezierCurve(
  24797. this.currentPoint.clone(),
  24798. new Vector2( aCPx, aCPy ),
  24799. new Vector2( aX, aY )
  24800. );
  24801. this.curves.push( curve );
  24802. this.currentPoint.set( aX, aY );
  24803. return this;
  24804. }
  24805. /**
  24806. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24807. * the current point with the given one.
  24808. *
  24809. * @param {number} aCP1x - The x coordinate of the first control point.
  24810. * @param {number} aCP1y - The y coordinate of the first control point.
  24811. * @param {number} aCP2x - The x coordinate of the second control point.
  24812. * @param {number} aCP2y - The y coordinate of the second control point.
  24813. * @param {number} aX - The x coordinate of the end point.
  24814. * @param {number} aY - The y coordinate of the end point.
  24815. * @return {Path} A reference to this path.
  24816. */
  24817. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24818. const curve = new CubicBezierCurve(
  24819. this.currentPoint.clone(),
  24820. new Vector2( aCP1x, aCP1y ),
  24821. new Vector2( aCP2x, aCP2y ),
  24822. new Vector2( aX, aY )
  24823. );
  24824. this.curves.push( curve );
  24825. this.currentPoint.set( aX, aY );
  24826. return this;
  24827. }
  24828. /**
  24829. * Adds an instance of {@link SplineCurve} to the path by connecting
  24830. * the current point with the given list of points.
  24831. *
  24832. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24833. * @return {Path} A reference to this path.
  24834. */
  24835. splineThru( pts ) {
  24836. const npts = [ this.currentPoint.clone() ].concat( pts );
  24837. const curve = new SplineCurve( npts );
  24838. this.curves.push( curve );
  24839. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24840. return this;
  24841. }
  24842. /**
  24843. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24844. * to the current point.
  24845. *
  24846. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24847. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24848. * @param {number} [aRadius=1] - The radius of the arc.
  24849. * @param {number} [aStartAngle=0] - The start angle in radians.
  24850. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24851. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24852. * @return {Path} A reference to this path.
  24853. */
  24854. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24855. const x0 = this.currentPoint.x;
  24856. const y0 = this.currentPoint.y;
  24857. this.absarc( aX + x0, aY + y0, aRadius,
  24858. aStartAngle, aEndAngle, aClockwise );
  24859. return this;
  24860. }
  24861. /**
  24862. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24863. *
  24864. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24865. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24866. * @param {number} [aRadius=1] - The radius of the arc.
  24867. * @param {number} [aStartAngle=0] - The start angle in radians.
  24868. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24869. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24870. * @return {Path} A reference to this path.
  24871. */
  24872. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24873. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24874. return this;
  24875. }
  24876. /**
  24877. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24878. * to the current point
  24879. *
  24880. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24881. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24882. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24883. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24884. * @param {number} [aStartAngle=0] - The start angle in radians.
  24885. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24886. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24887. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24888. * @return {Path} A reference to this path.
  24889. */
  24890. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24891. const x0 = this.currentPoint.x;
  24892. const y0 = this.currentPoint.y;
  24893. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24894. return this;
  24895. }
  24896. /**
  24897. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24898. *
  24899. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24900. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24901. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24902. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24903. * @param {number} [aStartAngle=0] - The start angle in radians.
  24904. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24905. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24906. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24907. * @return {Path} A reference to this path.
  24908. */
  24909. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24910. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24911. if ( this.curves.length > 0 ) {
  24912. // if a previous curve is present, attempt to join
  24913. const firstPoint = curve.getPoint( 0 );
  24914. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24915. this.lineTo( firstPoint.x, firstPoint.y );
  24916. }
  24917. }
  24918. this.curves.push( curve );
  24919. const lastPoint = curve.getPoint( 1 );
  24920. this.currentPoint.copy( lastPoint );
  24921. return this;
  24922. }
  24923. copy( source ) {
  24924. super.copy( source );
  24925. this.currentPoint.copy( source.currentPoint );
  24926. return this;
  24927. }
  24928. toJSON() {
  24929. const data = super.toJSON();
  24930. data.currentPoint = this.currentPoint.toArray();
  24931. return data;
  24932. }
  24933. fromJSON( json ) {
  24934. super.fromJSON( json );
  24935. this.currentPoint.fromArray( json.currentPoint );
  24936. return this;
  24937. }
  24938. }
  24939. /**
  24940. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24941. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24942. * points, or to get triangulated faces.
  24943. *
  24944. * ```js
  24945. * const heartShape = new THREE.Shape();
  24946. *
  24947. * heartShape.moveTo( 25, 25 );
  24948. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24949. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24950. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24951. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24952. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24953. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24954. *
  24955. * const extrudeSettings = {
  24956. * depth: 8,
  24957. * bevelEnabled: true,
  24958. * bevelSegments: 2,
  24959. * steps: 2,
  24960. * bevelSize: 1,
  24961. * bevelThickness: 1
  24962. * };
  24963. *
  24964. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24965. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24966. * ```
  24967. *
  24968. * @augments Path
  24969. */
  24970. class Shape extends Path {
  24971. /**
  24972. * Constructs a new shape.
  24973. *
  24974. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24975. */
  24976. constructor( points ) {
  24977. super( points );
  24978. /**
  24979. * The UUID of the shape.
  24980. *
  24981. * @type {string}
  24982. * @readonly
  24983. */
  24984. this.uuid = generateUUID();
  24985. this.type = 'Shape';
  24986. /**
  24987. * Defines the holes in the shape. Hole definitions must use the
  24988. * opposite winding order (CW/CCW) than the outer shape.
  24989. *
  24990. * @type {Array<Path>}
  24991. * @readonly
  24992. */
  24993. this.holes = [];
  24994. }
  24995. /**
  24996. * Returns an array representing each contour of the holes
  24997. * as a list of 2D points.
  24998. *
  24999. * @param {number} divisions - The fineness of the result.
  25000. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25001. */
  25002. getPointsHoles( divisions ) {
  25003. const holesPts = [];
  25004. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25005. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25006. }
  25007. return holesPts;
  25008. }
  25009. // get points of shape and holes (keypoints based on segments parameter)
  25010. /**
  25011. * Returns an object that holds contour data for the shape and its holes as
  25012. * arrays of 2D points.
  25013. *
  25014. * @param {number} divisions - The fineness of the result.
  25015. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25016. */
  25017. extractPoints( divisions ) {
  25018. return {
  25019. shape: this.getPoints( divisions ),
  25020. holes: this.getPointsHoles( divisions )
  25021. };
  25022. }
  25023. copy( source ) {
  25024. super.copy( source );
  25025. this.holes = [];
  25026. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25027. const hole = source.holes[ i ];
  25028. this.holes.push( hole.clone() );
  25029. }
  25030. return this;
  25031. }
  25032. toJSON() {
  25033. const data = super.toJSON();
  25034. data.uuid = this.uuid;
  25035. data.holes = [];
  25036. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25037. const hole = this.holes[ i ];
  25038. data.holes.push( hole.toJSON() );
  25039. }
  25040. return data;
  25041. }
  25042. fromJSON( json ) {
  25043. super.fromJSON( json );
  25044. this.uuid = json.uuid;
  25045. this.holes = [];
  25046. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25047. const hole = json.holes[ i ];
  25048. this.holes.push( new Path().fromJSON( hole ) );
  25049. }
  25050. return this;
  25051. }
  25052. }
  25053. /* eslint-disable */
  25054. // copy of mapbox/earcut version 3.0.1
  25055. // https://github.com/mapbox/earcut/tree/v3.0.1
  25056. function earcut(data, holeIndices, dim = 2) {
  25057. const hasHoles = holeIndices && holeIndices.length;
  25058. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25059. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25060. const triangles = [];
  25061. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25062. let minX, minY, invSize;
  25063. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25064. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25065. if (data.length > 80 * dim) {
  25066. minX = Infinity;
  25067. minY = Infinity;
  25068. let maxX = -Infinity;
  25069. let maxY = -Infinity;
  25070. for (let i = dim; i < outerLen; i += dim) {
  25071. const x = data[i];
  25072. const y = data[i + 1];
  25073. if (x < minX) minX = x;
  25074. if (y < minY) minY = y;
  25075. if (x > maxX) maxX = x;
  25076. if (y > maxY) maxY = y;
  25077. }
  25078. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25079. invSize = Math.max(maxX - minX, maxY - minY);
  25080. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25081. }
  25082. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25083. return triangles;
  25084. }
  25085. // create a circular doubly linked list from polygon points in the specified winding order
  25086. function linkedList(data, start, end, dim, clockwise) {
  25087. let last;
  25088. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25089. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25090. } else {
  25091. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25092. }
  25093. if (last && equals(last, last.next)) {
  25094. removeNode(last);
  25095. last = last.next;
  25096. }
  25097. return last;
  25098. }
  25099. // eliminate colinear or duplicate points
  25100. function filterPoints(start, end) {
  25101. if (!start) return start;
  25102. if (!end) end = start;
  25103. let p = start,
  25104. again;
  25105. do {
  25106. again = false;
  25107. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25108. removeNode(p);
  25109. p = end = p.prev;
  25110. if (p === p.next) break;
  25111. again = true;
  25112. } else {
  25113. p = p.next;
  25114. }
  25115. } while (again || p !== end);
  25116. return end;
  25117. }
  25118. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25119. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25120. if (!ear) return;
  25121. // interlink polygon nodes in z-order
  25122. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25123. let stop = ear;
  25124. // iterate through ears, slicing them one by one
  25125. while (ear.prev !== ear.next) {
  25126. const prev = ear.prev;
  25127. const next = ear.next;
  25128. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25129. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25130. removeNode(ear);
  25131. // skipping the next vertex leads to less sliver triangles
  25132. ear = next.next;
  25133. stop = next.next;
  25134. continue;
  25135. }
  25136. ear = next;
  25137. // if we looped through the whole remaining polygon and can't find any more ears
  25138. if (ear === stop) {
  25139. // try filtering points and slicing again
  25140. if (!pass) {
  25141. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25142. // if this didn't work, try curing all small self-intersections locally
  25143. } else if (pass === 1) {
  25144. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25145. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25146. // as a last resort, try splitting the remaining polygon into two
  25147. } else if (pass === 2) {
  25148. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25149. }
  25150. break;
  25151. }
  25152. }
  25153. }
  25154. // check whether a polygon node forms a valid ear with adjacent nodes
  25155. function isEar(ear) {
  25156. const a = ear.prev,
  25157. b = ear,
  25158. c = ear.next;
  25159. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25160. // now make sure we don't have other points inside the potential ear
  25161. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25162. // triangle bbox
  25163. const x0 = Math.min(ax, bx, cx),
  25164. y0 = Math.min(ay, by, cy),
  25165. x1 = Math.max(ax, bx, cx),
  25166. y1 = Math.max(ay, by, cy);
  25167. let p = c.next;
  25168. while (p !== a) {
  25169. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25170. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25171. area(p.prev, p, p.next) >= 0) return false;
  25172. p = p.next;
  25173. }
  25174. return true;
  25175. }
  25176. function isEarHashed(ear, minX, minY, invSize) {
  25177. const a = ear.prev,
  25178. b = ear,
  25179. c = ear.next;
  25180. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25181. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25182. // triangle bbox
  25183. const x0 = Math.min(ax, bx, cx),
  25184. y0 = Math.min(ay, by, cy),
  25185. x1 = Math.max(ax, bx, cx),
  25186. y1 = Math.max(ay, by, cy);
  25187. // z-order range for the current triangle bbox;
  25188. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25189. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25190. let p = ear.prevZ,
  25191. n = ear.nextZ;
  25192. // look for points inside the triangle in both directions
  25193. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25194. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25195. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25196. p = p.prevZ;
  25197. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25198. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25199. n = n.nextZ;
  25200. }
  25201. // look for remaining points in decreasing z-order
  25202. while (p && p.z >= minZ) {
  25203. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25204. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25205. p = p.prevZ;
  25206. }
  25207. // look for remaining points in increasing z-order
  25208. while (n && n.z <= maxZ) {
  25209. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25210. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25211. n = n.nextZ;
  25212. }
  25213. return true;
  25214. }
  25215. // go through all polygon nodes and cure small local self-intersections
  25216. function cureLocalIntersections(start, triangles) {
  25217. let p = start;
  25218. do {
  25219. const a = p.prev,
  25220. b = p.next.next;
  25221. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25222. triangles.push(a.i, p.i, b.i);
  25223. // remove two nodes involved
  25224. removeNode(p);
  25225. removeNode(p.next);
  25226. p = start = b;
  25227. }
  25228. p = p.next;
  25229. } while (p !== start);
  25230. return filterPoints(p);
  25231. }
  25232. // try splitting polygon into two and triangulate them independently
  25233. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25234. // look for a valid diagonal that divides the polygon into two
  25235. let a = start;
  25236. do {
  25237. let b = a.next.next;
  25238. while (b !== a.prev) {
  25239. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25240. // split the polygon in two by the diagonal
  25241. let c = splitPolygon(a, b);
  25242. // filter colinear points around the cuts
  25243. a = filterPoints(a, a.next);
  25244. c = filterPoints(c, c.next);
  25245. // run earcut on each half
  25246. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25247. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25248. return;
  25249. }
  25250. b = b.next;
  25251. }
  25252. a = a.next;
  25253. } while (a !== start);
  25254. }
  25255. // link every hole into the outer loop, producing a single-ring polygon without holes
  25256. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25257. const queue = [];
  25258. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25259. const start = holeIndices[i] * dim;
  25260. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25261. const list = linkedList(data, start, end, dim, false);
  25262. if (list === list.next) list.steiner = true;
  25263. queue.push(getLeftmost(list));
  25264. }
  25265. queue.sort(compareXYSlope);
  25266. // process holes from left to right
  25267. for (let i = 0; i < queue.length; i++) {
  25268. outerNode = eliminateHole(queue[i], outerNode);
  25269. }
  25270. return outerNode;
  25271. }
  25272. function compareXYSlope(a, b) {
  25273. let result = a.x - b.x;
  25274. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25275. // the bridge to the outer shell is always the point that they meet at.
  25276. if (result === 0) {
  25277. result = a.y - b.y;
  25278. if (result === 0) {
  25279. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25280. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25281. result = aSlope - bSlope;
  25282. }
  25283. }
  25284. return result;
  25285. }
  25286. // find a bridge between vertices that connects hole with an outer ring and and link it
  25287. function eliminateHole(hole, outerNode) {
  25288. const bridge = findHoleBridge(hole, outerNode);
  25289. if (!bridge) {
  25290. return outerNode;
  25291. }
  25292. const bridgeReverse = splitPolygon(bridge, hole);
  25293. // filter collinear points around the cuts
  25294. filterPoints(bridgeReverse, bridgeReverse.next);
  25295. return filterPoints(bridge, bridge.next);
  25296. }
  25297. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25298. function findHoleBridge(hole, outerNode) {
  25299. let p = outerNode;
  25300. const hx = hole.x;
  25301. const hy = hole.y;
  25302. let qx = -Infinity;
  25303. let m;
  25304. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25305. // segment's endpoint with lesser x will be potential connection point
  25306. // unless they intersect at a vertex, then choose the vertex
  25307. if (equals(hole, p)) return p;
  25308. do {
  25309. if (equals(hole, p.next)) return p.next;
  25310. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25311. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25312. if (x <= hx && x > qx) {
  25313. qx = x;
  25314. m = p.x < p.next.x ? p : p.next;
  25315. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25316. }
  25317. }
  25318. p = p.next;
  25319. } while (p !== outerNode);
  25320. if (!m) return null;
  25321. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25322. // if there are no points found, we have a valid connection;
  25323. // otherwise choose the point of the minimum angle with the ray as connection point
  25324. const stop = m;
  25325. const mx = m.x;
  25326. const my = m.y;
  25327. let tanMin = Infinity;
  25328. p = m;
  25329. do {
  25330. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25331. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25332. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25333. if (locallyInside(p, hole) &&
  25334. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25335. m = p;
  25336. tanMin = tan;
  25337. }
  25338. }
  25339. p = p.next;
  25340. } while (p !== stop);
  25341. return m;
  25342. }
  25343. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25344. function sectorContainsSector(m, p) {
  25345. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25346. }
  25347. // interlink polygon nodes in z-order
  25348. function indexCurve(start, minX, minY, invSize) {
  25349. let p = start;
  25350. do {
  25351. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25352. p.prevZ = p.prev;
  25353. p.nextZ = p.next;
  25354. p = p.next;
  25355. } while (p !== start);
  25356. p.prevZ.nextZ = null;
  25357. p.prevZ = null;
  25358. sortLinked(p);
  25359. }
  25360. // Simon Tatham's linked list merge sort algorithm
  25361. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25362. function sortLinked(list) {
  25363. let numMerges;
  25364. let inSize = 1;
  25365. do {
  25366. let p = list;
  25367. let e;
  25368. list = null;
  25369. let tail = null;
  25370. numMerges = 0;
  25371. while (p) {
  25372. numMerges++;
  25373. let q = p;
  25374. let pSize = 0;
  25375. for (let i = 0; i < inSize; i++) {
  25376. pSize++;
  25377. q = q.nextZ;
  25378. if (!q) break;
  25379. }
  25380. let qSize = inSize;
  25381. while (pSize > 0 || (qSize > 0 && q)) {
  25382. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25383. e = p;
  25384. p = p.nextZ;
  25385. pSize--;
  25386. } else {
  25387. e = q;
  25388. q = q.nextZ;
  25389. qSize--;
  25390. }
  25391. if (tail) tail.nextZ = e;
  25392. else list = e;
  25393. e.prevZ = tail;
  25394. tail = e;
  25395. }
  25396. p = q;
  25397. }
  25398. tail.nextZ = null;
  25399. inSize *= 2;
  25400. } while (numMerges > 1);
  25401. return list;
  25402. }
  25403. // z-order of a point given coords and inverse of the longer side of data bbox
  25404. function zOrder(x, y, minX, minY, invSize) {
  25405. // coords are transformed into non-negative 15-bit integer range
  25406. x = (x - minX) * invSize | 0;
  25407. y = (y - minY) * invSize | 0;
  25408. x = (x | (x << 8)) & 0x00FF00FF;
  25409. x = (x | (x << 4)) & 0x0F0F0F0F;
  25410. x = (x | (x << 2)) & 0x33333333;
  25411. x = (x | (x << 1)) & 0x55555555;
  25412. y = (y | (y << 8)) & 0x00FF00FF;
  25413. y = (y | (y << 4)) & 0x0F0F0F0F;
  25414. y = (y | (y << 2)) & 0x33333333;
  25415. y = (y | (y << 1)) & 0x55555555;
  25416. return x | (y << 1);
  25417. }
  25418. // find the leftmost node of a polygon ring
  25419. function getLeftmost(start) {
  25420. let p = start,
  25421. leftmost = start;
  25422. do {
  25423. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25424. p = p.next;
  25425. } while (p !== start);
  25426. return leftmost;
  25427. }
  25428. // check if a point lies within a convex triangle
  25429. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25430. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25431. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25432. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25433. }
  25434. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25435. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25436. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25437. }
  25438. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25439. function isValidDiagonal(a, b) {
  25440. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25441. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25442. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25443. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25444. }
  25445. // signed area of a triangle
  25446. function area(p, q, r) {
  25447. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25448. }
  25449. // check if two points are equal
  25450. function equals(p1, p2) {
  25451. return p1.x === p2.x && p1.y === p2.y;
  25452. }
  25453. // check if two segments intersect
  25454. function intersects(p1, q1, p2, q2) {
  25455. const o1 = sign(area(p1, q1, p2));
  25456. const o2 = sign(area(p1, q1, q2));
  25457. const o3 = sign(area(p2, q2, p1));
  25458. const o4 = sign(area(p2, q2, q1));
  25459. if (o1 !== o2 && o3 !== o4) return true; // general case
  25460. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25461. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25462. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25463. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25464. return false;
  25465. }
  25466. // for collinear points p, q, r, check if point q lies on segment pr
  25467. function onSegment(p, q, r) {
  25468. 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);
  25469. }
  25470. function sign(num) {
  25471. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25472. }
  25473. // check if a polygon diagonal intersects any polygon segments
  25474. function intersectsPolygon(a, b) {
  25475. let p = a;
  25476. do {
  25477. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25478. intersects(p, p.next, a, b)) return true;
  25479. p = p.next;
  25480. } while (p !== a);
  25481. return false;
  25482. }
  25483. // check if a polygon diagonal is locally inside the polygon
  25484. function locallyInside(a, b) {
  25485. return area(a.prev, a, a.next) < 0 ?
  25486. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25487. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25488. }
  25489. // check if the middle point of a polygon diagonal is inside the polygon
  25490. function middleInside(a, b) {
  25491. let p = a;
  25492. let inside = false;
  25493. const px = (a.x + b.x) / 2;
  25494. const py = (a.y + b.y) / 2;
  25495. do {
  25496. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25497. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25498. inside = !inside;
  25499. p = p.next;
  25500. } while (p !== a);
  25501. return inside;
  25502. }
  25503. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25504. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25505. function splitPolygon(a, b) {
  25506. const a2 = createNode(a.i, a.x, a.y),
  25507. b2 = createNode(b.i, b.x, b.y),
  25508. an = a.next,
  25509. bp = b.prev;
  25510. a.next = b;
  25511. b.prev = a;
  25512. a2.next = an;
  25513. an.prev = a2;
  25514. b2.next = a2;
  25515. a2.prev = b2;
  25516. bp.next = b2;
  25517. b2.prev = bp;
  25518. return b2;
  25519. }
  25520. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25521. function insertNode(i, x, y, last) {
  25522. const p = createNode(i, x, y);
  25523. if (!last) {
  25524. p.prev = p;
  25525. p.next = p;
  25526. } else {
  25527. p.next = last.next;
  25528. p.prev = last;
  25529. last.next.prev = p;
  25530. last.next = p;
  25531. }
  25532. return p;
  25533. }
  25534. function removeNode(p) {
  25535. p.next.prev = p.prev;
  25536. p.prev.next = p.next;
  25537. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25538. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25539. }
  25540. function createNode(i, x, y) {
  25541. return {
  25542. i, // vertex index in coordinates array
  25543. x, y, // vertex coordinates
  25544. prev: null, // previous and next vertex nodes in a polygon ring
  25545. next: null,
  25546. z: 0, // z-order curve value
  25547. prevZ: null, // previous and next nodes in z-order
  25548. nextZ: null,
  25549. steiner: false // indicates whether this is a steiner point
  25550. };
  25551. }
  25552. function signedArea(data, start, end, dim) {
  25553. let sum = 0;
  25554. for (let i = start, j = end - dim; i < end; i += dim) {
  25555. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25556. j = i;
  25557. }
  25558. return sum;
  25559. }
  25560. class Earcut {
  25561. /**
  25562. * Triangulates the given shape definition by returning an array of triangles.
  25563. *
  25564. * @param {Array<number>} data - An array with 2D points.
  25565. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25566. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25567. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25568. * representing vertex indices.
  25569. */
  25570. static triangulate( data, holeIndices, dim = 2 ) {
  25571. return earcut( data, holeIndices, dim );
  25572. }
  25573. }
  25574. /**
  25575. * A class containing utility functions for shapes.
  25576. *
  25577. * @hideconstructor
  25578. */
  25579. class ShapeUtils {
  25580. /**
  25581. * Calculate area of a ( 2D ) contour polygon.
  25582. *
  25583. * @param {Array<Vector2>} contour - An array of 2D points.
  25584. * @return {number} The area.
  25585. */
  25586. static area( contour ) {
  25587. const n = contour.length;
  25588. let a = 0.0;
  25589. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25590. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25591. }
  25592. return a * 0.5;
  25593. }
  25594. /**
  25595. * Returns `true` if the given contour uses a clockwise winding order.
  25596. *
  25597. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25598. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25599. */
  25600. static isClockWise( pts ) {
  25601. return ShapeUtils.area( pts ) < 0;
  25602. }
  25603. /**
  25604. * Triangulates the given shape definition.
  25605. *
  25606. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25607. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25608. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25609. */
  25610. static triangulateShape( contour, holes ) {
  25611. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25612. const holeIndices = []; // array of hole indices
  25613. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25614. removeDupEndPts( contour );
  25615. addContour( vertices, contour );
  25616. //
  25617. let holeIndex = contour.length;
  25618. holes.forEach( removeDupEndPts );
  25619. for ( let i = 0; i < holes.length; i ++ ) {
  25620. holeIndices.push( holeIndex );
  25621. holeIndex += holes[ i ].length;
  25622. addContour( vertices, holes[ i ] );
  25623. }
  25624. //
  25625. const triangles = Earcut.triangulate( vertices, holeIndices );
  25626. //
  25627. for ( let i = 0; i < triangles.length; i += 3 ) {
  25628. faces.push( triangles.slice( i, i + 3 ) );
  25629. }
  25630. return faces;
  25631. }
  25632. }
  25633. function removeDupEndPts( points ) {
  25634. const l = points.length;
  25635. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25636. points.pop();
  25637. }
  25638. }
  25639. function addContour( vertices, contour ) {
  25640. for ( let i = 0; i < contour.length; i ++ ) {
  25641. vertices.push( contour[ i ].x );
  25642. vertices.push( contour[ i ].y );
  25643. }
  25644. }
  25645. /**
  25646. * Creates extruded geometry from a path shape.
  25647. *
  25648. * ```js
  25649. * const length = 12, width = 8;
  25650. *
  25651. * const shape = new THREE.Shape();
  25652. * shape.moveTo( 0,0 );
  25653. * shape.lineTo( 0, width );
  25654. * shape.lineTo( length, width );
  25655. * shape.lineTo( length, 0 );
  25656. * shape.lineTo( 0, 0 );
  25657. *
  25658. * const geometry = new THREE.ExtrudeGeometry( shape );
  25659. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25660. * const mesh = new THREE.Mesh( geometry, material ) ;
  25661. * scene.add( mesh );
  25662. * ```
  25663. *
  25664. * @augments BufferGeometry
  25665. */
  25666. class ExtrudeGeometry extends BufferGeometry {
  25667. /**
  25668. * Constructs a new extrude geometry.
  25669. *
  25670. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25671. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25672. */
  25673. 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 = {} ) {
  25674. super();
  25675. this.type = 'ExtrudeGeometry';
  25676. /**
  25677. * Holds the constructor parameters that have been
  25678. * used to generate the geometry. Any modification
  25679. * after instantiation does not change the geometry.
  25680. *
  25681. * @type {Object}
  25682. */
  25683. this.parameters = {
  25684. shapes: shapes,
  25685. options: options
  25686. };
  25687. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25688. const scope = this;
  25689. const verticesArray = [];
  25690. const uvArray = [];
  25691. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25692. const shape = shapes[ i ];
  25693. addShape( shape );
  25694. }
  25695. // build geometry
  25696. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25697. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25698. this.computeVertexNormals();
  25699. // functions
  25700. function addShape( shape ) {
  25701. const placeholder = [];
  25702. // options
  25703. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25704. const steps = options.steps !== undefined ? options.steps : 1;
  25705. const depth = options.depth !== undefined ? options.depth : 1;
  25706. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25707. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25708. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25709. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25710. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25711. const extrudePath = options.extrudePath;
  25712. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25713. //
  25714. let extrudePts, extrudeByPath = false;
  25715. let splineTube, binormal, normal, position2;
  25716. if ( extrudePath ) {
  25717. extrudePts = extrudePath.getSpacedPoints( steps );
  25718. extrudeByPath = true;
  25719. bevelEnabled = false; // bevels not supported for path extrusion
  25720. // SETUP TNB variables
  25721. // TODO1 - have a .isClosed in spline?
  25722. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25723. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25724. binormal = new Vector3();
  25725. normal = new Vector3();
  25726. position2 = new Vector3();
  25727. }
  25728. // Safeguards if bevels are not enabled
  25729. if ( ! bevelEnabled ) {
  25730. bevelSegments = 0;
  25731. bevelThickness = 0;
  25732. bevelSize = 0;
  25733. bevelOffset = 0;
  25734. }
  25735. // Variables initialization
  25736. const shapePoints = shape.extractPoints( curveSegments );
  25737. let vertices = shapePoints.shape;
  25738. const holes = shapePoints.holes;
  25739. const reverse = ! ShapeUtils.isClockWise( vertices );
  25740. if ( reverse ) {
  25741. vertices = vertices.reverse();
  25742. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25743. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25744. const ahole = holes[ h ];
  25745. if ( ShapeUtils.isClockWise( ahole ) ) {
  25746. holes[ h ] = ahole.reverse();
  25747. }
  25748. }
  25749. }
  25750. /**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.
  25751. * @param {Array<Vector2>} points
  25752. */
  25753. function mergeOverlappingPoints( points ) {
  25754. const THRESHOLD = 1e-10;
  25755. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25756. let prevPos = points[ 0 ];
  25757. for ( let i = 1; i <= points.length; i ++ ) {
  25758. const currentIndex = i % points.length;
  25759. const currentPos = points[ currentIndex ];
  25760. const dx = currentPos.x - prevPos.x;
  25761. const dy = currentPos.y - prevPos.y;
  25762. const distSq = dx * dx + dy * dy;
  25763. const scalingFactorSqrt = Math.max(
  25764. Math.abs( currentPos.x ),
  25765. Math.abs( currentPos.y ),
  25766. Math.abs( prevPos.x ),
  25767. Math.abs( prevPos.y )
  25768. );
  25769. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25770. if ( distSq <= thresholdSqScaled ) {
  25771. points.splice( currentIndex, 1 );
  25772. i --;
  25773. continue;
  25774. }
  25775. prevPos = currentPos;
  25776. }
  25777. }
  25778. mergeOverlappingPoints( vertices );
  25779. holes.forEach( mergeOverlappingPoints );
  25780. const numHoles = holes.length;
  25781. /* Vertices */
  25782. const contour = vertices; // vertices has all points but contour has only points of circumference
  25783. for ( let h = 0; h < numHoles; h ++ ) {
  25784. const ahole = holes[ h ];
  25785. vertices = vertices.concat( ahole );
  25786. }
  25787. function scalePt2( pt, vec, size ) {
  25788. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25789. return pt.clone().addScaledVector( vec, size );
  25790. }
  25791. const vlen = vertices.length;
  25792. // Find directions for point movement
  25793. function getBevelVec( inPt, inPrev, inNext ) {
  25794. // computes for inPt the corresponding point inPt' on a new contour
  25795. // shifted by 1 unit (length of normalized vector) to the left
  25796. // if we walk along contour clockwise, this new contour is outside the old one
  25797. //
  25798. // inPt' is the intersection of the two lines parallel to the two
  25799. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25800. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25801. // good reading for geometry algorithms (here: line-line intersection)
  25802. // http://geomalgorithms.com/a05-_intersect-1.html
  25803. const v_prev_x = inPt.x - inPrev.x,
  25804. v_prev_y = inPt.y - inPrev.y;
  25805. const v_next_x = inNext.x - inPt.x,
  25806. v_next_y = inNext.y - inPt.y;
  25807. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25808. // check for collinear edges
  25809. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25810. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25811. // not collinear
  25812. // length of vectors for normalizing
  25813. const v_prev_len = Math.sqrt( v_prev_lensq );
  25814. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25815. // shift adjacent points by unit vectors to the left
  25816. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25817. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25818. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25819. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25820. // scaling factor for v_prev to intersection point
  25821. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25822. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25823. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25824. // vector from inPt to intersection point
  25825. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25826. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25827. // Don't normalize!, otherwise sharp corners become ugly
  25828. // but prevent crazy spikes
  25829. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25830. if ( v_trans_lensq <= 2 ) {
  25831. return new Vector2( v_trans_x, v_trans_y );
  25832. } else {
  25833. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25834. }
  25835. } else {
  25836. // handle special case of collinear edges
  25837. let direction_eq = false; // assumes: opposite
  25838. if ( v_prev_x > Number.EPSILON ) {
  25839. if ( v_next_x > Number.EPSILON ) {
  25840. direction_eq = true;
  25841. }
  25842. } else {
  25843. if ( v_prev_x < - Number.EPSILON ) {
  25844. if ( v_next_x < - Number.EPSILON ) {
  25845. direction_eq = true;
  25846. }
  25847. } else {
  25848. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25849. direction_eq = true;
  25850. }
  25851. }
  25852. }
  25853. if ( direction_eq ) {
  25854. // console.log("Warning: lines are a straight sequence");
  25855. v_trans_x = - v_prev_y;
  25856. v_trans_y = v_prev_x;
  25857. shrink_by = Math.sqrt( v_prev_lensq );
  25858. } else {
  25859. // console.log("Warning: lines are a straight spike");
  25860. v_trans_x = v_prev_x;
  25861. v_trans_y = v_prev_y;
  25862. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25863. }
  25864. }
  25865. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25866. }
  25867. const contourMovements = [];
  25868. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25869. if ( j === il ) j = 0;
  25870. if ( k === il ) k = 0;
  25871. // (j)---(i)---(k)
  25872. // console.log('i,j,k', i, j , k)
  25873. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25874. }
  25875. const holesMovements = [];
  25876. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25877. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25878. const ahole = holes[ h ];
  25879. oneHoleMovements = [];
  25880. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25881. if ( j === il ) j = 0;
  25882. if ( k === il ) k = 0;
  25883. // (j)---(i)---(k)
  25884. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25885. }
  25886. holesMovements.push( oneHoleMovements );
  25887. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25888. }
  25889. let faces;
  25890. if ( bevelSegments === 0 ) {
  25891. faces = ShapeUtils.triangulateShape( contour, holes );
  25892. } else {
  25893. const contractedContourVertices = [];
  25894. const expandedHoleVertices = [];
  25895. // Loop bevelSegments, 1 for the front, 1 for the back
  25896. for ( let b = 0; b < bevelSegments; b ++ ) {
  25897. //for ( b = bevelSegments; b > 0; b -- ) {
  25898. const t = b / bevelSegments;
  25899. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25900. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25901. // contract shape
  25902. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25903. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25904. v( vert.x, vert.y, - z );
  25905. if ( t === 0 ) contractedContourVertices.push( vert );
  25906. }
  25907. // expand holes
  25908. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25909. const ahole = holes[ h ];
  25910. oneHoleMovements = holesMovements[ h ];
  25911. const oneHoleVertices = [];
  25912. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25913. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25914. v( vert.x, vert.y, - z );
  25915. if ( t === 0 ) oneHoleVertices.push( vert );
  25916. }
  25917. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25918. }
  25919. }
  25920. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25921. }
  25922. const flen = faces.length;
  25923. const bs = bevelSize + bevelOffset;
  25924. // Back facing vertices
  25925. for ( let i = 0; i < vlen; i ++ ) {
  25926. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25927. if ( ! extrudeByPath ) {
  25928. v( vert.x, vert.y, 0 );
  25929. } else {
  25930. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25931. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25932. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25933. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25934. v( position2.x, position2.y, position2.z );
  25935. }
  25936. }
  25937. // Add stepped vertices...
  25938. // Including front facing vertices
  25939. for ( let s = 1; s <= steps; s ++ ) {
  25940. for ( let i = 0; i < vlen; i ++ ) {
  25941. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25942. if ( ! extrudeByPath ) {
  25943. v( vert.x, vert.y, depth / steps * s );
  25944. } else {
  25945. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25946. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25947. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25948. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25949. v( position2.x, position2.y, position2.z );
  25950. }
  25951. }
  25952. }
  25953. // Add bevel segments planes
  25954. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25955. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25956. const t = b / bevelSegments;
  25957. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25958. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25959. // contract shape
  25960. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25961. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25962. v( vert.x, vert.y, depth + z );
  25963. }
  25964. // expand holes
  25965. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25966. const ahole = holes[ h ];
  25967. oneHoleMovements = holesMovements[ h ];
  25968. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25969. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25970. if ( ! extrudeByPath ) {
  25971. v( vert.x, vert.y, depth + z );
  25972. } else {
  25973. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25974. }
  25975. }
  25976. }
  25977. }
  25978. /* Faces */
  25979. // Top and bottom faces
  25980. buildLidFaces();
  25981. // Sides faces
  25982. buildSideFaces();
  25983. ///// Internal functions
  25984. function buildLidFaces() {
  25985. const start = verticesArray.length / 3;
  25986. if ( bevelEnabled ) {
  25987. let layer = 0; // steps + 1
  25988. let offset = vlen * layer;
  25989. // Bottom faces
  25990. for ( let i = 0; i < flen; i ++ ) {
  25991. const face = faces[ i ];
  25992. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25993. }
  25994. layer = steps + bevelSegments * 2;
  25995. offset = vlen * layer;
  25996. // Top faces
  25997. for ( let i = 0; i < flen; i ++ ) {
  25998. const face = faces[ i ];
  25999. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26000. }
  26001. } else {
  26002. // Bottom faces
  26003. for ( let i = 0; i < flen; i ++ ) {
  26004. const face = faces[ i ];
  26005. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26006. }
  26007. // Top faces
  26008. for ( let i = 0; i < flen; i ++ ) {
  26009. const face = faces[ i ];
  26010. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26011. }
  26012. }
  26013. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26014. }
  26015. // Create faces for the z-sides of the shape
  26016. function buildSideFaces() {
  26017. const start = verticesArray.length / 3;
  26018. let layeroffset = 0;
  26019. sidewalls( contour, layeroffset );
  26020. layeroffset += contour.length;
  26021. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26022. const ahole = holes[ h ];
  26023. sidewalls( ahole, layeroffset );
  26024. //, true
  26025. layeroffset += ahole.length;
  26026. }
  26027. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26028. }
  26029. function sidewalls( contour, layeroffset ) {
  26030. let i = contour.length;
  26031. while ( -- i >= 0 ) {
  26032. const j = i;
  26033. let k = i - 1;
  26034. if ( k < 0 ) k = contour.length - 1;
  26035. //console.log('b', i,j, i-1, k,vertices.length);
  26036. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26037. const slen1 = vlen * s;
  26038. const slen2 = vlen * ( s + 1 );
  26039. const a = layeroffset + j + slen1,
  26040. b = layeroffset + k + slen1,
  26041. c = layeroffset + k + slen2,
  26042. d = layeroffset + j + slen2;
  26043. f4( a, b, c, d );
  26044. }
  26045. }
  26046. }
  26047. function v( x, y, z ) {
  26048. placeholder.push( x );
  26049. placeholder.push( y );
  26050. placeholder.push( z );
  26051. }
  26052. function f3( a, b, c ) {
  26053. addVertex( a );
  26054. addVertex( b );
  26055. addVertex( c );
  26056. const nextIndex = verticesArray.length / 3;
  26057. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26058. addUV( uvs[ 0 ] );
  26059. addUV( uvs[ 1 ] );
  26060. addUV( uvs[ 2 ] );
  26061. }
  26062. function f4( a, b, c, d ) {
  26063. addVertex( a );
  26064. addVertex( b );
  26065. addVertex( d );
  26066. addVertex( b );
  26067. addVertex( c );
  26068. addVertex( d );
  26069. const nextIndex = verticesArray.length / 3;
  26070. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26071. addUV( uvs[ 0 ] );
  26072. addUV( uvs[ 1 ] );
  26073. addUV( uvs[ 3 ] );
  26074. addUV( uvs[ 1 ] );
  26075. addUV( uvs[ 2 ] );
  26076. addUV( uvs[ 3 ] );
  26077. }
  26078. function addVertex( index ) {
  26079. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26080. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26081. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26082. }
  26083. function addUV( vector2 ) {
  26084. uvArray.push( vector2.x );
  26085. uvArray.push( vector2.y );
  26086. }
  26087. }
  26088. }
  26089. copy( source ) {
  26090. super.copy( source );
  26091. this.parameters = Object.assign( {}, source.parameters );
  26092. return this;
  26093. }
  26094. toJSON() {
  26095. const data = super.toJSON();
  26096. const shapes = this.parameters.shapes;
  26097. const options = this.parameters.options;
  26098. return toJSON$1( shapes, options, data );
  26099. }
  26100. /**
  26101. * Factory method for creating an instance of this class from the given
  26102. * JSON object.
  26103. *
  26104. * @param {Object} data - A JSON object representing the serialized geometry.
  26105. * @param {Array<Shape>} shapes - An array of shapes.
  26106. * @return {ExtrudeGeometry} A new instance.
  26107. */
  26108. static fromJSON( data, shapes ) {
  26109. const geometryShapes = [];
  26110. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26111. const shape = shapes[ data.shapes[ j ] ];
  26112. geometryShapes.push( shape );
  26113. }
  26114. const extrudePath = data.options.extrudePath;
  26115. if ( extrudePath !== undefined ) {
  26116. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26117. }
  26118. return new ExtrudeGeometry( geometryShapes, data.options );
  26119. }
  26120. }
  26121. const WorldUVGenerator = {
  26122. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26123. const a_x = vertices[ indexA * 3 ];
  26124. const a_y = vertices[ indexA * 3 + 1 ];
  26125. const b_x = vertices[ indexB * 3 ];
  26126. const b_y = vertices[ indexB * 3 + 1 ];
  26127. const c_x = vertices[ indexC * 3 ];
  26128. const c_y = vertices[ indexC * 3 + 1 ];
  26129. return [
  26130. new Vector2( a_x, a_y ),
  26131. new Vector2( b_x, b_y ),
  26132. new Vector2( c_x, c_y )
  26133. ];
  26134. },
  26135. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26136. const a_x = vertices[ indexA * 3 ];
  26137. const a_y = vertices[ indexA * 3 + 1 ];
  26138. const a_z = vertices[ indexA * 3 + 2 ];
  26139. const b_x = vertices[ indexB * 3 ];
  26140. const b_y = vertices[ indexB * 3 + 1 ];
  26141. const b_z = vertices[ indexB * 3 + 2 ];
  26142. const c_x = vertices[ indexC * 3 ];
  26143. const c_y = vertices[ indexC * 3 + 1 ];
  26144. const c_z = vertices[ indexC * 3 + 2 ];
  26145. const d_x = vertices[ indexD * 3 ];
  26146. const d_y = vertices[ indexD * 3 + 1 ];
  26147. const d_z = vertices[ indexD * 3 + 2 ];
  26148. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26149. return [
  26150. new Vector2( a_x, 1 - a_z ),
  26151. new Vector2( b_x, 1 - b_z ),
  26152. new Vector2( c_x, 1 - c_z ),
  26153. new Vector2( d_x, 1 - d_z )
  26154. ];
  26155. } else {
  26156. return [
  26157. new Vector2( a_y, 1 - a_z ),
  26158. new Vector2( b_y, 1 - b_z ),
  26159. new Vector2( c_y, 1 - c_z ),
  26160. new Vector2( d_y, 1 - d_z )
  26161. ];
  26162. }
  26163. }
  26164. };
  26165. function toJSON$1( shapes, options, data ) {
  26166. data.shapes = [];
  26167. if ( Array.isArray( shapes ) ) {
  26168. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26169. const shape = shapes[ i ];
  26170. data.shapes.push( shape.uuid );
  26171. }
  26172. } else {
  26173. data.shapes.push( shapes.uuid );
  26174. }
  26175. data.options = Object.assign( {}, options );
  26176. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26177. return data;
  26178. }
  26179. /**
  26180. * A geometry class for representing an icosahedron.
  26181. *
  26182. * ```js
  26183. * const geometry = new THREE.IcosahedronGeometry();
  26184. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26185. * const icosahedron = new THREE.Mesh( geometry, material );
  26186. * scene.add( icosahedron );
  26187. * ```
  26188. *
  26189. * @augments PolyhedronGeometry
  26190. */
  26191. class IcosahedronGeometry extends PolyhedronGeometry {
  26192. /**
  26193. * Constructs a new icosahedron geometry.
  26194. *
  26195. * @param {number} [radius=1] - Radius of the icosahedron.
  26196. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26197. */
  26198. constructor( radius = 1, detail = 0 ) {
  26199. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26200. const vertices = [
  26201. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26202. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26203. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26204. ];
  26205. const indices = [
  26206. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26207. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26208. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26209. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26210. ];
  26211. super( vertices, indices, radius, detail );
  26212. this.type = 'IcosahedronGeometry';
  26213. /**
  26214. * Holds the constructor parameters that have been
  26215. * used to generate the geometry. Any modification
  26216. * after instantiation does not change the geometry.
  26217. *
  26218. * @type {Object}
  26219. */
  26220. this.parameters = {
  26221. radius: radius,
  26222. detail: detail
  26223. };
  26224. }
  26225. /**
  26226. * Factory method for creating an instance of this class from the given
  26227. * JSON object.
  26228. *
  26229. * @param {Object} data - A JSON object representing the serialized geometry.
  26230. * @return {IcosahedronGeometry} A new instance.
  26231. */
  26232. static fromJSON( data ) {
  26233. return new IcosahedronGeometry( data.radius, data.detail );
  26234. }
  26235. }
  26236. /**
  26237. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26238. *
  26239. * ```js
  26240. * const points = [];
  26241. * for ( let i = 0; i < 10; i ++ ) {
  26242. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26243. * }
  26244. * const geometry = new THREE.LatheGeometry( points );
  26245. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26246. * const lathe = new THREE.Mesh( geometry, material );
  26247. * scene.add( lathe );
  26248. * ```
  26249. *
  26250. * @augments BufferGeometry
  26251. */
  26252. class LatheGeometry extends BufferGeometry {
  26253. /**
  26254. * Constructs a new lathe geometry.
  26255. *
  26256. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26257. * must be greater than zero.
  26258. * @param {number} [segments=12] - The number of circumference segments to generate.
  26259. * @param {number} [phiStart=0] - The starting angle in radians.
  26260. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26261. * closed lathe, less than 2PI is a portion.
  26262. */
  26263. 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 ) {
  26264. super();
  26265. this.type = 'LatheGeometry';
  26266. /**
  26267. * Holds the constructor parameters that have been
  26268. * used to generate the geometry. Any modification
  26269. * after instantiation does not change the geometry.
  26270. *
  26271. * @type {Object}
  26272. */
  26273. this.parameters = {
  26274. points: points,
  26275. segments: segments,
  26276. phiStart: phiStart,
  26277. phiLength: phiLength
  26278. };
  26279. segments = Math.floor( segments );
  26280. // clamp phiLength so it's in range of [ 0, 2PI ]
  26281. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26282. // buffers
  26283. const indices = [];
  26284. const vertices = [];
  26285. const uvs = [];
  26286. const initNormals = [];
  26287. const normals = [];
  26288. // helper variables
  26289. const inverseSegments = 1.0 / segments;
  26290. const vertex = new Vector3();
  26291. const uv = new Vector2();
  26292. const normal = new Vector3();
  26293. const curNormal = new Vector3();
  26294. const prevNormal = new Vector3();
  26295. let dx = 0;
  26296. let dy = 0;
  26297. // pre-compute normals for initial "meridian"
  26298. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26299. switch ( j ) {
  26300. case 0: // special handling for 1st vertex on path
  26301. dx = points[ j + 1 ].x - points[ j ].x;
  26302. dy = points[ j + 1 ].y - points[ j ].y;
  26303. normal.x = dy * 1.0;
  26304. normal.y = - dx;
  26305. normal.z = dy * 0.0;
  26306. prevNormal.copy( normal );
  26307. normal.normalize();
  26308. initNormals.push( normal.x, normal.y, normal.z );
  26309. break;
  26310. case ( points.length - 1 ): // special handling for last Vertex on path
  26311. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26312. break;
  26313. default: // default handling for all vertices in between
  26314. dx = points[ j + 1 ].x - points[ j ].x;
  26315. dy = points[ j + 1 ].y - points[ j ].y;
  26316. normal.x = dy * 1.0;
  26317. normal.y = - dx;
  26318. normal.z = dy * 0.0;
  26319. curNormal.copy( normal );
  26320. normal.x += prevNormal.x;
  26321. normal.y += prevNormal.y;
  26322. normal.z += prevNormal.z;
  26323. normal.normalize();
  26324. initNormals.push( normal.x, normal.y, normal.z );
  26325. prevNormal.copy( curNormal );
  26326. }
  26327. }
  26328. // generate vertices, uvs and normals
  26329. for ( let i = 0; i <= segments; i ++ ) {
  26330. const phi = phiStart + i * inverseSegments * phiLength;
  26331. const sin = Math.sin( phi );
  26332. const cos = Math.cos( phi );
  26333. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26334. // vertex
  26335. vertex.x = points[ j ].x * sin;
  26336. vertex.y = points[ j ].y;
  26337. vertex.z = points[ j ].x * cos;
  26338. vertices.push( vertex.x, vertex.y, vertex.z );
  26339. // uv
  26340. uv.x = i / segments;
  26341. uv.y = j / ( points.length - 1 );
  26342. uvs.push( uv.x, uv.y );
  26343. // normal
  26344. const x = initNormals[ 3 * j + 0 ] * sin;
  26345. const y = initNormals[ 3 * j + 1 ];
  26346. const z = initNormals[ 3 * j + 0 ] * cos;
  26347. normals.push( x, y, z );
  26348. }
  26349. }
  26350. // indices
  26351. for ( let i = 0; i < segments; i ++ ) {
  26352. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26353. const base = j + i * points.length;
  26354. const a = base;
  26355. const b = base + points.length;
  26356. const c = base + points.length + 1;
  26357. const d = base + 1;
  26358. // faces
  26359. indices.push( a, b, d );
  26360. indices.push( c, d, b );
  26361. }
  26362. }
  26363. // build geometry
  26364. this.setIndex( indices );
  26365. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26366. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26367. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26368. }
  26369. copy( source ) {
  26370. super.copy( source );
  26371. this.parameters = Object.assign( {}, source.parameters );
  26372. return this;
  26373. }
  26374. /**
  26375. * Factory method for creating an instance of this class from the given
  26376. * JSON object.
  26377. *
  26378. * @param {Object} data - A JSON object representing the serialized geometry.
  26379. * @return {LatheGeometry} A new instance.
  26380. */
  26381. static fromJSON( data ) {
  26382. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26383. }
  26384. }
  26385. /**
  26386. * A geometry class for representing an octahedron.
  26387. *
  26388. * ```js
  26389. * const geometry = new THREE.OctahedronGeometry();
  26390. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26391. * const octahedron = new THREE.Mesh( geometry, material );
  26392. * scene.add( octahedron );
  26393. * ```
  26394. *
  26395. * @augments PolyhedronGeometry
  26396. */
  26397. class OctahedronGeometry extends PolyhedronGeometry {
  26398. /**
  26399. * Constructs a new octahedron geometry.
  26400. *
  26401. * @param {number} [radius=1] - Radius of the octahedron.
  26402. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26403. */
  26404. constructor( radius = 1, detail = 0 ) {
  26405. const vertices = [
  26406. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26407. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26408. ];
  26409. const indices = [
  26410. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26411. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26412. 1, 3, 4, 1, 4, 2
  26413. ];
  26414. super( vertices, indices, radius, detail );
  26415. this.type = 'OctahedronGeometry';
  26416. /**
  26417. * Holds the constructor parameters that have been
  26418. * used to generate the geometry. Any modification
  26419. * after instantiation does not change the geometry.
  26420. *
  26421. * @type {Object}
  26422. */
  26423. this.parameters = {
  26424. radius: radius,
  26425. detail: detail
  26426. };
  26427. }
  26428. /**
  26429. * Factory method for creating an instance of this class from the given
  26430. * JSON object.
  26431. *
  26432. * @param {Object} data - A JSON object representing the serialized geometry.
  26433. * @return {OctahedronGeometry} A new instance.
  26434. */
  26435. static fromJSON( data ) {
  26436. return new OctahedronGeometry( data.radius, data.detail );
  26437. }
  26438. }
  26439. /**
  26440. * A geometry class for representing a plane.
  26441. *
  26442. * ```js
  26443. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26444. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26445. * const plane = new THREE.Mesh( geometry, material );
  26446. * scene.add( plane );
  26447. * ```
  26448. *
  26449. * @augments BufferGeometry
  26450. */
  26451. class PlaneGeometry extends BufferGeometry {
  26452. /**
  26453. * Constructs a new plane geometry.
  26454. *
  26455. * @param {number} [width=1] - The width along the X axis.
  26456. * @param {number} [height=1] - The height along the Y axis
  26457. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26458. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26459. */
  26460. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26461. super();
  26462. this.type = 'PlaneGeometry';
  26463. /**
  26464. * Holds the constructor parameters that have been
  26465. * used to generate the geometry. Any modification
  26466. * after instantiation does not change the geometry.
  26467. *
  26468. * @type {Object}
  26469. */
  26470. this.parameters = {
  26471. width: width,
  26472. height: height,
  26473. widthSegments: widthSegments,
  26474. heightSegments: heightSegments
  26475. };
  26476. const width_half = width / 2;
  26477. const height_half = height / 2;
  26478. const gridX = Math.floor( widthSegments );
  26479. const gridY = Math.floor( heightSegments );
  26480. const gridX1 = gridX + 1;
  26481. const gridY1 = gridY + 1;
  26482. const segment_width = width / gridX;
  26483. const segment_height = height / gridY;
  26484. //
  26485. const indices = [];
  26486. const vertices = [];
  26487. const normals = [];
  26488. const uvs = [];
  26489. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26490. const y = iy * segment_height - height_half;
  26491. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26492. const x = ix * segment_width - width_half;
  26493. vertices.push( x, - y, 0 );
  26494. normals.push( 0, 0, 1 );
  26495. uvs.push( ix / gridX );
  26496. uvs.push( 1 - ( iy / gridY ) );
  26497. }
  26498. }
  26499. for ( let iy = 0; iy < gridY; iy ++ ) {
  26500. for ( let ix = 0; ix < gridX; ix ++ ) {
  26501. const a = ix + gridX1 * iy;
  26502. const b = ix + gridX1 * ( iy + 1 );
  26503. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26504. const d = ( ix + 1 ) + gridX1 * iy;
  26505. indices.push( a, b, d );
  26506. indices.push( b, c, d );
  26507. }
  26508. }
  26509. this.setIndex( indices );
  26510. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26511. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26512. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26513. }
  26514. copy( source ) {
  26515. super.copy( source );
  26516. this.parameters = Object.assign( {}, source.parameters );
  26517. return this;
  26518. }
  26519. /**
  26520. * Factory method for creating an instance of this class from the given
  26521. * JSON object.
  26522. *
  26523. * @param {Object} data - A JSON object representing the serialized geometry.
  26524. * @return {PlaneGeometry} A new instance.
  26525. */
  26526. static fromJSON( data ) {
  26527. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26528. }
  26529. }
  26530. /**
  26531. * A class for generating a two-dimensional ring geometry.
  26532. *
  26533. * ```js
  26534. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26535. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26536. * const mesh = new THREE.Mesh( geometry, material );
  26537. * scene.add( mesh );
  26538. * ```
  26539. *
  26540. * @augments BufferGeometry
  26541. */
  26542. class RingGeometry extends BufferGeometry {
  26543. /**
  26544. * Constructs a new ring geometry.
  26545. *
  26546. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26547. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26548. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26549. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26550. * @param {number} [thetaStart=0] - Starting angle in radians.
  26551. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26552. */
  26553. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26554. super();
  26555. this.type = 'RingGeometry';
  26556. /**
  26557. * Holds the constructor parameters that have been
  26558. * used to generate the geometry. Any modification
  26559. * after instantiation does not change the geometry.
  26560. *
  26561. * @type {Object}
  26562. */
  26563. this.parameters = {
  26564. innerRadius: innerRadius,
  26565. outerRadius: outerRadius,
  26566. thetaSegments: thetaSegments,
  26567. phiSegments: phiSegments,
  26568. thetaStart: thetaStart,
  26569. thetaLength: thetaLength
  26570. };
  26571. thetaSegments = Math.max( 3, thetaSegments );
  26572. phiSegments = Math.max( 1, phiSegments );
  26573. // buffers
  26574. const indices = [];
  26575. const vertices = [];
  26576. const normals = [];
  26577. const uvs = [];
  26578. // some helper variables
  26579. let radius = innerRadius;
  26580. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26581. const vertex = new Vector3();
  26582. const uv = new Vector2();
  26583. // generate vertices, normals and uvs
  26584. for ( let j = 0; j <= phiSegments; j ++ ) {
  26585. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26586. // values are generate from the inside of the ring to the outside
  26587. const segment = thetaStart + i / thetaSegments * thetaLength;
  26588. // vertex
  26589. vertex.x = radius * Math.cos( segment );
  26590. vertex.y = radius * Math.sin( segment );
  26591. vertices.push( vertex.x, vertex.y, vertex.z );
  26592. // normal
  26593. normals.push( 0, 0, 1 );
  26594. // uv
  26595. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26596. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26597. uvs.push( uv.x, uv.y );
  26598. }
  26599. // increase the radius for next row of vertices
  26600. radius += radiusStep;
  26601. }
  26602. // indices
  26603. for ( let j = 0; j < phiSegments; j ++ ) {
  26604. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26605. for ( let i = 0; i < thetaSegments; i ++ ) {
  26606. const segment = i + thetaSegmentLevel;
  26607. const a = segment;
  26608. const b = segment + thetaSegments + 1;
  26609. const c = segment + thetaSegments + 2;
  26610. const d = segment + 1;
  26611. // faces
  26612. indices.push( a, b, d );
  26613. indices.push( b, c, d );
  26614. }
  26615. }
  26616. // build geometry
  26617. this.setIndex( indices );
  26618. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26619. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26620. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26621. }
  26622. copy( source ) {
  26623. super.copy( source );
  26624. this.parameters = Object.assign( {}, source.parameters );
  26625. return this;
  26626. }
  26627. /**
  26628. * Factory method for creating an instance of this class from the given
  26629. * JSON object.
  26630. *
  26631. * @param {Object} data - A JSON object representing the serialized geometry.
  26632. * @return {RingGeometry} A new instance.
  26633. */
  26634. static fromJSON( data ) {
  26635. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26636. }
  26637. }
  26638. /**
  26639. * Creates an one-sided polygonal geometry from one or more path shapes.
  26640. *
  26641. * ```js
  26642. * const arcShape = new THREE.Shape()
  26643. * .moveTo( 5, 1 )
  26644. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26645. *
  26646. * const geometry = new THREE.ShapeGeometry( arcShape );
  26647. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26648. * const mesh = new THREE.Mesh( geometry, material ) ;
  26649. * scene.add( mesh );
  26650. * ```
  26651. *
  26652. * @augments BufferGeometry
  26653. */
  26654. class ShapeGeometry extends BufferGeometry {
  26655. /**
  26656. * Constructs a new shape geometry.
  26657. *
  26658. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26659. * @param {number} [curveSegments=12] - Number of segments per shape.
  26660. */
  26661. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26662. super();
  26663. this.type = 'ShapeGeometry';
  26664. /**
  26665. * Holds the constructor parameters that have been
  26666. * used to generate the geometry. Any modification
  26667. * after instantiation does not change the geometry.
  26668. *
  26669. * @type {Object}
  26670. */
  26671. this.parameters = {
  26672. shapes: shapes,
  26673. curveSegments: curveSegments
  26674. };
  26675. // buffers
  26676. const indices = [];
  26677. const vertices = [];
  26678. const normals = [];
  26679. const uvs = [];
  26680. // helper variables
  26681. let groupStart = 0;
  26682. let groupCount = 0;
  26683. // allow single and array values for "shapes" parameter
  26684. if ( Array.isArray( shapes ) === false ) {
  26685. addShape( shapes );
  26686. } else {
  26687. for ( let i = 0; i < shapes.length; i ++ ) {
  26688. addShape( shapes[ i ] );
  26689. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26690. groupStart += groupCount;
  26691. groupCount = 0;
  26692. }
  26693. }
  26694. // build geometry
  26695. this.setIndex( indices );
  26696. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26697. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26698. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26699. // helper functions
  26700. function addShape( shape ) {
  26701. const indexOffset = vertices.length / 3;
  26702. const points = shape.extractPoints( curveSegments );
  26703. let shapeVertices = points.shape;
  26704. const shapeHoles = points.holes;
  26705. // check direction of vertices
  26706. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26707. shapeVertices = shapeVertices.reverse();
  26708. }
  26709. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26710. const shapeHole = shapeHoles[ i ];
  26711. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26712. shapeHoles[ i ] = shapeHole.reverse();
  26713. }
  26714. }
  26715. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26716. // join vertices of inner and outer paths to a single array
  26717. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26718. const shapeHole = shapeHoles[ i ];
  26719. shapeVertices = shapeVertices.concat( shapeHole );
  26720. }
  26721. // vertices, normals, uvs
  26722. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26723. const vertex = shapeVertices[ i ];
  26724. vertices.push( vertex.x, vertex.y, 0 );
  26725. normals.push( 0, 0, 1 );
  26726. uvs.push( vertex.x, vertex.y ); // world uvs
  26727. }
  26728. // indices
  26729. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26730. const face = faces[ i ];
  26731. const a = face[ 0 ] + indexOffset;
  26732. const b = face[ 1 ] + indexOffset;
  26733. const c = face[ 2 ] + indexOffset;
  26734. indices.push( a, b, c );
  26735. groupCount += 3;
  26736. }
  26737. }
  26738. }
  26739. copy( source ) {
  26740. super.copy( source );
  26741. this.parameters = Object.assign( {}, source.parameters );
  26742. return this;
  26743. }
  26744. toJSON() {
  26745. const data = super.toJSON();
  26746. const shapes = this.parameters.shapes;
  26747. return toJSON( shapes, data );
  26748. }
  26749. /**
  26750. * Factory method for creating an instance of this class from the given
  26751. * JSON object.
  26752. *
  26753. * @param {Object} data - A JSON object representing the serialized geometry.
  26754. * @param {Array<Shape>} shapes - An array of shapes.
  26755. * @return {ShapeGeometry} A new instance.
  26756. */
  26757. static fromJSON( data, shapes ) {
  26758. const geometryShapes = [];
  26759. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26760. const shape = shapes[ data.shapes[ j ] ];
  26761. geometryShapes.push( shape );
  26762. }
  26763. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26764. }
  26765. }
  26766. function toJSON( shapes, data ) {
  26767. data.shapes = [];
  26768. if ( Array.isArray( shapes ) ) {
  26769. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26770. const shape = shapes[ i ];
  26771. data.shapes.push( shape.uuid );
  26772. }
  26773. } else {
  26774. data.shapes.push( shapes.uuid );
  26775. }
  26776. return data;
  26777. }
  26778. /**
  26779. * A class for generating a sphere geometry.
  26780. *
  26781. * ```js
  26782. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26783. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26784. * const sphere = new THREE.Mesh( geometry, material );
  26785. * scene.add( sphere );
  26786. * ```
  26787. *
  26788. * @augments BufferGeometry
  26789. */
  26790. class SphereGeometry extends BufferGeometry {
  26791. /**
  26792. * Constructs a new sphere geometry.
  26793. *
  26794. * @param {number} [radius=1] - The sphere radius.
  26795. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26796. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26797. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26798. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26799. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26800. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26801. */
  26802. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26803. super();
  26804. this.type = 'SphereGeometry';
  26805. /**
  26806. * Holds the constructor parameters that have been
  26807. * used to generate the geometry. Any modification
  26808. * after instantiation does not change the geometry.
  26809. *
  26810. * @type {Object}
  26811. */
  26812. this.parameters = {
  26813. radius: radius,
  26814. widthSegments: widthSegments,
  26815. heightSegments: heightSegments,
  26816. phiStart: phiStart,
  26817. phiLength: phiLength,
  26818. thetaStart: thetaStart,
  26819. thetaLength: thetaLength
  26820. };
  26821. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26822. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26823. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26824. let index = 0;
  26825. const grid = [];
  26826. const vertex = new Vector3();
  26827. const normal = new Vector3();
  26828. // buffers
  26829. const indices = [];
  26830. const vertices = [];
  26831. const normals = [];
  26832. const uvs = [];
  26833. // generate vertices, normals and uvs
  26834. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26835. const verticesRow = [];
  26836. const v = iy / heightSegments;
  26837. // special case for the poles
  26838. let uOffset = 0;
  26839. if ( iy === 0 && thetaStart === 0 ) {
  26840. uOffset = 0.5 / widthSegments;
  26841. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26842. uOffset = -0.5 / widthSegments;
  26843. }
  26844. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26845. const u = ix / widthSegments;
  26846. // vertex
  26847. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26848. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26849. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26850. vertices.push( vertex.x, vertex.y, vertex.z );
  26851. // normal
  26852. normal.copy( vertex ).normalize();
  26853. normals.push( normal.x, normal.y, normal.z );
  26854. // uv
  26855. uvs.push( u + uOffset, 1 - v );
  26856. verticesRow.push( index ++ );
  26857. }
  26858. grid.push( verticesRow );
  26859. }
  26860. // indices
  26861. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26862. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26863. const a = grid[ iy ][ ix + 1 ];
  26864. const b = grid[ iy ][ ix ];
  26865. const c = grid[ iy + 1 ][ ix ];
  26866. const d = grid[ iy + 1 ][ ix + 1 ];
  26867. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26868. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26869. }
  26870. }
  26871. // build geometry
  26872. this.setIndex( indices );
  26873. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26874. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26875. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26876. }
  26877. copy( source ) {
  26878. super.copy( source );
  26879. this.parameters = Object.assign( {}, source.parameters );
  26880. return this;
  26881. }
  26882. /**
  26883. * Factory method for creating an instance of this class from the given
  26884. * JSON object.
  26885. *
  26886. * @param {Object} data - A JSON object representing the serialized geometry.
  26887. * @return {SphereGeometry} A new instance.
  26888. */
  26889. static fromJSON( data ) {
  26890. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26891. }
  26892. }
  26893. /**
  26894. * A geometry class for representing an tetrahedron.
  26895. *
  26896. * ```js
  26897. * const geometry = new THREE.TetrahedronGeometry();
  26898. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26899. * const tetrahedron = new THREE.Mesh( geometry, material );
  26900. * scene.add( tetrahedron );
  26901. * ```
  26902. *
  26903. * @augments PolyhedronGeometry
  26904. */
  26905. class TetrahedronGeometry extends PolyhedronGeometry {
  26906. /**
  26907. * Constructs a new tetrahedron geometry.
  26908. *
  26909. * @param {number} [radius=1] - Radius of the tetrahedron.
  26910. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26911. */
  26912. constructor( radius = 1, detail = 0 ) {
  26913. const vertices = [
  26914. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26915. ];
  26916. const indices = [
  26917. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26918. ];
  26919. super( vertices, indices, radius, detail );
  26920. this.type = 'TetrahedronGeometry';
  26921. /**
  26922. * Holds the constructor parameters that have been
  26923. * used to generate the geometry. Any modification
  26924. * after instantiation does not change the geometry.
  26925. *
  26926. * @type {Object}
  26927. */
  26928. this.parameters = {
  26929. radius: radius,
  26930. detail: detail
  26931. };
  26932. }
  26933. /**
  26934. * Factory method for creating an instance of this class from the given
  26935. * JSON object.
  26936. *
  26937. * @param {Object} data - A JSON object representing the serialized geometry.
  26938. * @return {TetrahedronGeometry} A new instance.
  26939. */
  26940. static fromJSON( data ) {
  26941. return new TetrahedronGeometry( data.radius, data.detail );
  26942. }
  26943. }
  26944. /**
  26945. * A geometry class for representing an torus.
  26946. *
  26947. * ```js
  26948. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26949. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26950. * const torus = new THREE.Mesh( geometry, material );
  26951. * scene.add( torus );
  26952. * ```
  26953. *
  26954. * @augments BufferGeometry
  26955. */
  26956. class TorusGeometry extends BufferGeometry {
  26957. /**
  26958. * Constructs a new torus geometry.
  26959. *
  26960. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26961. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26962. * @param {number} [radialSegments=12] - The number of radial segments.
  26963. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26964. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26965. */
  26966. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26967. super();
  26968. this.type = 'TorusGeometry';
  26969. /**
  26970. * Holds the constructor parameters that have been
  26971. * used to generate the geometry. Any modification
  26972. * after instantiation does not change the geometry.
  26973. *
  26974. * @type {Object}
  26975. */
  26976. this.parameters = {
  26977. radius: radius,
  26978. tube: tube,
  26979. radialSegments: radialSegments,
  26980. tubularSegments: tubularSegments,
  26981. arc: arc
  26982. };
  26983. radialSegments = Math.floor( radialSegments );
  26984. tubularSegments = Math.floor( tubularSegments );
  26985. // buffers
  26986. const indices = [];
  26987. const vertices = [];
  26988. const normals = [];
  26989. const uvs = [];
  26990. // helper variables
  26991. const center = new Vector3();
  26992. const vertex = new Vector3();
  26993. const normal = new Vector3();
  26994. // generate vertices, normals and uvs
  26995. for ( let j = 0; j <= radialSegments; j ++ ) {
  26996. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26997. const u = i / tubularSegments * arc;
  26998. const v = j / radialSegments * Math.PI * 2;
  26999. // vertex
  27000. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27001. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27002. vertex.z = tube * Math.sin( v );
  27003. vertices.push( vertex.x, vertex.y, vertex.z );
  27004. // normal
  27005. center.x = radius * Math.cos( u );
  27006. center.y = radius * Math.sin( u );
  27007. normal.subVectors( vertex, center ).normalize();
  27008. normals.push( normal.x, normal.y, normal.z );
  27009. // uv
  27010. uvs.push( i / tubularSegments );
  27011. uvs.push( j / radialSegments );
  27012. }
  27013. }
  27014. // generate indices
  27015. for ( let j = 1; j <= radialSegments; j ++ ) {
  27016. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27017. // indices
  27018. const a = ( tubularSegments + 1 ) * j + i - 1;
  27019. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27020. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27021. const d = ( tubularSegments + 1 ) * j + i;
  27022. // faces
  27023. indices.push( a, b, d );
  27024. indices.push( b, c, d );
  27025. }
  27026. }
  27027. // build geometry
  27028. this.setIndex( indices );
  27029. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27030. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27031. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27032. }
  27033. copy( source ) {
  27034. super.copy( source );
  27035. this.parameters = Object.assign( {}, source.parameters );
  27036. return this;
  27037. }
  27038. /**
  27039. * Factory method for creating an instance of this class from the given
  27040. * JSON object.
  27041. *
  27042. * @param {Object} data - A JSON object representing the serialized geometry.
  27043. * @return {TorusGeometry} A new instance.
  27044. */
  27045. static fromJSON( data ) {
  27046. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27047. }
  27048. }
  27049. /**
  27050. * Creates a torus knot, the particular shape of which is defined by a pair
  27051. * of coprime integers, p and q. If p and q are not coprime, the result will
  27052. * be a torus link.
  27053. *
  27054. * ```js
  27055. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27056. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27057. * const torusKnot = new THREE.Mesh( geometry, material );
  27058. * scene.add( torusKnot );
  27059. * ```
  27060. *
  27061. * @augments BufferGeometry
  27062. */
  27063. class TorusKnotGeometry extends BufferGeometry {
  27064. /**
  27065. * Constructs a new torus knot geometry.
  27066. *
  27067. * @param {number} [radius=1] - Radius of the torus knot.
  27068. * @param {number} [tube=0.4] - Radius of the tube.
  27069. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27070. * @param {number} [radialSegments=8] - The number of radial segments.
  27071. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27072. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27073. */
  27074. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27075. super();
  27076. this.type = 'TorusKnotGeometry';
  27077. /**
  27078. * Holds the constructor parameters that have been
  27079. * used to generate the geometry. Any modification
  27080. * after instantiation does not change the geometry.
  27081. *
  27082. * @type {Object}
  27083. */
  27084. this.parameters = {
  27085. radius: radius,
  27086. tube: tube,
  27087. tubularSegments: tubularSegments,
  27088. radialSegments: radialSegments,
  27089. p: p,
  27090. q: q
  27091. };
  27092. tubularSegments = Math.floor( tubularSegments );
  27093. radialSegments = Math.floor( radialSegments );
  27094. // buffers
  27095. const indices = [];
  27096. const vertices = [];
  27097. const normals = [];
  27098. const uvs = [];
  27099. // helper variables
  27100. const vertex = new Vector3();
  27101. const normal = new Vector3();
  27102. const P1 = new Vector3();
  27103. const P2 = new Vector3();
  27104. const B = new Vector3();
  27105. const T = new Vector3();
  27106. const N = new Vector3();
  27107. // generate vertices, normals and uvs
  27108. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27109. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27110. const u = i / tubularSegments * p * Math.PI * 2;
  27111. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27112. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27113. calculatePositionOnCurve( u, p, q, radius, P1 );
  27114. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27115. // calculate orthonormal basis
  27116. T.subVectors( P2, P1 );
  27117. N.addVectors( P2, P1 );
  27118. B.crossVectors( T, N );
  27119. N.crossVectors( B, T );
  27120. // normalize B, N. T can be ignored, we don't use it
  27121. B.normalize();
  27122. N.normalize();
  27123. for ( let j = 0; j <= radialSegments; ++ j ) {
  27124. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27125. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27126. const v = j / radialSegments * Math.PI * 2;
  27127. const cx = - tube * Math.cos( v );
  27128. const cy = tube * Math.sin( v );
  27129. // now calculate the final vertex position.
  27130. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27131. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27132. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27133. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27134. vertices.push( vertex.x, vertex.y, vertex.z );
  27135. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27136. normal.subVectors( vertex, P1 ).normalize();
  27137. normals.push( normal.x, normal.y, normal.z );
  27138. // uv
  27139. uvs.push( i / tubularSegments );
  27140. uvs.push( j / radialSegments );
  27141. }
  27142. }
  27143. // generate indices
  27144. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27145. for ( let i = 1; i <= radialSegments; i ++ ) {
  27146. // indices
  27147. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27148. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27149. const c = ( radialSegments + 1 ) * j + i;
  27150. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27151. // faces
  27152. indices.push( a, b, d );
  27153. indices.push( b, c, d );
  27154. }
  27155. }
  27156. // build geometry
  27157. this.setIndex( indices );
  27158. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27159. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27160. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27161. // this function calculates the current position on the torus curve
  27162. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27163. const cu = Math.cos( u );
  27164. const su = Math.sin( u );
  27165. const quOverP = q / p * u;
  27166. const cs = Math.cos( quOverP );
  27167. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27168. position.y = radius * ( 2 + cs ) * su * 0.5;
  27169. position.z = radius * Math.sin( quOverP ) * 0.5;
  27170. }
  27171. }
  27172. copy( source ) {
  27173. super.copy( source );
  27174. this.parameters = Object.assign( {}, source.parameters );
  27175. return this;
  27176. }
  27177. /**
  27178. * Factory method for creating an instance of this class from the given
  27179. * JSON object.
  27180. *
  27181. * @param {Object} data - A JSON object representing the serialized geometry.
  27182. * @return {TorusKnotGeometry} A new instance.
  27183. */
  27184. static fromJSON( data ) {
  27185. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27186. }
  27187. }
  27188. /**
  27189. * Creates a tube that extrudes along a 3D curve.
  27190. *
  27191. * ```js
  27192. * class CustomSinCurve extends THREE.Curve {
  27193. *
  27194. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27195. *
  27196. * const tx = t * 3 - 1.5;
  27197. * const ty = Math.sin( 2 * Math.PI * t );
  27198. * const tz = 0;
  27199. *
  27200. * return optionalTarget.set( tx, ty, tz );
  27201. * }
  27202. *
  27203. * }
  27204. *
  27205. * const path = new CustomSinCurve( 10 );
  27206. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27207. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27208. * const mesh = new THREE.Mesh( geometry, material );
  27209. * scene.add( mesh );
  27210. * ```
  27211. *
  27212. * @augments BufferGeometry
  27213. */
  27214. class TubeGeometry extends BufferGeometry {
  27215. /**
  27216. * Constructs a new tube geometry.
  27217. *
  27218. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27219. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27220. * @param {number} [radius=1] -The radius of the tube.
  27221. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27222. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27223. */
  27224. 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 ) {
  27225. super();
  27226. this.type = 'TubeGeometry';
  27227. /**
  27228. * Holds the constructor parameters that have been
  27229. * used to generate the geometry. Any modification
  27230. * after instantiation does not change the geometry.
  27231. *
  27232. * @type {Object}
  27233. */
  27234. this.parameters = {
  27235. path: path,
  27236. tubularSegments: tubularSegments,
  27237. radius: radius,
  27238. radialSegments: radialSegments,
  27239. closed: closed
  27240. };
  27241. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27242. // expose internals
  27243. this.tangents = frames.tangents;
  27244. this.normals = frames.normals;
  27245. this.binormals = frames.binormals;
  27246. // helper variables
  27247. const vertex = new Vector3();
  27248. const normal = new Vector3();
  27249. const uv = new Vector2();
  27250. let P = new Vector3();
  27251. // buffer
  27252. const vertices = [];
  27253. const normals = [];
  27254. const uvs = [];
  27255. const indices = [];
  27256. // create buffer data
  27257. generateBufferData();
  27258. // build geometry
  27259. this.setIndex( indices );
  27260. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27261. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27262. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27263. // functions
  27264. function generateBufferData() {
  27265. for ( let i = 0; i < tubularSegments; i ++ ) {
  27266. generateSegment( i );
  27267. }
  27268. // if the geometry is not closed, generate the last row of vertices and normals
  27269. // at the regular position on the given path
  27270. //
  27271. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27272. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27273. // uvs are generated in a separate function.
  27274. // this makes it easy compute correct values for closed geometries
  27275. generateUVs();
  27276. // finally create faces
  27277. generateIndices();
  27278. }
  27279. function generateSegment( i ) {
  27280. // we use getPointAt to sample evenly distributed points from the given path
  27281. P = path.getPointAt( i / tubularSegments, P );
  27282. // retrieve corresponding normal and binormal
  27283. const N = frames.normals[ i ];
  27284. const B = frames.binormals[ i ];
  27285. // generate normals and vertices for the current segment
  27286. for ( let j = 0; j <= radialSegments; j ++ ) {
  27287. const v = j / radialSegments * Math.PI * 2;
  27288. const sin = Math.sin( v );
  27289. const cos = - Math.cos( v );
  27290. // normal
  27291. normal.x = ( cos * N.x + sin * B.x );
  27292. normal.y = ( cos * N.y + sin * B.y );
  27293. normal.z = ( cos * N.z + sin * B.z );
  27294. normal.normalize();
  27295. normals.push( normal.x, normal.y, normal.z );
  27296. // vertex
  27297. vertex.x = P.x + radius * normal.x;
  27298. vertex.y = P.y + radius * normal.y;
  27299. vertex.z = P.z + radius * normal.z;
  27300. vertices.push( vertex.x, vertex.y, vertex.z );
  27301. }
  27302. }
  27303. function generateIndices() {
  27304. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27305. for ( let i = 1; i <= radialSegments; i ++ ) {
  27306. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27307. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27308. const c = ( radialSegments + 1 ) * j + i;
  27309. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27310. // faces
  27311. indices.push( a, b, d );
  27312. indices.push( b, c, d );
  27313. }
  27314. }
  27315. }
  27316. function generateUVs() {
  27317. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27318. for ( let j = 0; j <= radialSegments; j ++ ) {
  27319. uv.x = i / tubularSegments;
  27320. uv.y = j / radialSegments;
  27321. uvs.push( uv.x, uv.y );
  27322. }
  27323. }
  27324. }
  27325. }
  27326. copy( source ) {
  27327. super.copy( source );
  27328. this.parameters = Object.assign( {}, source.parameters );
  27329. return this;
  27330. }
  27331. toJSON() {
  27332. const data = super.toJSON();
  27333. data.path = this.parameters.path.toJSON();
  27334. return data;
  27335. }
  27336. /**
  27337. * Factory method for creating an instance of this class from the given
  27338. * JSON object.
  27339. *
  27340. * @param {Object} data - A JSON object representing the serialized geometry.
  27341. * @return {TubeGeometry} A new instance.
  27342. */
  27343. static fromJSON( data ) {
  27344. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27345. // User defined curves or instances of CurvePath will not be deserialized.
  27346. return new TubeGeometry(
  27347. new Curves[ data.path.type ]().fromJSON( data.path ),
  27348. data.tubularSegments,
  27349. data.radius,
  27350. data.radialSegments,
  27351. data.closed
  27352. );
  27353. }
  27354. }
  27355. /**
  27356. * Can be used as a helper object to visualize a geometry as a wireframe.
  27357. *
  27358. * ```js
  27359. * const geometry = new THREE.SphereGeometry();
  27360. *
  27361. * const wireframe = new THREE.WireframeGeometry( geometry );
  27362. *
  27363. * const line = new THREE.LineSegments( wireframe );
  27364. * line.material.depthWrite = false;
  27365. * line.material.opacity = 0.25;
  27366. * line.material.transparent = true;
  27367. *
  27368. * scene.add( line );
  27369. * ```
  27370. *
  27371. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27372. *
  27373. * @augments BufferGeometry
  27374. */
  27375. class WireframeGeometry extends BufferGeometry {
  27376. /**
  27377. * Constructs a new wireframe geometry.
  27378. *
  27379. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27380. */
  27381. constructor( geometry = null ) {
  27382. super();
  27383. this.type = 'WireframeGeometry';
  27384. /**
  27385. * Holds the constructor parameters that have been
  27386. * used to generate the geometry. Any modification
  27387. * after instantiation does not change the geometry.
  27388. *
  27389. * @type {Object}
  27390. */
  27391. this.parameters = {
  27392. geometry: geometry
  27393. };
  27394. if ( geometry !== null ) {
  27395. // buffer
  27396. const vertices = [];
  27397. const edges = new Set();
  27398. // helper variables
  27399. const start = new Vector3();
  27400. const end = new Vector3();
  27401. if ( geometry.index !== null ) {
  27402. // indexed BufferGeometry
  27403. const position = geometry.attributes.position;
  27404. const indices = geometry.index;
  27405. let groups = geometry.groups;
  27406. if ( groups.length === 0 ) {
  27407. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27408. }
  27409. // create a data structure that contains all edges without duplicates
  27410. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27411. const group = groups[ o ];
  27412. const groupStart = group.start;
  27413. const groupCount = group.count;
  27414. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27415. for ( let j = 0; j < 3; j ++ ) {
  27416. const index1 = indices.getX( i + j );
  27417. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27418. start.fromBufferAttribute( position, index1 );
  27419. end.fromBufferAttribute( position, index2 );
  27420. if ( isUniqueEdge( start, end, edges ) === true ) {
  27421. vertices.push( start.x, start.y, start.z );
  27422. vertices.push( end.x, end.y, end.z );
  27423. }
  27424. }
  27425. }
  27426. }
  27427. } else {
  27428. // non-indexed BufferGeometry
  27429. const position = geometry.attributes.position;
  27430. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27431. for ( let j = 0; j < 3; j ++ ) {
  27432. // three edges per triangle, an edge is represented as (index1, index2)
  27433. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27434. const index1 = 3 * i + j;
  27435. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27436. start.fromBufferAttribute( position, index1 );
  27437. end.fromBufferAttribute( position, index2 );
  27438. if ( isUniqueEdge( start, end, edges ) === true ) {
  27439. vertices.push( start.x, start.y, start.z );
  27440. vertices.push( end.x, end.y, end.z );
  27441. }
  27442. }
  27443. }
  27444. }
  27445. // build geometry
  27446. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27447. }
  27448. }
  27449. copy( source ) {
  27450. super.copy( source );
  27451. this.parameters = Object.assign( {}, source.parameters );
  27452. return this;
  27453. }
  27454. }
  27455. function isUniqueEdge( start, end, edges ) {
  27456. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27457. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27458. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27459. return false;
  27460. } else {
  27461. edges.add( hash1 );
  27462. edges.add( hash2 );
  27463. return true;
  27464. }
  27465. }
  27466. var Geometries = /*#__PURE__*/Object.freeze({
  27467. __proto__: null,
  27468. BoxGeometry: BoxGeometry,
  27469. CapsuleGeometry: CapsuleGeometry,
  27470. CircleGeometry: CircleGeometry,
  27471. ConeGeometry: ConeGeometry,
  27472. CylinderGeometry: CylinderGeometry,
  27473. DodecahedronGeometry: DodecahedronGeometry,
  27474. EdgesGeometry: EdgesGeometry,
  27475. ExtrudeGeometry: ExtrudeGeometry,
  27476. IcosahedronGeometry: IcosahedronGeometry,
  27477. LatheGeometry: LatheGeometry,
  27478. OctahedronGeometry: OctahedronGeometry,
  27479. PlaneGeometry: PlaneGeometry,
  27480. PolyhedronGeometry: PolyhedronGeometry,
  27481. RingGeometry: RingGeometry,
  27482. ShapeGeometry: ShapeGeometry,
  27483. SphereGeometry: SphereGeometry,
  27484. TetrahedronGeometry: TetrahedronGeometry,
  27485. TorusGeometry: TorusGeometry,
  27486. TorusKnotGeometry: TorusKnotGeometry,
  27487. TubeGeometry: TubeGeometry,
  27488. WireframeGeometry: WireframeGeometry
  27489. });
  27490. /**
  27491. * This material can receive shadows, but otherwise is completely transparent.
  27492. *
  27493. * ```js
  27494. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27495. * geometry.rotateX( - Math.PI / 2 );
  27496. *
  27497. * const material = new THREE.ShadowMaterial();
  27498. * material.opacity = 0.2;
  27499. *
  27500. * const plane = new THREE.Mesh( geometry, material );
  27501. * plane.position.y = -200;
  27502. * plane.receiveShadow = true;
  27503. * scene.add( plane );
  27504. * ```
  27505. *
  27506. * @augments Material
  27507. */
  27508. class ShadowMaterial extends Material {
  27509. /**
  27510. * Constructs a new shadow material.
  27511. *
  27512. * @param {Object} [parameters] - An object with one or more properties
  27513. * defining the material's appearance. Any property of the material
  27514. * (including any property from inherited materials) can be passed
  27515. * in here. Color values can be passed any type of value accepted
  27516. * by {@link Color#set}.
  27517. */
  27518. constructor( parameters ) {
  27519. super();
  27520. /**
  27521. * This flag can be used for type testing.
  27522. *
  27523. * @type {boolean}
  27524. * @readonly
  27525. * @default true
  27526. */
  27527. this.isShadowMaterial = true;
  27528. this.type = 'ShadowMaterial';
  27529. /**
  27530. * Color of the material.
  27531. *
  27532. * @type {Color}
  27533. * @default (0,0,0)
  27534. */
  27535. this.color = new Color( 0x000000 );
  27536. /**
  27537. * Overwritten since shadow materials are transparent
  27538. * by default.
  27539. *
  27540. * @type {boolean}
  27541. * @default true
  27542. */
  27543. this.transparent = true;
  27544. /**
  27545. * Whether the material is affected by fog or not.
  27546. *
  27547. * @type {boolean}
  27548. * @default true
  27549. */
  27550. this.fog = true;
  27551. this.setValues( parameters );
  27552. }
  27553. copy( source ) {
  27554. super.copy( source );
  27555. this.color.copy( source.color );
  27556. this.fog = source.fog;
  27557. return this;
  27558. }
  27559. }
  27560. /**
  27561. * This class works just like {@link ShaderMaterial}, except that definitions
  27562. * of built-in uniforms and attributes are not automatically prepended to the
  27563. * GLSL shader code.
  27564. *
  27565. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27566. *
  27567. * @augments ShaderMaterial
  27568. */
  27569. class RawShaderMaterial extends ShaderMaterial {
  27570. /**
  27571. * Constructs a new raw shader material.
  27572. *
  27573. * @param {Object} [parameters] - An object with one or more properties
  27574. * defining the material's appearance. Any property of the material
  27575. * (including any property from inherited materials) can be passed
  27576. * in here. Color values can be passed any type of value accepted
  27577. * by {@link Color#set}.
  27578. */
  27579. constructor( parameters ) {
  27580. super( parameters );
  27581. /**
  27582. * This flag can be used for type testing.
  27583. *
  27584. * @type {boolean}
  27585. * @readonly
  27586. * @default true
  27587. */
  27588. this.isRawShaderMaterial = true;
  27589. this.type = 'RawShaderMaterial';
  27590. }
  27591. }
  27592. /**
  27593. * A standard physically based material, using Metallic-Roughness workflow.
  27594. *
  27595. * Physically based rendering (PBR) has recently become the standard in many
  27596. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27597. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27598. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27599. *
  27600. * This approach differs from older approaches in that instead of using
  27601. * approximations for the way in which light interacts with a surface, a
  27602. * physically correct model is used. The idea is that, instead of tweaking
  27603. * materials to look good under specific lighting, a material can be created
  27604. * that will react 'correctly' under all lighting scenarios.
  27605. *
  27606. * In practice this gives a more accurate and realistic looking result than
  27607. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27608. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27609. * shading.
  27610. *
  27611. * Note that for best results you should always specify an environment map when using this material.
  27612. *
  27613. * For a non-technical introduction to the concept of PBR and how to set up a
  27614. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27615. *
  27616. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27617. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27618. *
  27619. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27620. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27621. * (pdf), by Brent Burley.
  27622. *
  27623. * @augments Material
  27624. */
  27625. class MeshStandardMaterial extends Material {
  27626. /**
  27627. * Constructs a new mesh standard material.
  27628. *
  27629. * @param {Object} [parameters] - An object with one or more properties
  27630. * defining the material's appearance. Any property of the material
  27631. * (including any property from inherited materials) can be passed
  27632. * in here. Color values can be passed any type of value accepted
  27633. * by {@link Color#set}.
  27634. */
  27635. constructor( parameters ) {
  27636. super();
  27637. /**
  27638. * This flag can be used for type testing.
  27639. *
  27640. * @type {boolean}
  27641. * @readonly
  27642. * @default true
  27643. */
  27644. this.isMeshStandardMaterial = true;
  27645. this.type = 'MeshStandardMaterial';
  27646. this.defines = { 'STANDARD': '' };
  27647. /**
  27648. * Color of the material.
  27649. *
  27650. * @type {Color}
  27651. * @default (1,1,1)
  27652. */
  27653. this.color = new Color( 0xffffff ); // diffuse
  27654. /**
  27655. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27656. * means fully diffuse. If `roughnessMap` is also provided,
  27657. * both values are multiplied.
  27658. *
  27659. * @type {number}
  27660. * @default 1
  27661. */
  27662. this.roughness = 1.0;
  27663. /**
  27664. * How much the material is like a metal. Non-metallic materials such as wood
  27665. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27666. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27667. * If `metalnessMap` is also provided, both values are multiplied.
  27668. *
  27669. * @type {number}
  27670. * @default 0
  27671. */
  27672. this.metalness = 0.0;
  27673. /**
  27674. * The color map. May optionally include an alpha channel, typically combined
  27675. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27676. * color is modulated by the diffuse `color`.
  27677. *
  27678. * @type {?Texture}
  27679. * @default null
  27680. */
  27681. this.map = null;
  27682. /**
  27683. * The light map. Requires a second set of UVs.
  27684. *
  27685. * @type {?Texture}
  27686. * @default null
  27687. */
  27688. this.lightMap = null;
  27689. /**
  27690. * Intensity of the baked light.
  27691. *
  27692. * @type {number}
  27693. * @default 1
  27694. */
  27695. this.lightMapIntensity = 1.0;
  27696. /**
  27697. * The red channel of this texture is used as the ambient occlusion map.
  27698. * Requires a second set of UVs.
  27699. *
  27700. * @type {?Texture}
  27701. * @default null
  27702. */
  27703. this.aoMap = null;
  27704. /**
  27705. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27706. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27707. * red channel is also `1`, ambient light is fully occluded on a surface.
  27708. *
  27709. * @type {number}
  27710. * @default 1
  27711. */
  27712. this.aoMapIntensity = 1.0;
  27713. /**
  27714. * Emissive (light) color of the material, essentially a solid color
  27715. * unaffected by other lighting.
  27716. *
  27717. * @type {Color}
  27718. * @default (0,0,0)
  27719. */
  27720. this.emissive = new Color( 0x000000 );
  27721. /**
  27722. * Intensity of the emissive light. Modulates the emissive color.
  27723. *
  27724. * @type {number}
  27725. * @default 1
  27726. */
  27727. this.emissiveIntensity = 1.0;
  27728. /**
  27729. * Set emissive (glow) map. The emissive map color is modulated by the
  27730. * emissive color and the emissive intensity. If you have an emissive map,
  27731. * be sure to set the emissive color to something other than black.
  27732. *
  27733. * @type {?Texture}
  27734. * @default null
  27735. */
  27736. this.emissiveMap = null;
  27737. /**
  27738. * The texture to create a bump map. The black and white values map to the
  27739. * perceived depth in relation to the lights. Bump doesn't actually affect
  27740. * the geometry of the object, only the lighting. If a normal map is defined
  27741. * this will be ignored.
  27742. *
  27743. * @type {?Texture}
  27744. * @default null
  27745. */
  27746. this.bumpMap = null;
  27747. /**
  27748. * How much the bump map affects the material. Typical range is `[0,1]`.
  27749. *
  27750. * @type {number}
  27751. * @default 1
  27752. */
  27753. this.bumpScale = 1;
  27754. /**
  27755. * The texture to create a normal map. The RGB values affect the surface
  27756. * normal for each pixel fragment and change the way the color is lit. Normal
  27757. * maps do not change the actual shape of the surface, only the lighting. In
  27758. * case the material has a normal map authored using the left handed
  27759. * convention, the `y` component of `normalScale` should be negated to compensate
  27760. * for the different handedness.
  27761. *
  27762. * @type {?Texture}
  27763. * @default null
  27764. */
  27765. this.normalMap = null;
  27766. /**
  27767. * The type of normal map.
  27768. *
  27769. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27770. * @default TangentSpaceNormalMap
  27771. */
  27772. this.normalMapType = TangentSpaceNormalMap;
  27773. /**
  27774. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27775. *
  27776. * @type {Vector2}
  27777. * @default (1,1)
  27778. */
  27779. this.normalScale = new Vector2( 1, 1 );
  27780. /**
  27781. * The displacement map affects the position of the mesh's vertices. Unlike
  27782. * other maps which only affect the light and shade of the material the
  27783. * displaced vertices can cast shadows, block other objects, and otherwise
  27784. * act as real geometry. The displacement texture is an image where the value
  27785. * of each pixel (white being the highest) is mapped against, and
  27786. * repositions, the vertices of the mesh.
  27787. *
  27788. * @type {?Texture}
  27789. * @default null
  27790. */
  27791. this.displacementMap = null;
  27792. /**
  27793. * How much the displacement map affects the mesh (where black is no
  27794. * displacement, and white is maximum displacement). Without a displacement
  27795. * map set, this value is not applied.
  27796. *
  27797. * @type {number}
  27798. * @default 0
  27799. */
  27800. this.displacementScale = 1;
  27801. /**
  27802. * The offset of the displacement map's values on the mesh's vertices.
  27803. * The bias is added to the scaled sample of the displacement map.
  27804. * Without a displacement map set, this value is not applied.
  27805. *
  27806. * @type {number}
  27807. * @default 0
  27808. */
  27809. this.displacementBias = 0;
  27810. /**
  27811. * The green channel of this texture is used to alter the roughness of the
  27812. * material.
  27813. *
  27814. * @type {?Texture}
  27815. * @default null
  27816. */
  27817. this.roughnessMap = null;
  27818. /**
  27819. * The blue channel of this texture is used to alter the metalness of the
  27820. * material.
  27821. *
  27822. * @type {?Texture}
  27823. * @default null
  27824. */
  27825. this.metalnessMap = null;
  27826. /**
  27827. * The alpha map is a grayscale texture that controls the opacity across the
  27828. * surface (black: fully transparent; white: fully opaque).
  27829. *
  27830. * Only the color of the texture is used, ignoring the alpha channel if one
  27831. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27832. * when sampling this texture due to the extra bit of precision provided for
  27833. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27834. * luminance/alpha textures will also still work as expected.
  27835. *
  27836. * @type {?Texture}
  27837. * @default null
  27838. */
  27839. this.alphaMap = null;
  27840. /**
  27841. * The environment map. To ensure a physically correct rendering, environment maps
  27842. * are internally pre-processed with {@link PMREMGenerator}.
  27843. *
  27844. * @type {?Texture}
  27845. * @default null
  27846. */
  27847. this.envMap = null;
  27848. /**
  27849. * The rotation of the environment map in radians.
  27850. *
  27851. * @type {Euler}
  27852. * @default (0,0,0)
  27853. */
  27854. this.envMapRotation = new Euler();
  27855. /**
  27856. * Scales the effect of the environment map by multiplying its color.
  27857. *
  27858. * @type {number}
  27859. * @default 1
  27860. */
  27861. this.envMapIntensity = 1.0;
  27862. /**
  27863. * Renders the geometry as a wireframe.
  27864. *
  27865. * @type {boolean}
  27866. * @default false
  27867. */
  27868. this.wireframe = false;
  27869. /**
  27870. * Controls the thickness of the wireframe.
  27871. *
  27872. * Can only be used with {@link SVGRenderer}.
  27873. *
  27874. * @type {number}
  27875. * @default 1
  27876. */
  27877. this.wireframeLinewidth = 1;
  27878. /**
  27879. * Defines appearance of wireframe ends.
  27880. *
  27881. * Can only be used with {@link SVGRenderer}.
  27882. *
  27883. * @type {('round'|'bevel'|'miter')}
  27884. * @default 'round'
  27885. */
  27886. this.wireframeLinecap = 'round';
  27887. /**
  27888. * Defines appearance of wireframe joints.
  27889. *
  27890. * Can only be used with {@link SVGRenderer}.
  27891. *
  27892. * @type {('round'|'bevel'|'miter')}
  27893. * @default 'round'
  27894. */
  27895. this.wireframeLinejoin = 'round';
  27896. /**
  27897. * Whether the material is rendered with flat shading or not.
  27898. *
  27899. * @type {boolean}
  27900. * @default false
  27901. */
  27902. this.flatShading = false;
  27903. /**
  27904. * Whether the material is affected by fog or not.
  27905. *
  27906. * @type {boolean}
  27907. * @default true
  27908. */
  27909. this.fog = true;
  27910. this.setValues( parameters );
  27911. }
  27912. copy( source ) {
  27913. super.copy( source );
  27914. this.defines = { 'STANDARD': '' };
  27915. this.color.copy( source.color );
  27916. this.roughness = source.roughness;
  27917. this.metalness = source.metalness;
  27918. this.map = source.map;
  27919. this.lightMap = source.lightMap;
  27920. this.lightMapIntensity = source.lightMapIntensity;
  27921. this.aoMap = source.aoMap;
  27922. this.aoMapIntensity = source.aoMapIntensity;
  27923. this.emissive.copy( source.emissive );
  27924. this.emissiveMap = source.emissiveMap;
  27925. this.emissiveIntensity = source.emissiveIntensity;
  27926. this.bumpMap = source.bumpMap;
  27927. this.bumpScale = source.bumpScale;
  27928. this.normalMap = source.normalMap;
  27929. this.normalMapType = source.normalMapType;
  27930. this.normalScale.copy( source.normalScale );
  27931. this.displacementMap = source.displacementMap;
  27932. this.displacementScale = source.displacementScale;
  27933. this.displacementBias = source.displacementBias;
  27934. this.roughnessMap = source.roughnessMap;
  27935. this.metalnessMap = source.metalnessMap;
  27936. this.alphaMap = source.alphaMap;
  27937. this.envMap = source.envMap;
  27938. this.envMapRotation.copy( source.envMapRotation );
  27939. this.envMapIntensity = source.envMapIntensity;
  27940. this.wireframe = source.wireframe;
  27941. this.wireframeLinewidth = source.wireframeLinewidth;
  27942. this.wireframeLinecap = source.wireframeLinecap;
  27943. this.wireframeLinejoin = source.wireframeLinejoin;
  27944. this.flatShading = source.flatShading;
  27945. this.fog = source.fog;
  27946. return this;
  27947. }
  27948. }
  27949. /**
  27950. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27951. * physically-based rendering properties:
  27952. *
  27953. * - Anisotropy: Ability to represent the anisotropic property of materials
  27954. * as observable with brushed metals.
  27955. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27956. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27957. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27958. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27959. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27960. * wings of many insects.
  27961. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27962. * transparent materials are less reflective. Physically-based transmission provides a more
  27963. * realistic option for thin, transparent surfaces like glass.
  27964. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27965. * - Sheen: Can be used for representing cloth and fabric materials.
  27966. *
  27967. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27968. * higher performance cost, per pixel, than other three.js materials. Most
  27969. * effects are disabled by default, and add cost as they are enabled. For
  27970. * best results, always specify an environment map when using this material.
  27971. *
  27972. * @augments MeshStandardMaterial
  27973. */
  27974. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27975. /**
  27976. * Constructs a new mesh physical material.
  27977. *
  27978. * @param {Object} [parameters] - An object with one or more properties
  27979. * defining the material's appearance. Any property of the material
  27980. * (including any property from inherited materials) can be passed
  27981. * in here. Color values can be passed any type of value accepted
  27982. * by {@link Color#set}.
  27983. */
  27984. constructor( parameters ) {
  27985. super();
  27986. /**
  27987. * This flag can be used for type testing.
  27988. *
  27989. * @type {boolean}
  27990. * @readonly
  27991. * @default true
  27992. */
  27993. this.isMeshPhysicalMaterial = true;
  27994. this.defines = {
  27995. 'STANDARD': '',
  27996. 'PHYSICAL': ''
  27997. };
  27998. this.type = 'MeshPhysicalMaterial';
  27999. /**
  28000. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28001. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28002. * property provides additional rotation to the vectors in the texture.
  28003. *
  28004. * @type {number}
  28005. * @default 1
  28006. */
  28007. this.anisotropyRotation = 0;
  28008. /**
  28009. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28010. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28011. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28012. *
  28013. * @type {?Texture}
  28014. * @default null
  28015. */
  28016. this.anisotropyMap = null;
  28017. /**
  28018. * The red channel of this texture is multiplied against `clearcoat`,
  28019. * for per-pixel control over a coating's intensity.
  28020. *
  28021. * @type {?Texture}
  28022. * @default null
  28023. */
  28024. this.clearcoatMap = null;
  28025. /**
  28026. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28027. *
  28028. * @type {number}
  28029. * @default 0
  28030. */
  28031. this.clearcoatRoughness = 0.0;
  28032. /**
  28033. * The green channel of this texture is multiplied against
  28034. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28035. *
  28036. * @type {?Texture}
  28037. * @default null
  28038. */
  28039. this.clearcoatRoughnessMap = null;
  28040. /**
  28041. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28042. * `(0,0)` to `(1,1)`.
  28043. *
  28044. * @type {Vector2}
  28045. * @default (1,1)
  28046. */
  28047. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28048. /**
  28049. * Can be used to enable independent normals for the clear coat layer.
  28050. *
  28051. * @type {?Texture}
  28052. * @default null
  28053. */
  28054. this.clearcoatNormalMap = null;
  28055. /**
  28056. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28057. *
  28058. * @type {number}
  28059. * @default 1.5
  28060. */
  28061. this.ior = 1.5;
  28062. /**
  28063. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28064. * corresponds to an index-of-refraction of `1.5`.
  28065. *
  28066. * This models the reflectivity of non-metallic materials. It has no effect
  28067. * when `metalness` is `1.0`
  28068. *
  28069. * @name MeshPhysicalMaterial#reflectivity
  28070. * @type {number}
  28071. * @default 0.5
  28072. */
  28073. Object.defineProperty( this, 'reflectivity', {
  28074. get: function () {
  28075. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28076. },
  28077. set: function ( reflectivity ) {
  28078. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28079. }
  28080. } );
  28081. /**
  28082. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28083. * control over iridescence.
  28084. *
  28085. * @type {?Texture}
  28086. * @default null
  28087. */
  28088. this.iridescenceMap = null;
  28089. /**
  28090. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28091. * Between `1.0` to `2.333`.
  28092. *
  28093. * @type {number}
  28094. * @default 1.3
  28095. */
  28096. this.iridescenceIOR = 1.3;
  28097. /**
  28098. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28099. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28100. *
  28101. * @type {Array<number,number>}
  28102. * @default [100,400]
  28103. */
  28104. this.iridescenceThicknessRange = [ 100, 400 ];
  28105. /**
  28106. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28107. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28108. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28109. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28110. * - Values in-between will linearly interpolate between the elements of the array.
  28111. *
  28112. * @type {?Texture}
  28113. * @default null
  28114. */
  28115. this.iridescenceThicknessMap = null;
  28116. /**
  28117. * The sheen tint.
  28118. *
  28119. * @type {Color}
  28120. * @default (0,0,0)
  28121. */
  28122. this.sheenColor = new Color( 0x000000 );
  28123. /**
  28124. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28125. * over sheen tint.
  28126. *
  28127. * @type {?Texture}
  28128. * @default null
  28129. */
  28130. this.sheenColorMap = null;
  28131. /**
  28132. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28133. *
  28134. * @type {number}
  28135. * @default 1
  28136. */
  28137. this.sheenRoughness = 1.0;
  28138. /**
  28139. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28140. * over sheen roughness.
  28141. *
  28142. * @type {?Texture}
  28143. * @default null
  28144. */
  28145. this.sheenRoughnessMap = null;
  28146. /**
  28147. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28148. * optical transparency.
  28149. *
  28150. * @type {?Texture}
  28151. * @default null
  28152. */
  28153. this.transmissionMap = null;
  28154. /**
  28155. * The thickness of the volume beneath the surface. The value is given in the
  28156. * coordinate space of the mesh. If the value is `0` the material is
  28157. * thin-walled. Otherwise the material is a volume boundary.
  28158. *
  28159. * @type {number}
  28160. * @default 0
  28161. */
  28162. this.thickness = 0;
  28163. /**
  28164. * A texture that defines the thickness, stored in the green channel. This will
  28165. * be multiplied by `thickness`.
  28166. *
  28167. * @type {?Texture}
  28168. * @default null
  28169. */
  28170. this.thicknessMap = null;
  28171. /**
  28172. * Density of the medium given as the average distance that light travels in
  28173. * the medium before interacting with a particle. The value is given in world
  28174. * space units, and must be greater than zero.
  28175. *
  28176. * @type {number}
  28177. * @default Infinity
  28178. */
  28179. this.attenuationDistance = Infinity;
  28180. /**
  28181. * The color that white light turns into due to absorption when reaching the
  28182. * attenuation distance.
  28183. *
  28184. * @type {Color}
  28185. * @default (1,1,1)
  28186. */
  28187. this.attenuationColor = new Color( 1, 1, 1 );
  28188. /**
  28189. * A float that scales the amount of specular reflection for non-metals only.
  28190. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28191. *
  28192. * @type {number}
  28193. * @default 1
  28194. */
  28195. this.specularIntensity = 1.0;
  28196. /**
  28197. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28198. * for per-pixel control over specular intensity.
  28199. *
  28200. * @type {?Texture}
  28201. * @default null
  28202. */
  28203. this.specularIntensityMap = null;
  28204. /**
  28205. * Tints the specular reflection at normal incidence for non-metals only.
  28206. *
  28207. * @type {Color}
  28208. * @default (1,1,1)
  28209. */
  28210. this.specularColor = new Color( 1, 1, 1 );
  28211. /**
  28212. * The RGB channels of this texture are multiplied against `specularColor`,
  28213. * for per-pixel control over specular color.
  28214. *
  28215. * @type {?Texture}
  28216. * @default null
  28217. */
  28218. this.specularColorMap = null;
  28219. this._anisotropy = 0;
  28220. this._clearcoat = 0;
  28221. this._dispersion = 0;
  28222. this._iridescence = 0;
  28223. this._sheen = 0.0;
  28224. this._transmission = 0;
  28225. this.setValues( parameters );
  28226. }
  28227. /**
  28228. * The anisotropy strength.
  28229. *
  28230. * @type {number}
  28231. * @default 0
  28232. */
  28233. get anisotropy() {
  28234. return this._anisotropy;
  28235. }
  28236. set anisotropy( value ) {
  28237. if ( this._anisotropy > 0 !== value > 0 ) {
  28238. this.version ++;
  28239. }
  28240. this._anisotropy = value;
  28241. }
  28242. /**
  28243. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28244. * clear coat related properties to enable multilayer materials that have a
  28245. * thin translucent layer over the base layer.
  28246. *
  28247. * @type {number}
  28248. * @default 0
  28249. */
  28250. get clearcoat() {
  28251. return this._clearcoat;
  28252. }
  28253. set clearcoat( value ) {
  28254. if ( this._clearcoat > 0 !== value > 0 ) {
  28255. this.version ++;
  28256. }
  28257. this._clearcoat = value;
  28258. }
  28259. /**
  28260. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28261. * the surface and the viewer, from `0.0` to `1.0`.
  28262. *
  28263. * @type {number}
  28264. * @default 0
  28265. */
  28266. get iridescence() {
  28267. return this._iridescence;
  28268. }
  28269. set iridescence( value ) {
  28270. if ( this._iridescence > 0 !== value > 0 ) {
  28271. this.version ++;
  28272. }
  28273. this._iridescence = value;
  28274. }
  28275. /**
  28276. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28277. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28278. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28279. *
  28280. * @type {number}
  28281. * @default 0
  28282. */
  28283. get dispersion() {
  28284. return this._dispersion;
  28285. }
  28286. set dispersion( value ) {
  28287. if ( this._dispersion > 0 !== value > 0 ) {
  28288. this.version ++;
  28289. }
  28290. this._dispersion = value;
  28291. }
  28292. /**
  28293. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28294. *
  28295. * @type {number}
  28296. * @default 0
  28297. */
  28298. get sheen() {
  28299. return this._sheen;
  28300. }
  28301. set sheen( value ) {
  28302. if ( this._sheen > 0 !== value > 0 ) {
  28303. this.version ++;
  28304. }
  28305. this._sheen = value;
  28306. }
  28307. /**
  28308. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28309. *
  28310. * Thin, transparent or semitransparent, plastic or glass materials remain
  28311. * largely reflective even if they are fully transmissive. The transmission
  28312. * property can be used to model these materials.
  28313. *
  28314. * When transmission is non-zero, `opacity` should be set to `1`.
  28315. *
  28316. * @type {number}
  28317. * @default 0
  28318. */
  28319. get transmission() {
  28320. return this._transmission;
  28321. }
  28322. set transmission( value ) {
  28323. if ( this._transmission > 0 !== value > 0 ) {
  28324. this.version ++;
  28325. }
  28326. this._transmission = value;
  28327. }
  28328. copy( source ) {
  28329. super.copy( source );
  28330. this.defines = {
  28331. 'STANDARD': '',
  28332. 'PHYSICAL': ''
  28333. };
  28334. this.anisotropy = source.anisotropy;
  28335. this.anisotropyRotation = source.anisotropyRotation;
  28336. this.anisotropyMap = source.anisotropyMap;
  28337. this.clearcoat = source.clearcoat;
  28338. this.clearcoatMap = source.clearcoatMap;
  28339. this.clearcoatRoughness = source.clearcoatRoughness;
  28340. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28341. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28342. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28343. this.dispersion = source.dispersion;
  28344. this.ior = source.ior;
  28345. this.iridescence = source.iridescence;
  28346. this.iridescenceMap = source.iridescenceMap;
  28347. this.iridescenceIOR = source.iridescenceIOR;
  28348. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28349. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28350. this.sheen = source.sheen;
  28351. this.sheenColor.copy( source.sheenColor );
  28352. this.sheenColorMap = source.sheenColorMap;
  28353. this.sheenRoughness = source.sheenRoughness;
  28354. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28355. this.transmission = source.transmission;
  28356. this.transmissionMap = source.transmissionMap;
  28357. this.thickness = source.thickness;
  28358. this.thicknessMap = source.thicknessMap;
  28359. this.attenuationDistance = source.attenuationDistance;
  28360. this.attenuationColor.copy( source.attenuationColor );
  28361. this.specularIntensity = source.specularIntensity;
  28362. this.specularIntensityMap = source.specularIntensityMap;
  28363. this.specularColor.copy( source.specularColor );
  28364. this.specularColorMap = source.specularColorMap;
  28365. return this;
  28366. }
  28367. }
  28368. /**
  28369. * A material for shiny surfaces with specular highlights.
  28370. *
  28371. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28372. * model for calculating reflectance. Unlike the Lambertian model used in the
  28373. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28374. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28375. *
  28376. * Performance will generally be greater when using this material over the
  28377. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28378. * some graphical accuracy.
  28379. *
  28380. * @augments Material
  28381. */
  28382. class MeshPhongMaterial extends Material {
  28383. /**
  28384. * Constructs a new mesh phong material.
  28385. *
  28386. * @param {Object} [parameters] - An object with one or more properties
  28387. * defining the material's appearance. Any property of the material
  28388. * (including any property from inherited materials) can be passed
  28389. * in here. Color values can be passed any type of value accepted
  28390. * by {@link Color#set}.
  28391. */
  28392. constructor( parameters ) {
  28393. super();
  28394. /**
  28395. * This flag can be used for type testing.
  28396. *
  28397. * @type {boolean}
  28398. * @readonly
  28399. * @default true
  28400. */
  28401. this.isMeshPhongMaterial = true;
  28402. this.type = 'MeshPhongMaterial';
  28403. /**
  28404. * Color of the material.
  28405. *
  28406. * @type {Color}
  28407. * @default (1,1,1)
  28408. */
  28409. this.color = new Color( 0xffffff ); // diffuse
  28410. /**
  28411. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28412. *
  28413. * This defines how shiny the material is and the color of its shine.
  28414. *
  28415. * @type {Color}
  28416. */
  28417. this.specular = new Color( 0x111111 );
  28418. /**
  28419. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28420. *
  28421. * @type {number}
  28422. * @default 30
  28423. */
  28424. this.shininess = 30;
  28425. /**
  28426. * The color map. May optionally include an alpha channel, typically combined
  28427. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28428. * color is modulated by the diffuse `color`.
  28429. *
  28430. * @type {?Texture}
  28431. * @default null
  28432. */
  28433. this.map = null;
  28434. /**
  28435. * The light map. Requires a second set of UVs.
  28436. *
  28437. * @type {?Texture}
  28438. * @default null
  28439. */
  28440. this.lightMap = null;
  28441. /**
  28442. * Intensity of the baked light.
  28443. *
  28444. * @type {number}
  28445. * @default 1
  28446. */
  28447. this.lightMapIntensity = 1.0;
  28448. /**
  28449. * The red channel of this texture is used as the ambient occlusion map.
  28450. * Requires a second set of UVs.
  28451. *
  28452. * @type {?Texture}
  28453. * @default null
  28454. */
  28455. this.aoMap = null;
  28456. /**
  28457. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28458. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28459. * red channel is also `1`, ambient light is fully occluded on a surface.
  28460. *
  28461. * @type {number}
  28462. * @default 1
  28463. */
  28464. this.aoMapIntensity = 1.0;
  28465. /**
  28466. * Emissive (light) color of the material, essentially a solid color
  28467. * unaffected by other lighting.
  28468. *
  28469. * @type {Color}
  28470. * @default (0,0,0)
  28471. */
  28472. this.emissive = new Color( 0x000000 );
  28473. /**
  28474. * Intensity of the emissive light. Modulates the emissive color.
  28475. *
  28476. * @type {number}
  28477. * @default 1
  28478. */
  28479. this.emissiveIntensity = 1.0;
  28480. /**
  28481. * Set emissive (glow) map. The emissive map color is modulated by the
  28482. * emissive color and the emissive intensity. If you have an emissive map,
  28483. * be sure to set the emissive color to something other than black.
  28484. *
  28485. * @type {?Texture}
  28486. * @default null
  28487. */
  28488. this.emissiveMap = null;
  28489. /**
  28490. * The texture to create a bump map. The black and white values map to the
  28491. * perceived depth in relation to the lights. Bump doesn't actually affect
  28492. * the geometry of the object, only the lighting. If a normal map is defined
  28493. * this will be ignored.
  28494. *
  28495. * @type {?Texture}
  28496. * @default null
  28497. */
  28498. this.bumpMap = null;
  28499. /**
  28500. * How much the bump map affects the material. Typical range is `[0,1]`.
  28501. *
  28502. * @type {number}
  28503. * @default 1
  28504. */
  28505. this.bumpScale = 1;
  28506. /**
  28507. * The texture to create a normal map. The RGB values affect the surface
  28508. * normal for each pixel fragment and change the way the color is lit. Normal
  28509. * maps do not change the actual shape of the surface, only the lighting. In
  28510. * case the material has a normal map authored using the left handed
  28511. * convention, the `y` component of `normalScale` should be negated to compensate
  28512. * for the different handedness.
  28513. *
  28514. * @type {?Texture}
  28515. * @default null
  28516. */
  28517. this.normalMap = null;
  28518. /**
  28519. * The type of normal map.
  28520. *
  28521. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28522. * @default TangentSpaceNormalMap
  28523. */
  28524. this.normalMapType = TangentSpaceNormalMap;
  28525. /**
  28526. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28527. *
  28528. * @type {Vector2}
  28529. * @default (1,1)
  28530. */
  28531. this.normalScale = new Vector2( 1, 1 );
  28532. /**
  28533. * The displacement map affects the position of the mesh's vertices. Unlike
  28534. * other maps which only affect the light and shade of the material the
  28535. * displaced vertices can cast shadows, block other objects, and otherwise
  28536. * act as real geometry. The displacement texture is an image where the value
  28537. * of each pixel (white being the highest) is mapped against, and
  28538. * repositions, the vertices of the mesh.
  28539. *
  28540. * @type {?Texture}
  28541. * @default null
  28542. */
  28543. this.displacementMap = null;
  28544. /**
  28545. * How much the displacement map affects the mesh (where black is no
  28546. * displacement, and white is maximum displacement). Without a displacement
  28547. * map set, this value is not applied.
  28548. *
  28549. * @type {number}
  28550. * @default 0
  28551. */
  28552. this.displacementScale = 1;
  28553. /**
  28554. * The offset of the displacement map's values on the mesh's vertices.
  28555. * The bias is added to the scaled sample of the displacement map.
  28556. * Without a displacement map set, this value is not applied.
  28557. *
  28558. * @type {number}
  28559. * @default 0
  28560. */
  28561. this.displacementBias = 0;
  28562. /**
  28563. * The specular map value affects both how much the specular surface
  28564. * highlight contributes and how much of the environment map affects the
  28565. * surface.
  28566. *
  28567. * @type {?Texture}
  28568. * @default null
  28569. */
  28570. this.specularMap = null;
  28571. /**
  28572. * The alpha map is a grayscale texture that controls the opacity across the
  28573. * surface (black: fully transparent; white: fully opaque).
  28574. *
  28575. * Only the color of the texture is used, ignoring the alpha channel if one
  28576. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28577. * when sampling this texture due to the extra bit of precision provided for
  28578. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28579. * luminance/alpha textures will also still work as expected.
  28580. *
  28581. * @type {?Texture}
  28582. * @default null
  28583. */
  28584. this.alphaMap = null;
  28585. /**
  28586. * The environment map.
  28587. *
  28588. * @type {?Texture}
  28589. * @default null
  28590. */
  28591. this.envMap = null;
  28592. /**
  28593. * The rotation of the environment map in radians.
  28594. *
  28595. * @type {Euler}
  28596. * @default (0,0,0)
  28597. */
  28598. this.envMapRotation = new Euler();
  28599. /**
  28600. * How to combine the result of the surface's color with the environment map, if any.
  28601. *
  28602. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28603. * blend between the two colors.
  28604. *
  28605. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28606. * @default MultiplyOperation
  28607. */
  28608. this.combine = MultiplyOperation;
  28609. /**
  28610. * How much the environment map affects the surface.
  28611. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28612. *
  28613. * @type {number}
  28614. * @default 1
  28615. */
  28616. this.reflectivity = 1;
  28617. /**
  28618. * The index of refraction (IOR) of air (approximately 1) divided by the
  28619. * index of refraction of the material. It is used with environment mapping
  28620. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28621. * The refraction ratio should not exceed `1`.
  28622. *
  28623. * @type {number}
  28624. * @default 0.98
  28625. */
  28626. this.refractionRatio = 0.98;
  28627. /**
  28628. * Renders the geometry as a wireframe.
  28629. *
  28630. * @type {boolean}
  28631. * @default false
  28632. */
  28633. this.wireframe = false;
  28634. /**
  28635. * Controls the thickness of the wireframe.
  28636. *
  28637. * Can only be used with {@link SVGRenderer}.
  28638. *
  28639. * @type {number}
  28640. * @default 1
  28641. */
  28642. this.wireframeLinewidth = 1;
  28643. /**
  28644. * Defines appearance of wireframe ends.
  28645. *
  28646. * Can only be used with {@link SVGRenderer}.
  28647. *
  28648. * @type {('round'|'bevel'|'miter')}
  28649. * @default 'round'
  28650. */
  28651. this.wireframeLinecap = 'round';
  28652. /**
  28653. * Defines appearance of wireframe joints.
  28654. *
  28655. * Can only be used with {@link SVGRenderer}.
  28656. *
  28657. * @type {('round'|'bevel'|'miter')}
  28658. * @default 'round'
  28659. */
  28660. this.wireframeLinejoin = 'round';
  28661. /**
  28662. * Whether the material is rendered with flat shading or not.
  28663. *
  28664. * @type {boolean}
  28665. * @default false
  28666. */
  28667. this.flatShading = false;
  28668. /**
  28669. * Whether the material is affected by fog or not.
  28670. *
  28671. * @type {boolean}
  28672. * @default true
  28673. */
  28674. this.fog = true;
  28675. this.setValues( parameters );
  28676. }
  28677. copy( source ) {
  28678. super.copy( source );
  28679. this.color.copy( source.color );
  28680. this.specular.copy( source.specular );
  28681. this.shininess = source.shininess;
  28682. this.map = source.map;
  28683. this.lightMap = source.lightMap;
  28684. this.lightMapIntensity = source.lightMapIntensity;
  28685. this.aoMap = source.aoMap;
  28686. this.aoMapIntensity = source.aoMapIntensity;
  28687. this.emissive.copy( source.emissive );
  28688. this.emissiveMap = source.emissiveMap;
  28689. this.emissiveIntensity = source.emissiveIntensity;
  28690. this.bumpMap = source.bumpMap;
  28691. this.bumpScale = source.bumpScale;
  28692. this.normalMap = source.normalMap;
  28693. this.normalMapType = source.normalMapType;
  28694. this.normalScale.copy( source.normalScale );
  28695. this.displacementMap = source.displacementMap;
  28696. this.displacementScale = source.displacementScale;
  28697. this.displacementBias = source.displacementBias;
  28698. this.specularMap = source.specularMap;
  28699. this.alphaMap = source.alphaMap;
  28700. this.envMap = source.envMap;
  28701. this.envMapRotation.copy( source.envMapRotation );
  28702. this.combine = source.combine;
  28703. this.reflectivity = source.reflectivity;
  28704. this.refractionRatio = source.refractionRatio;
  28705. this.wireframe = source.wireframe;
  28706. this.wireframeLinewidth = source.wireframeLinewidth;
  28707. this.wireframeLinecap = source.wireframeLinecap;
  28708. this.wireframeLinejoin = source.wireframeLinejoin;
  28709. this.flatShading = source.flatShading;
  28710. this.fog = source.fog;
  28711. return this;
  28712. }
  28713. }
  28714. /**
  28715. * A material implementing toon shading.
  28716. *
  28717. * @augments Material
  28718. */
  28719. class MeshToonMaterial extends Material {
  28720. /**
  28721. * Constructs a new mesh toon material.
  28722. *
  28723. * @param {Object} [parameters] - An object with one or more properties
  28724. * defining the material's appearance. Any property of the material
  28725. * (including any property from inherited materials) can be passed
  28726. * in here. Color values can be passed any type of value accepted
  28727. * by {@link Color#set}.
  28728. */
  28729. constructor( parameters ) {
  28730. super();
  28731. /**
  28732. * This flag can be used for type testing.
  28733. *
  28734. * @type {boolean}
  28735. * @readonly
  28736. * @default true
  28737. */
  28738. this.isMeshToonMaterial = true;
  28739. this.defines = { 'TOON': '' };
  28740. this.type = 'MeshToonMaterial';
  28741. /**
  28742. * Color of the material.
  28743. *
  28744. * @type {Color}
  28745. * @default (1,1,1)
  28746. */
  28747. this.color = new Color( 0xffffff );
  28748. /**
  28749. * The color map. May optionally include an alpha channel, typically combined
  28750. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28751. * color is modulated by the diffuse `color`.
  28752. *
  28753. * @type {?Texture}
  28754. * @default null
  28755. */
  28756. this.map = null;
  28757. /**
  28758. * Gradient map for toon shading. It's required to set
  28759. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28760. * when using this type of texture.
  28761. *
  28762. * @type {?Texture}
  28763. * @default null
  28764. */
  28765. this.gradientMap = null;
  28766. /**
  28767. * The light map. Requires a second set of UVs.
  28768. *
  28769. * @type {?Texture}
  28770. * @default null
  28771. */
  28772. this.lightMap = null;
  28773. /**
  28774. * Intensity of the baked light.
  28775. *
  28776. * @type {number}
  28777. * @default 1
  28778. */
  28779. this.lightMapIntensity = 1.0;
  28780. /**
  28781. * The red channel of this texture is used as the ambient occlusion map.
  28782. * Requires a second set of UVs.
  28783. *
  28784. * @type {?Texture}
  28785. * @default null
  28786. */
  28787. this.aoMap = null;
  28788. /**
  28789. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28790. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28791. * red channel is also `1`, ambient light is fully occluded on a surface.
  28792. *
  28793. * @type {number}
  28794. * @default 1
  28795. */
  28796. this.aoMapIntensity = 1.0;
  28797. /**
  28798. * Emissive (light) color of the material, essentially a solid color
  28799. * unaffected by other lighting.
  28800. *
  28801. * @type {Color}
  28802. * @default (0,0,0)
  28803. */
  28804. this.emissive = new Color( 0x000000 );
  28805. /**
  28806. * Intensity of the emissive light. Modulates the emissive color.
  28807. *
  28808. * @type {number}
  28809. * @default 1
  28810. */
  28811. this.emissiveIntensity = 1.0;
  28812. /**
  28813. * Set emissive (glow) map. The emissive map color is modulated by the
  28814. * emissive color and the emissive intensity. If you have an emissive map,
  28815. * be sure to set the emissive color to something other than black.
  28816. *
  28817. * @type {?Texture}
  28818. * @default null
  28819. */
  28820. this.emissiveMap = null;
  28821. /**
  28822. * The texture to create a bump map. The black and white values map to the
  28823. * perceived depth in relation to the lights. Bump doesn't actually affect
  28824. * the geometry of the object, only the lighting. If a normal map is defined
  28825. * this will be ignored.
  28826. *
  28827. * @type {?Texture}
  28828. * @default null
  28829. */
  28830. this.bumpMap = null;
  28831. /**
  28832. * How much the bump map affects the material. Typical range is `[0,1]`.
  28833. *
  28834. * @type {number}
  28835. * @default 1
  28836. */
  28837. this.bumpScale = 1;
  28838. /**
  28839. * The texture to create a normal map. The RGB values affect the surface
  28840. * normal for each pixel fragment and change the way the color is lit. Normal
  28841. * maps do not change the actual shape of the surface, only the lighting. In
  28842. * case the material has a normal map authored using the left handed
  28843. * convention, the `y` component of `normalScale` should be negated to compensate
  28844. * for the different handedness.
  28845. *
  28846. * @type {?Texture}
  28847. * @default null
  28848. */
  28849. this.normalMap = null;
  28850. /**
  28851. * The type of normal map.
  28852. *
  28853. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28854. * @default TangentSpaceNormalMap
  28855. */
  28856. this.normalMapType = TangentSpaceNormalMap;
  28857. /**
  28858. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28859. *
  28860. * @type {Vector2}
  28861. * @default (1,1)
  28862. */
  28863. this.normalScale = new Vector2( 1, 1 );
  28864. /**
  28865. * The displacement map affects the position of the mesh's vertices. Unlike
  28866. * other maps which only affect the light and shade of the material the
  28867. * displaced vertices can cast shadows, block other objects, and otherwise
  28868. * act as real geometry. The displacement texture is an image where the value
  28869. * of each pixel (white being the highest) is mapped against, and
  28870. * repositions, the vertices of the mesh.
  28871. *
  28872. * @type {?Texture}
  28873. * @default null
  28874. */
  28875. this.displacementMap = null;
  28876. /**
  28877. * How much the displacement map affects the mesh (where black is no
  28878. * displacement, and white is maximum displacement). Without a displacement
  28879. * map set, this value is not applied.
  28880. *
  28881. * @type {number}
  28882. * @default 0
  28883. */
  28884. this.displacementScale = 1;
  28885. /**
  28886. * The offset of the displacement map's values on the mesh's vertices.
  28887. * The bias is added to the scaled sample of the displacement map.
  28888. * Without a displacement map set, this value is not applied.
  28889. *
  28890. * @type {number}
  28891. * @default 0
  28892. */
  28893. this.displacementBias = 0;
  28894. /**
  28895. * The alpha map is a grayscale texture that controls the opacity across the
  28896. * surface (black: fully transparent; white: fully opaque).
  28897. *
  28898. * Only the color of the texture is used, ignoring the alpha channel if one
  28899. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28900. * when sampling this texture due to the extra bit of precision provided for
  28901. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28902. * luminance/alpha textures will also still work as expected.
  28903. *
  28904. * @type {?Texture}
  28905. * @default null
  28906. */
  28907. this.alphaMap = null;
  28908. /**
  28909. * Renders the geometry as a wireframe.
  28910. *
  28911. * @type {boolean}
  28912. * @default false
  28913. */
  28914. this.wireframe = false;
  28915. /**
  28916. * Controls the thickness of the wireframe.
  28917. *
  28918. * Can only be used with {@link SVGRenderer}.
  28919. *
  28920. * @type {number}
  28921. * @default 1
  28922. */
  28923. this.wireframeLinewidth = 1;
  28924. /**
  28925. * Defines appearance of wireframe ends.
  28926. *
  28927. * Can only be used with {@link SVGRenderer}.
  28928. *
  28929. * @type {('round'|'bevel'|'miter')}
  28930. * @default 'round'
  28931. */
  28932. this.wireframeLinecap = 'round';
  28933. /**
  28934. * Defines appearance of wireframe joints.
  28935. *
  28936. * Can only be used with {@link SVGRenderer}.
  28937. *
  28938. * @type {('round'|'bevel'|'miter')}
  28939. * @default 'round'
  28940. */
  28941. this.wireframeLinejoin = 'round';
  28942. /**
  28943. * Whether the material is affected by fog or not.
  28944. *
  28945. * @type {boolean}
  28946. * @default true
  28947. */
  28948. this.fog = true;
  28949. this.setValues( parameters );
  28950. }
  28951. copy( source ) {
  28952. super.copy( source );
  28953. this.color.copy( source.color );
  28954. this.map = source.map;
  28955. this.gradientMap = source.gradientMap;
  28956. this.lightMap = source.lightMap;
  28957. this.lightMapIntensity = source.lightMapIntensity;
  28958. this.aoMap = source.aoMap;
  28959. this.aoMapIntensity = source.aoMapIntensity;
  28960. this.emissive.copy( source.emissive );
  28961. this.emissiveMap = source.emissiveMap;
  28962. this.emissiveIntensity = source.emissiveIntensity;
  28963. this.bumpMap = source.bumpMap;
  28964. this.bumpScale = source.bumpScale;
  28965. this.normalMap = source.normalMap;
  28966. this.normalMapType = source.normalMapType;
  28967. this.normalScale.copy( source.normalScale );
  28968. this.displacementMap = source.displacementMap;
  28969. this.displacementScale = source.displacementScale;
  28970. this.displacementBias = source.displacementBias;
  28971. this.alphaMap = source.alphaMap;
  28972. this.wireframe = source.wireframe;
  28973. this.wireframeLinewidth = source.wireframeLinewidth;
  28974. this.wireframeLinecap = source.wireframeLinecap;
  28975. this.wireframeLinejoin = source.wireframeLinejoin;
  28976. this.fog = source.fog;
  28977. return this;
  28978. }
  28979. }
  28980. /**
  28981. * A material that maps the normal vectors to RGB colors.
  28982. *
  28983. * @augments Material
  28984. */
  28985. class MeshNormalMaterial extends Material {
  28986. /**
  28987. * Constructs a new mesh normal material.
  28988. *
  28989. * @param {Object} [parameters] - An object with one or more properties
  28990. * defining the material's appearance. Any property of the material
  28991. * (including any property from inherited materials) can be passed
  28992. * in here. Color values can be passed any type of value accepted
  28993. * by {@link Color#set}.
  28994. */
  28995. constructor( parameters ) {
  28996. super();
  28997. /**
  28998. * This flag can be used for type testing.
  28999. *
  29000. * @type {boolean}
  29001. * @readonly
  29002. * @default true
  29003. */
  29004. this.isMeshNormalMaterial = true;
  29005. this.type = 'MeshNormalMaterial';
  29006. /**
  29007. * The texture to create a bump map. The black and white values map to the
  29008. * perceived depth in relation to the lights. Bump doesn't actually affect
  29009. * the geometry of the object, only the lighting. If a normal map is defined
  29010. * this will be ignored.
  29011. *
  29012. * @type {?Texture}
  29013. * @default null
  29014. */
  29015. this.bumpMap = null;
  29016. /**
  29017. * How much the bump map affects the material. Typical range is `[0,1]`.
  29018. *
  29019. * @type {number}
  29020. * @default 1
  29021. */
  29022. this.bumpScale = 1;
  29023. /**
  29024. * The texture to create a normal map. The RGB values affect the surface
  29025. * normal for each pixel fragment and change the way the color is lit. Normal
  29026. * maps do not change the actual shape of the surface, only the lighting. In
  29027. * case the material has a normal map authored using the left handed
  29028. * convention, the `y` component of `normalScale` should be negated to compensate
  29029. * for the different handedness.
  29030. *
  29031. * @type {?Texture}
  29032. * @default null
  29033. */
  29034. this.normalMap = null;
  29035. /**
  29036. * The type of normal map.
  29037. *
  29038. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29039. * @default TangentSpaceNormalMap
  29040. */
  29041. this.normalMapType = TangentSpaceNormalMap;
  29042. /**
  29043. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29044. *
  29045. * @type {Vector2}
  29046. * @default (1,1)
  29047. */
  29048. this.normalScale = new Vector2( 1, 1 );
  29049. /**
  29050. * The displacement map affects the position of the mesh's vertices. Unlike
  29051. * other maps which only affect the light and shade of the material the
  29052. * displaced vertices can cast shadows, block other objects, and otherwise
  29053. * act as real geometry. The displacement texture is an image where the value
  29054. * of each pixel (white being the highest) is mapped against, and
  29055. * repositions, the vertices of the mesh.
  29056. *
  29057. * @type {?Texture}
  29058. * @default null
  29059. */
  29060. this.displacementMap = null;
  29061. /**
  29062. * How much the displacement map affects the mesh (where black is no
  29063. * displacement, and white is maximum displacement). Without a displacement
  29064. * map set, this value is not applied.
  29065. *
  29066. * @type {number}
  29067. * @default 0
  29068. */
  29069. this.displacementScale = 1;
  29070. /**
  29071. * The offset of the displacement map's values on the mesh's vertices.
  29072. * The bias is added to the scaled sample of the displacement map.
  29073. * Without a displacement map set, this value is not applied.
  29074. *
  29075. * @type {number}
  29076. * @default 0
  29077. */
  29078. this.displacementBias = 0;
  29079. /**
  29080. * Renders the geometry as a wireframe.
  29081. *
  29082. * @type {boolean}
  29083. * @default false
  29084. */
  29085. this.wireframe = false;
  29086. /**
  29087. * Controls the thickness of the wireframe.
  29088. *
  29089. * WebGL and WebGPU ignore this property and always render
  29090. * 1 pixel wide lines.
  29091. *
  29092. * @type {number}
  29093. * @default 1
  29094. */
  29095. this.wireframeLinewidth = 1;
  29096. /**
  29097. * Whether the material is rendered with flat shading or not.
  29098. *
  29099. * @type {boolean}
  29100. * @default false
  29101. */
  29102. this.flatShading = false;
  29103. this.setValues( parameters );
  29104. }
  29105. copy( source ) {
  29106. super.copy( source );
  29107. this.bumpMap = source.bumpMap;
  29108. this.bumpScale = source.bumpScale;
  29109. this.normalMap = source.normalMap;
  29110. this.normalMapType = source.normalMapType;
  29111. this.normalScale.copy( source.normalScale );
  29112. this.displacementMap = source.displacementMap;
  29113. this.displacementScale = source.displacementScale;
  29114. this.displacementBias = source.displacementBias;
  29115. this.wireframe = source.wireframe;
  29116. this.wireframeLinewidth = source.wireframeLinewidth;
  29117. this.flatShading = source.flatShading;
  29118. return this;
  29119. }
  29120. }
  29121. /**
  29122. * A material for non-shiny surfaces, without specular highlights.
  29123. *
  29124. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29125. * model for calculating reflectance. This can simulate some surfaces (such
  29126. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29127. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29128. * shading.
  29129. *
  29130. * Due to the simplicity of the reflectance and illumination models,
  29131. * performance will be greater when using this material over the
  29132. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29133. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29134. *
  29135. * @augments Material
  29136. */
  29137. class MeshLambertMaterial extends Material {
  29138. /**
  29139. * Constructs a new mesh lambert material.
  29140. *
  29141. * @param {Object} [parameters] - An object with one or more properties
  29142. * defining the material's appearance. Any property of the material
  29143. * (including any property from inherited materials) can be passed
  29144. * in here. Color values can be passed any type of value accepted
  29145. * by {@link Color#set}.
  29146. */
  29147. constructor( parameters ) {
  29148. super();
  29149. /**
  29150. * This flag can be used for type testing.
  29151. *
  29152. * @type {boolean}
  29153. * @readonly
  29154. * @default true
  29155. */
  29156. this.isMeshLambertMaterial = true;
  29157. this.type = 'MeshLambertMaterial';
  29158. /**
  29159. * Color of the material.
  29160. *
  29161. * @type {Color}
  29162. * @default (1,1,1)
  29163. */
  29164. this.color = new Color( 0xffffff ); // diffuse
  29165. /**
  29166. * The color map. May optionally include an alpha channel, typically combined
  29167. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29168. * color is modulated by the diffuse `color`.
  29169. *
  29170. * @type {?Texture}
  29171. * @default null
  29172. */
  29173. this.map = null;
  29174. /**
  29175. * The light map. Requires a second set of UVs.
  29176. *
  29177. * @type {?Texture}
  29178. * @default null
  29179. */
  29180. this.lightMap = null;
  29181. /**
  29182. * Intensity of the baked light.
  29183. *
  29184. * @type {number}
  29185. * @default 1
  29186. */
  29187. this.lightMapIntensity = 1.0;
  29188. /**
  29189. * The red channel of this texture is used as the ambient occlusion map.
  29190. * Requires a second set of UVs.
  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. * @type {?Texture}
  29226. * @default null
  29227. */
  29228. this.emissiveMap = null;
  29229. /**
  29230. * The texture to create a bump map. The black and white values map to the
  29231. * perceived depth in relation to the lights. Bump doesn't actually affect
  29232. * the geometry of the object, only the lighting. If a normal map is defined
  29233. * this will be ignored.
  29234. *
  29235. * @type {?Texture}
  29236. * @default null
  29237. */
  29238. this.bumpMap = null;
  29239. /**
  29240. * How much the bump map affects the material. Typical range is `[0,1]`.
  29241. *
  29242. * @type {number}
  29243. * @default 1
  29244. */
  29245. this.bumpScale = 1;
  29246. /**
  29247. * The texture to create a normal map. The RGB values affect the surface
  29248. * normal for each pixel fragment and change the way the color is lit. Normal
  29249. * maps do not change the actual shape of the surface, only the lighting. In
  29250. * case the material has a normal map authored using the left handed
  29251. * convention, the `y` component of `normalScale` should be negated to compensate
  29252. * for the different handedness.
  29253. *
  29254. * @type {?Texture}
  29255. * @default null
  29256. */
  29257. this.normalMap = null;
  29258. /**
  29259. * The type of normal map.
  29260. *
  29261. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29262. * @default TangentSpaceNormalMap
  29263. */
  29264. this.normalMapType = TangentSpaceNormalMap;
  29265. /**
  29266. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29267. *
  29268. * @type {Vector2}
  29269. * @default (1,1)
  29270. */
  29271. this.normalScale = new Vector2( 1, 1 );
  29272. /**
  29273. * The displacement map affects the position of the mesh's vertices. Unlike
  29274. * other maps which only affect the light and shade of the material the
  29275. * displaced vertices can cast shadows, block other objects, and otherwise
  29276. * act as real geometry. The displacement texture is an image where the value
  29277. * of each pixel (white being the highest) is mapped against, and
  29278. * repositions, the vertices of the mesh.
  29279. *
  29280. * @type {?Texture}
  29281. * @default null
  29282. */
  29283. this.displacementMap = null;
  29284. /**
  29285. * How much the displacement map affects the mesh (where black is no
  29286. * displacement, and white is maximum displacement). Without a displacement
  29287. * map set, this value is not applied.
  29288. *
  29289. * @type {number}
  29290. * @default 0
  29291. */
  29292. this.displacementScale = 1;
  29293. /**
  29294. * The offset of the displacement map's values on the mesh's vertices.
  29295. * The bias is added to the scaled sample of the displacement map.
  29296. * Without a displacement map set, this value is not applied.
  29297. *
  29298. * @type {number}
  29299. * @default 0
  29300. */
  29301. this.displacementBias = 0;
  29302. /**
  29303. * Specular map used by the material.
  29304. *
  29305. * @type {?Texture}
  29306. * @default null
  29307. */
  29308. this.specularMap = null;
  29309. /**
  29310. * The alpha map is a grayscale texture that controls the opacity across the
  29311. * surface (black: fully transparent; white: fully opaque).
  29312. *
  29313. * Only the color of the texture is used, ignoring the alpha channel if one
  29314. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29315. * when sampling this texture due to the extra bit of precision provided for
  29316. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29317. * luminance/alpha textures will also still work as expected.
  29318. *
  29319. * @type {?Texture}
  29320. * @default null
  29321. */
  29322. this.alphaMap = null;
  29323. /**
  29324. * The environment map.
  29325. *
  29326. * @type {?Texture}
  29327. * @default null
  29328. */
  29329. this.envMap = null;
  29330. /**
  29331. * The rotation of the environment map in radians.
  29332. *
  29333. * @type {Euler}
  29334. * @default (0,0,0)
  29335. */
  29336. this.envMapRotation = new Euler();
  29337. /**
  29338. * How to combine the result of the surface's color with the environment map, if any.
  29339. *
  29340. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29341. * blend between the two colors.
  29342. *
  29343. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29344. * @default MultiplyOperation
  29345. */
  29346. this.combine = MultiplyOperation;
  29347. /**
  29348. * How much the environment map affects the surface.
  29349. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29350. *
  29351. * @type {number}
  29352. * @default 1
  29353. */
  29354. this.reflectivity = 1;
  29355. /**
  29356. * The index of refraction (IOR) of air (approximately 1) divided by the
  29357. * index of refraction of the material. It is used with environment mapping
  29358. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29359. * The refraction ratio should not exceed `1`.
  29360. *
  29361. * @type {number}
  29362. * @default 0.98
  29363. */
  29364. this.refractionRatio = 0.98;
  29365. /**
  29366. * Renders the geometry as a wireframe.
  29367. *
  29368. * @type {boolean}
  29369. * @default false
  29370. */
  29371. this.wireframe = false;
  29372. /**
  29373. * Controls the thickness of the wireframe.
  29374. *
  29375. * Can only be used with {@link SVGRenderer}.
  29376. *
  29377. * @type {number}
  29378. * @default 1
  29379. */
  29380. this.wireframeLinewidth = 1;
  29381. /**
  29382. * Defines appearance of wireframe ends.
  29383. *
  29384. * Can only be used with {@link SVGRenderer}.
  29385. *
  29386. * @type {('round'|'bevel'|'miter')}
  29387. * @default 'round'
  29388. */
  29389. this.wireframeLinecap = 'round';
  29390. /**
  29391. * Defines appearance of wireframe joints.
  29392. *
  29393. * Can only be used with {@link SVGRenderer}.
  29394. *
  29395. * @type {('round'|'bevel'|'miter')}
  29396. * @default 'round'
  29397. */
  29398. this.wireframeLinejoin = 'round';
  29399. /**
  29400. * Whether the material is rendered with flat shading or not.
  29401. *
  29402. * @type {boolean}
  29403. * @default false
  29404. */
  29405. this.flatShading = false;
  29406. /**
  29407. * Whether the material is affected by fog or not.
  29408. *
  29409. * @type {boolean}
  29410. * @default true
  29411. */
  29412. this.fog = true;
  29413. this.setValues( parameters );
  29414. }
  29415. copy( source ) {
  29416. super.copy( source );
  29417. this.color.copy( source.color );
  29418. this.map = source.map;
  29419. this.lightMap = source.lightMap;
  29420. this.lightMapIntensity = source.lightMapIntensity;
  29421. this.aoMap = source.aoMap;
  29422. this.aoMapIntensity = source.aoMapIntensity;
  29423. this.emissive.copy( source.emissive );
  29424. this.emissiveMap = source.emissiveMap;
  29425. this.emissiveIntensity = source.emissiveIntensity;
  29426. this.bumpMap = source.bumpMap;
  29427. this.bumpScale = source.bumpScale;
  29428. this.normalMap = source.normalMap;
  29429. this.normalMapType = source.normalMapType;
  29430. this.normalScale.copy( source.normalScale );
  29431. this.displacementMap = source.displacementMap;
  29432. this.displacementScale = source.displacementScale;
  29433. this.displacementBias = source.displacementBias;
  29434. this.specularMap = source.specularMap;
  29435. this.alphaMap = source.alphaMap;
  29436. this.envMap = source.envMap;
  29437. this.envMapRotation.copy( source.envMapRotation );
  29438. this.combine = source.combine;
  29439. this.reflectivity = source.reflectivity;
  29440. this.refractionRatio = source.refractionRatio;
  29441. this.wireframe = source.wireframe;
  29442. this.wireframeLinewidth = source.wireframeLinewidth;
  29443. this.wireframeLinecap = source.wireframeLinecap;
  29444. this.wireframeLinejoin = source.wireframeLinejoin;
  29445. this.flatShading = source.flatShading;
  29446. this.fog = source.fog;
  29447. return this;
  29448. }
  29449. }
  29450. /**
  29451. * A material for drawing geometry by depth. Depth is based off of the camera
  29452. * near and far plane. White is nearest, black is farthest.
  29453. *
  29454. * @augments Material
  29455. */
  29456. class MeshDepthMaterial extends Material {
  29457. /**
  29458. * Constructs a new mesh depth material.
  29459. *
  29460. * @param {Object} [parameters] - An object with one or more properties
  29461. * defining the material's appearance. Any property of the material
  29462. * (including any property from inherited materials) can be passed
  29463. * in here. Color values can be passed any type of value accepted
  29464. * by {@link Color#set}.
  29465. */
  29466. constructor( parameters ) {
  29467. super();
  29468. /**
  29469. * This flag can be used for type testing.
  29470. *
  29471. * @type {boolean}
  29472. * @readonly
  29473. * @default true
  29474. */
  29475. this.isMeshDepthMaterial = true;
  29476. this.type = 'MeshDepthMaterial';
  29477. /**
  29478. * Type for depth packing.
  29479. *
  29480. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29481. * @default BasicDepthPacking
  29482. */
  29483. this.depthPacking = BasicDepthPacking;
  29484. /**
  29485. * The color map. May optionally include an alpha channel, typically combined
  29486. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29487. *
  29488. * @type {?Texture}
  29489. * @default null
  29490. */
  29491. this.map = null;
  29492. /**
  29493. * The alpha map is a grayscale texture that controls the opacity across the
  29494. * surface (black: fully transparent; white: fully opaque).
  29495. *
  29496. * Only the color of the texture is used, ignoring the alpha channel if one
  29497. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29498. * when sampling this texture due to the extra bit of precision provided for
  29499. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29500. * luminance/alpha textures will also still work as expected.
  29501. *
  29502. * @type {?Texture}
  29503. * @default null
  29504. */
  29505. this.alphaMap = null;
  29506. /**
  29507. * The displacement map affects the position of the mesh's vertices. Unlike
  29508. * other maps which only affect the light and shade of the material the
  29509. * displaced vertices can cast shadows, block other objects, and otherwise
  29510. * act as real geometry. The displacement texture is an image where the value
  29511. * of each pixel (white being the highest) is mapped against, and
  29512. * repositions, the vertices of the mesh.
  29513. *
  29514. * @type {?Texture}
  29515. * @default null
  29516. */
  29517. this.displacementMap = null;
  29518. /**
  29519. * How much the displacement map affects the mesh (where black is no
  29520. * displacement, and white is maximum displacement). Without a displacement
  29521. * map set, this value is not applied.
  29522. *
  29523. * @type {number}
  29524. * @default 0
  29525. */
  29526. this.displacementScale = 1;
  29527. /**
  29528. * The offset of the displacement map's values on the mesh's vertices.
  29529. * The bias is added to the scaled sample of the displacement map.
  29530. * Without a displacement map set, this value is not applied.
  29531. *
  29532. * @type {number}
  29533. * @default 0
  29534. */
  29535. this.displacementBias = 0;
  29536. /**
  29537. * Renders the geometry as a wireframe.
  29538. *
  29539. * @type {boolean}
  29540. * @default false
  29541. */
  29542. this.wireframe = false;
  29543. /**
  29544. * Controls the thickness of the wireframe.
  29545. *
  29546. * WebGL and WebGPU ignore this property and always render
  29547. * 1 pixel wide lines.
  29548. *
  29549. * @type {number}
  29550. * @default 1
  29551. */
  29552. this.wireframeLinewidth = 1;
  29553. this.setValues( parameters );
  29554. }
  29555. copy( source ) {
  29556. super.copy( source );
  29557. this.depthPacking = source.depthPacking;
  29558. this.map = source.map;
  29559. this.alphaMap = source.alphaMap;
  29560. this.displacementMap = source.displacementMap;
  29561. this.displacementScale = source.displacementScale;
  29562. this.displacementBias = source.displacementBias;
  29563. this.wireframe = source.wireframe;
  29564. this.wireframeLinewidth = source.wireframeLinewidth;
  29565. return this;
  29566. }
  29567. }
  29568. /**
  29569. * A material used internally for implementing shadow mapping with
  29570. * point lights.
  29571. *
  29572. * Can also be used to customize the shadow casting of an object by assigning
  29573. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29574. * The following examples demonstrates this approach in order to ensure
  29575. * transparent parts of objects do no cast shadows.
  29576. *
  29577. * @augments Material
  29578. */
  29579. class MeshDistanceMaterial extends Material {
  29580. /**
  29581. * Constructs a new mesh distance material.
  29582. *
  29583. * @param {Object} [parameters] - An object with one or more properties
  29584. * defining the material's appearance. Any property of the material
  29585. * (including any property from inherited materials) can be passed
  29586. * in here. Color values can be passed any type of value accepted
  29587. * by {@link Color#set}.
  29588. */
  29589. constructor( parameters ) {
  29590. super();
  29591. /**
  29592. * This flag can be used for type testing.
  29593. *
  29594. * @type {boolean}
  29595. * @readonly
  29596. * @default true
  29597. */
  29598. this.isMeshDistanceMaterial = true;
  29599. this.type = 'MeshDistanceMaterial';
  29600. /**
  29601. * The color map. May optionally include an alpha channel, typically combined
  29602. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29603. *
  29604. * @type {?Texture}
  29605. * @default null
  29606. */
  29607. this.map = null;
  29608. /**
  29609. * The alpha map is a grayscale texture that controls the opacity across the
  29610. * surface (black: fully transparent; white: fully opaque).
  29611. *
  29612. * Only the color of the texture is used, ignoring the alpha channel if one
  29613. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29614. * when sampling this texture due to the extra bit of precision provided for
  29615. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29616. * luminance/alpha textures will also still work as expected.
  29617. *
  29618. * @type {?Texture}
  29619. * @default null
  29620. */
  29621. this.alphaMap = null;
  29622. /**
  29623. * The displacement map affects the position of the mesh's vertices. Unlike
  29624. * other maps which only affect the light and shade of the material the
  29625. * displaced vertices can cast shadows, block other objects, and otherwise
  29626. * act as real geometry. The displacement texture is an image where the value
  29627. * of each pixel (white being the highest) is mapped against, and
  29628. * repositions, the vertices of the mesh.
  29629. *
  29630. * @type {?Texture}
  29631. * @default null
  29632. */
  29633. this.displacementMap = null;
  29634. /**
  29635. * How much the displacement map affects the mesh (where black is no
  29636. * displacement, and white is maximum displacement). Without a displacement
  29637. * map set, this value is not applied.
  29638. *
  29639. * @type {number}
  29640. * @default 0
  29641. */
  29642. this.displacementScale = 1;
  29643. /**
  29644. * The offset of the displacement map's values on the mesh's vertices.
  29645. * The bias is added to the scaled sample of the displacement map.
  29646. * Without a displacement map set, this value is not applied.
  29647. *
  29648. * @type {number}
  29649. * @default 0
  29650. */
  29651. this.displacementBias = 0;
  29652. this.setValues( parameters );
  29653. }
  29654. copy( source ) {
  29655. super.copy( source );
  29656. this.map = source.map;
  29657. this.alphaMap = source.alphaMap;
  29658. this.displacementMap = source.displacementMap;
  29659. this.displacementScale = source.displacementScale;
  29660. this.displacementBias = source.displacementBias;
  29661. return this;
  29662. }
  29663. }
  29664. /**
  29665. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29666. * material color and shading.
  29667. *
  29668. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29669. * baked lighting. It will cast a shadow onto an object that receives shadows
  29670. * (and shadow clipping works), but it will not self-shadow or receive
  29671. * shadows.
  29672. *
  29673. * @augments Material
  29674. */
  29675. class MeshMatcapMaterial extends Material {
  29676. /**
  29677. * Constructs a new mesh matcap material.
  29678. *
  29679. * @param {Object} [parameters] - An object with one or more properties
  29680. * defining the material's appearance. Any property of the material
  29681. * (including any property from inherited materials) can be passed
  29682. * in here. Color values can be passed any type of value accepted
  29683. * by {@link Color#set}.
  29684. */
  29685. constructor( parameters ) {
  29686. super();
  29687. /**
  29688. * This flag can be used for type testing.
  29689. *
  29690. * @type {boolean}
  29691. * @readonly
  29692. * @default true
  29693. */
  29694. this.isMeshMatcapMaterial = true;
  29695. this.defines = { 'MATCAP': '' };
  29696. this.type = 'MeshMatcapMaterial';
  29697. /**
  29698. * Color of the material.
  29699. *
  29700. * @type {Color}
  29701. * @default (1,1,1)
  29702. */
  29703. this.color = new Color( 0xffffff ); // diffuse
  29704. /**
  29705. * The matcap map.
  29706. *
  29707. * @type {?Texture}
  29708. * @default null
  29709. */
  29710. this.matcap = null;
  29711. /**
  29712. * The color map. May optionally include an alpha channel, typically combined
  29713. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29714. * color is modulated by the diffuse `color`.
  29715. *
  29716. * @type {?Texture}
  29717. * @default null
  29718. */
  29719. this.map = null;
  29720. /**
  29721. * The texture to create a bump map. The black and white values map to the
  29722. * perceived depth in relation to the lights. Bump doesn't actually affect
  29723. * the geometry of the object, only the lighting. If a normal map is defined
  29724. * this will be ignored.
  29725. *
  29726. * @type {?Texture}
  29727. * @default null
  29728. */
  29729. this.bumpMap = null;
  29730. /**
  29731. * How much the bump map affects the material. Typical range is `[0,1]`.
  29732. *
  29733. * @type {number}
  29734. * @default 1
  29735. */
  29736. this.bumpScale = 1;
  29737. /**
  29738. * The texture to create a normal map. The RGB values affect the surface
  29739. * normal for each pixel fragment and change the way the color is lit. Normal
  29740. * maps do not change the actual shape of the surface, only the lighting. In
  29741. * case the material has a normal map authored using the left handed
  29742. * convention, the `y` component of `normalScale` should be negated to compensate
  29743. * for the different handedness.
  29744. *
  29745. * @type {?Texture}
  29746. * @default null
  29747. */
  29748. this.normalMap = null;
  29749. /**
  29750. * The type of normal map.
  29751. *
  29752. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29753. * @default TangentSpaceNormalMap
  29754. */
  29755. this.normalMapType = TangentSpaceNormalMap;
  29756. /**
  29757. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29758. *
  29759. * @type {Vector2}
  29760. * @default (1,1)
  29761. */
  29762. this.normalScale = new Vector2( 1, 1 );
  29763. /**
  29764. * The displacement map affects the position of the mesh's vertices. Unlike
  29765. * other maps which only affect the light and shade of the material the
  29766. * displaced vertices can cast shadows, block other objects, and otherwise
  29767. * act as real geometry. The displacement texture is an image where the value
  29768. * of each pixel (white being the highest) is mapped against, and
  29769. * repositions, the vertices of the mesh.
  29770. *
  29771. * @type {?Texture}
  29772. * @default null
  29773. */
  29774. this.displacementMap = null;
  29775. /**
  29776. * How much the displacement map affects the mesh (where black is no
  29777. * displacement, and white is maximum displacement). Without a displacement
  29778. * map set, this value is not applied.
  29779. *
  29780. * @type {number}
  29781. * @default 0
  29782. */
  29783. this.displacementScale = 1;
  29784. /**
  29785. * The offset of the displacement map's values on the mesh's vertices.
  29786. * The bias is added to the scaled sample of the displacement map.
  29787. * Without a displacement map set, this value is not applied.
  29788. *
  29789. * @type {number}
  29790. * @default 0
  29791. */
  29792. this.displacementBias = 0;
  29793. /**
  29794. * The alpha map is a grayscale texture that controls the opacity across the
  29795. * surface (black: fully transparent; white: fully opaque).
  29796. *
  29797. * Only the color of the texture is used, ignoring the alpha channel if one
  29798. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29799. * when sampling this texture due to the extra bit of precision provided for
  29800. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29801. * luminance/alpha textures will also still work as expected.
  29802. *
  29803. * @type {?Texture}
  29804. * @default null
  29805. */
  29806. this.alphaMap = null;
  29807. /**
  29808. * Whether the material is rendered with flat shading or not.
  29809. *
  29810. * @type {boolean}
  29811. * @default false
  29812. */
  29813. this.flatShading = false;
  29814. /**
  29815. * Whether the material is affected by fog or not.
  29816. *
  29817. * @type {boolean}
  29818. * @default true
  29819. */
  29820. this.fog = true;
  29821. this.setValues( parameters );
  29822. }
  29823. copy( source ) {
  29824. super.copy( source );
  29825. this.defines = { 'MATCAP': '' };
  29826. this.color.copy( source.color );
  29827. this.matcap = source.matcap;
  29828. this.map = source.map;
  29829. this.bumpMap = source.bumpMap;
  29830. this.bumpScale = source.bumpScale;
  29831. this.normalMap = source.normalMap;
  29832. this.normalMapType = source.normalMapType;
  29833. this.normalScale.copy( source.normalScale );
  29834. this.displacementMap = source.displacementMap;
  29835. this.displacementScale = source.displacementScale;
  29836. this.displacementBias = source.displacementBias;
  29837. this.alphaMap = source.alphaMap;
  29838. this.flatShading = source.flatShading;
  29839. this.fog = source.fog;
  29840. return this;
  29841. }
  29842. }
  29843. /**
  29844. * A material for rendering line primitives.
  29845. *
  29846. * Materials define the appearance of renderable 3D objects.
  29847. *
  29848. * ```js
  29849. * const material = new THREE.LineDashedMaterial( {
  29850. * color: 0xffffff,
  29851. * scale: 1,
  29852. * dashSize: 3,
  29853. * gapSize: 1,
  29854. * } );
  29855. * ```
  29856. *
  29857. * @augments LineBasicMaterial
  29858. */
  29859. class LineDashedMaterial extends LineBasicMaterial {
  29860. /**
  29861. * Constructs a new line dashed material.
  29862. *
  29863. * @param {Object} [parameters] - An object with one or more properties
  29864. * defining the material's appearance. Any property of the material
  29865. * (including any property from inherited materials) can be passed
  29866. * in here. Color values can be passed any type of value accepted
  29867. * by {@link Color#set}.
  29868. */
  29869. constructor( parameters ) {
  29870. super();
  29871. /**
  29872. * This flag can be used for type testing.
  29873. *
  29874. * @type {boolean}
  29875. * @readonly
  29876. * @default true
  29877. */
  29878. this.isLineDashedMaterial = true;
  29879. this.type = 'LineDashedMaterial';
  29880. /**
  29881. * The scale of the dashed part of a line.
  29882. *
  29883. * @type {number}
  29884. * @default 1
  29885. */
  29886. this.scale = 1;
  29887. /**
  29888. * The size of the dash. This is both the gap with the stroke.
  29889. *
  29890. * @type {number}
  29891. * @default 3
  29892. */
  29893. this.dashSize = 3;
  29894. /**
  29895. * The size of the gap.
  29896. *
  29897. * @type {number}
  29898. * @default 1
  29899. */
  29900. this.gapSize = 1;
  29901. this.setValues( parameters );
  29902. }
  29903. copy( source ) {
  29904. super.copy( source );
  29905. this.scale = source.scale;
  29906. this.dashSize = source.dashSize;
  29907. this.gapSize = source.gapSize;
  29908. return this;
  29909. }
  29910. }
  29911. /**
  29912. * Converts an array to a specific type.
  29913. *
  29914. * @param {TypedArray|Array} array - The array to convert.
  29915. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29916. * @return {TypedArray} The converted array.
  29917. */
  29918. function convertArray( array, type ) {
  29919. if ( ! array || array.constructor === type ) return array;
  29920. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29921. return new type( array ); // create typed array
  29922. }
  29923. return Array.prototype.slice.call( array ); // create Array
  29924. }
  29925. /**
  29926. * Returns `true` if the given object is a typed array.
  29927. *
  29928. * @param {any} object - The object to check.
  29929. * @return {boolean} Whether the given object is a typed array.
  29930. */
  29931. function isTypedArray( object ) {
  29932. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29933. }
  29934. /**
  29935. * Returns an array by which times and values can be sorted.
  29936. *
  29937. * @param {Array<number>} times - The keyframe time values.
  29938. * @return {Array<number>} The array.
  29939. */
  29940. function getKeyframeOrder( times ) {
  29941. function compareTime( i, j ) {
  29942. return times[ i ] - times[ j ];
  29943. }
  29944. const n = times.length;
  29945. const result = new Array( n );
  29946. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29947. result.sort( compareTime );
  29948. return result;
  29949. }
  29950. /**
  29951. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29952. *
  29953. * @param {Array<number>} values - The values to sort.
  29954. * @param {number} stride - The stride.
  29955. * @param {Array<number>} order - The sort order.
  29956. * @return {Array<number>} The sorted values.
  29957. */
  29958. function sortedArray( values, stride, order ) {
  29959. const nValues = values.length;
  29960. const result = new values.constructor( nValues );
  29961. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29962. const srcOffset = order[ i ] * stride;
  29963. for ( let j = 0; j !== stride; ++ j ) {
  29964. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29965. }
  29966. }
  29967. return result;
  29968. }
  29969. /**
  29970. * Used for parsing AOS keyframe formats.
  29971. *
  29972. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29973. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29974. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29975. * @param {string} valuePropertyName - The name of the property to use.
  29976. */
  29977. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29978. let i = 1, key = jsonKeys[ 0 ];
  29979. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29980. key = jsonKeys[ i ++ ];
  29981. }
  29982. if ( key === undefined ) return; // no data
  29983. let value = key[ valuePropertyName ];
  29984. if ( value === undefined ) return; // no data
  29985. if ( Array.isArray( value ) ) {
  29986. do {
  29987. value = key[ valuePropertyName ];
  29988. if ( value !== undefined ) {
  29989. times.push( key.time );
  29990. values.push( ...value ); // push all elements
  29991. }
  29992. key = jsonKeys[ i ++ ];
  29993. } while ( key !== undefined );
  29994. } else if ( value.toArray !== undefined ) {
  29995. // ...assume THREE.Math-ish
  29996. do {
  29997. value = key[ valuePropertyName ];
  29998. if ( value !== undefined ) {
  29999. times.push( key.time );
  30000. value.toArray( values, values.length );
  30001. }
  30002. key = jsonKeys[ i ++ ];
  30003. } while ( key !== undefined );
  30004. } else {
  30005. // otherwise push as-is
  30006. do {
  30007. value = key[ valuePropertyName ];
  30008. if ( value !== undefined ) {
  30009. times.push( key.time );
  30010. values.push( value );
  30011. }
  30012. key = jsonKeys[ i ++ ];
  30013. } while ( key !== undefined );
  30014. }
  30015. }
  30016. /**
  30017. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30018. *
  30019. * @param {AnimationClip} sourceClip - The values to sort.
  30020. * @param {string} name - The name of the clip.
  30021. * @param {number} startFrame - The start frame.
  30022. * @param {number} endFrame - The end frame.
  30023. * @param {number} [fps=30] - The FPS.
  30024. * @return {AnimationClip} The new sub clip.
  30025. */
  30026. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30027. const clip = sourceClip.clone();
  30028. clip.name = name;
  30029. const tracks = [];
  30030. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30031. const track = clip.tracks[ i ];
  30032. const valueSize = track.getValueSize();
  30033. const times = [];
  30034. const values = [];
  30035. for ( let j = 0; j < track.times.length; ++ j ) {
  30036. const frame = track.times[ j ] * fps;
  30037. if ( frame < startFrame || frame >= endFrame ) continue;
  30038. times.push( track.times[ j ] );
  30039. for ( let k = 0; k < valueSize; ++ k ) {
  30040. values.push( track.values[ j * valueSize + k ] );
  30041. }
  30042. }
  30043. if ( times.length === 0 ) continue;
  30044. track.times = convertArray( times, track.times.constructor );
  30045. track.values = convertArray( values, track.values.constructor );
  30046. tracks.push( track );
  30047. }
  30048. clip.tracks = tracks;
  30049. // find minimum .times value across all tracks in the trimmed clip
  30050. let minStartTime = Infinity;
  30051. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30052. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30053. minStartTime = clip.tracks[ i ].times[ 0 ];
  30054. }
  30055. }
  30056. // shift all tracks such that clip begins at t=0
  30057. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30058. clip.tracks[ i ].shift( -1 * minStartTime );
  30059. }
  30060. clip.resetDuration();
  30061. return clip;
  30062. }
  30063. /**
  30064. * Converts the keyframes of the given animation clip to an additive format.
  30065. *
  30066. * @param {AnimationClip} targetClip - The clip to make additive.
  30067. * @param {number} [referenceFrame=0] - The reference frame.
  30068. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30069. * @param {number} [fps=30] - The FPS.
  30070. * @return {AnimationClip} The updated clip which is now additive.
  30071. */
  30072. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30073. if ( fps <= 0 ) fps = 30;
  30074. const numTracks = referenceClip.tracks.length;
  30075. const referenceTime = referenceFrame / fps;
  30076. // Make each track's values relative to the values at the reference frame
  30077. for ( let i = 0; i < numTracks; ++ i ) {
  30078. const referenceTrack = referenceClip.tracks[ i ];
  30079. const referenceTrackType = referenceTrack.ValueTypeName;
  30080. // Skip this track if it's non-numeric
  30081. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30082. // Find the track in the target clip whose name and type matches the reference track
  30083. const targetTrack = targetClip.tracks.find( function ( track ) {
  30084. return track.name === referenceTrack.name
  30085. && track.ValueTypeName === referenceTrackType;
  30086. } );
  30087. if ( targetTrack === undefined ) continue;
  30088. let referenceOffset = 0;
  30089. const referenceValueSize = referenceTrack.getValueSize();
  30090. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30091. referenceOffset = referenceValueSize / 3;
  30092. }
  30093. let targetOffset = 0;
  30094. const targetValueSize = targetTrack.getValueSize();
  30095. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30096. targetOffset = targetValueSize / 3;
  30097. }
  30098. const lastIndex = referenceTrack.times.length - 1;
  30099. let referenceValue;
  30100. // Find the value to subtract out of the track
  30101. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30102. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30103. const startIndex = referenceOffset;
  30104. const endIndex = referenceValueSize - referenceOffset;
  30105. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30106. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30107. // Reference frame is after the last keyframe, so just use the last keyframe
  30108. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30109. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30110. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30111. } else {
  30112. // Interpolate to the reference value
  30113. const interpolant = referenceTrack.createInterpolant();
  30114. const startIndex = referenceOffset;
  30115. const endIndex = referenceValueSize - referenceOffset;
  30116. interpolant.evaluate( referenceTime );
  30117. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30118. }
  30119. // Conjugate the quaternion
  30120. if ( referenceTrackType === 'quaternion' ) {
  30121. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30122. referenceQuat.toArray( referenceValue );
  30123. }
  30124. // Subtract the reference value from all of the track values
  30125. const numTimes = targetTrack.times.length;
  30126. for ( let j = 0; j < numTimes; ++ j ) {
  30127. const valueStart = j * targetValueSize + targetOffset;
  30128. if ( referenceTrackType === 'quaternion' ) {
  30129. // Multiply the conjugate for quaternion track types
  30130. Quaternion.multiplyQuaternionsFlat(
  30131. targetTrack.values,
  30132. valueStart,
  30133. referenceValue,
  30134. 0,
  30135. targetTrack.values,
  30136. valueStart
  30137. );
  30138. } else {
  30139. const valueEnd = targetValueSize - targetOffset * 2;
  30140. // Subtract each value for all other numeric track types
  30141. for ( let k = 0; k < valueEnd; ++ k ) {
  30142. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30143. }
  30144. }
  30145. }
  30146. }
  30147. targetClip.blendMode = AdditiveAnimationBlendMode;
  30148. return targetClip;
  30149. }
  30150. /**
  30151. * A class with various methods to assist with animations.
  30152. *
  30153. * @hideconstructor
  30154. */
  30155. class AnimationUtils {
  30156. /**
  30157. * Converts an array to a specific type
  30158. *
  30159. * @static
  30160. * @param {TypedArray|Array} array - The array to convert.
  30161. * @param {TypedArray.constructor} type - The constructor of a type array.
  30162. * @return {TypedArray} The converted array
  30163. */
  30164. static convertArray( array, type ) {
  30165. return convertArray( array, type );
  30166. }
  30167. /**
  30168. * Returns `true` if the given object is a typed array.
  30169. *
  30170. * @static
  30171. * @param {any} object - The object to check.
  30172. * @return {boolean} Whether the given object is a typed array.
  30173. */
  30174. static isTypedArray( object ) {
  30175. return isTypedArray( object );
  30176. }
  30177. /**
  30178. * Returns an array by which times and values can be sorted.
  30179. *
  30180. * @static
  30181. * @param {Array<number>} times - The keyframe time values.
  30182. * @return {Array<number>} The array.
  30183. */
  30184. static getKeyframeOrder( times ) {
  30185. return getKeyframeOrder( times );
  30186. }
  30187. /**
  30188. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30189. *
  30190. * @static
  30191. * @param {Array<number>} values - The values to sort.
  30192. * @param {number} stride - The stride.
  30193. * @param {Array<number>} order - The sort order.
  30194. * @return {Array<number>} The sorted values.
  30195. */
  30196. static sortedArray( values, stride, order ) {
  30197. return sortedArray( values, stride, order );
  30198. }
  30199. /**
  30200. * Used for parsing AOS keyframe formats.
  30201. *
  30202. * @static
  30203. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30204. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30205. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30206. * @param {string} valuePropertyName - The name of the property to use.
  30207. */
  30208. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30209. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30210. }
  30211. /**
  30212. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30213. *
  30214. * @static
  30215. * @param {AnimationClip} sourceClip - The values to sort.
  30216. * @param {string} name - The name of the clip.
  30217. * @param {number} startFrame - The start frame.
  30218. * @param {number} endFrame - The end frame.
  30219. * @param {number} [fps=30] - The FPS.
  30220. * @return {AnimationClip} The new sub clip.
  30221. */
  30222. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30223. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30224. }
  30225. /**
  30226. * Converts the keyframes of the given animation clip to an additive format.
  30227. *
  30228. * @static
  30229. * @param {AnimationClip} targetClip - The clip to make additive.
  30230. * @param {number} [referenceFrame=0] - The reference frame.
  30231. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30232. * @param {number} [fps=30] - The FPS.
  30233. * @return {AnimationClip} The updated clip which is now additive.
  30234. */
  30235. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30236. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30237. }
  30238. }
  30239. /**
  30240. * Abstract base class of interpolants over parametric samples.
  30241. *
  30242. * The parameter domain is one dimensional, typically the time or a path
  30243. * along a curve defined by the data.
  30244. *
  30245. * The sample values can have any dimensionality and derived classes may
  30246. * apply special interpretations to the data.
  30247. *
  30248. * This class provides the interval seek in a Template Method, deferring
  30249. * the actual interpolation to derived classes.
  30250. *
  30251. * Time complexity is O(1) for linear access crossing at most two points
  30252. * and O(log N) for random access, where N is the number of positions.
  30253. *
  30254. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30255. *
  30256. * @abstract
  30257. */
  30258. class Interpolant {
  30259. /**
  30260. * Constructs a new interpolant.
  30261. *
  30262. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30263. * @param {TypedArray} sampleValues - The sample values.
  30264. * @param {number} sampleSize - The sample size
  30265. * @param {TypedArray} [resultBuffer] - The result buffer.
  30266. */
  30267. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30268. /**
  30269. * The parameter positions.
  30270. *
  30271. * @type {TypedArray}
  30272. */
  30273. this.parameterPositions = parameterPositions;
  30274. /**
  30275. * A cache index.
  30276. *
  30277. * @private
  30278. * @type {number}
  30279. * @default 0
  30280. */
  30281. this._cachedIndex = 0;
  30282. /**
  30283. * The result buffer.
  30284. *
  30285. * @type {TypedArray}
  30286. */
  30287. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30288. /**
  30289. * The sample values.
  30290. *
  30291. * @type {TypedArray}
  30292. */
  30293. this.sampleValues = sampleValues;
  30294. /**
  30295. * The value size.
  30296. *
  30297. * @type {TypedArray}
  30298. */
  30299. this.valueSize = sampleSize;
  30300. /**
  30301. * The interpolation settings.
  30302. *
  30303. * @type {?Object}
  30304. * @default null
  30305. */
  30306. this.settings = null;
  30307. /**
  30308. * The default settings object.
  30309. *
  30310. * @type {Object}
  30311. */
  30312. this.DefaultSettings_ = {};
  30313. }
  30314. /**
  30315. * Evaluate the interpolant at position `t`.
  30316. *
  30317. * @param {number} t - The interpolation factor.
  30318. * @return {TypedArray} The result buffer.
  30319. */
  30320. evaluate( t ) {
  30321. const pp = this.parameterPositions;
  30322. let i1 = this._cachedIndex,
  30323. t1 = pp[ i1 ],
  30324. t0 = pp[ i1 - 1 ];
  30325. validate_interval: {
  30326. seek: {
  30327. let right;
  30328. linear_scan: {
  30329. //- See http://jsperf.com/comparison-to-undefined/3
  30330. //- slower code:
  30331. //-
  30332. //- if ( t >= t1 || t1 === undefined ) {
  30333. forward_scan: if ( ! ( t < t1 ) ) {
  30334. for ( let giveUpAt = i1 + 2; ; ) {
  30335. if ( t1 === undefined ) {
  30336. if ( t < t0 ) break forward_scan;
  30337. // after end
  30338. i1 = pp.length;
  30339. this._cachedIndex = i1;
  30340. return this.copySampleValue_( i1 - 1 );
  30341. }
  30342. if ( i1 === giveUpAt ) break; // this loop
  30343. t0 = t1;
  30344. t1 = pp[ ++ i1 ];
  30345. if ( t < t1 ) {
  30346. // we have arrived at the sought interval
  30347. break seek;
  30348. }
  30349. }
  30350. // prepare binary search on the right side of the index
  30351. right = pp.length;
  30352. break linear_scan;
  30353. }
  30354. //- slower code:
  30355. //- if ( t < t0 || t0 === undefined ) {
  30356. if ( ! ( t >= t0 ) ) {
  30357. // looping?
  30358. const t1global = pp[ 1 ];
  30359. if ( t < t1global ) {
  30360. i1 = 2; // + 1, using the scan for the details
  30361. t0 = t1global;
  30362. }
  30363. // linear reverse scan
  30364. for ( let giveUpAt = i1 - 2; ; ) {
  30365. if ( t0 === undefined ) {
  30366. // before start
  30367. this._cachedIndex = 0;
  30368. return this.copySampleValue_( 0 );
  30369. }
  30370. if ( i1 === giveUpAt ) break; // this loop
  30371. t1 = t0;
  30372. t0 = pp[ -- i1 - 1 ];
  30373. if ( t >= t0 ) {
  30374. // we have arrived at the sought interval
  30375. break seek;
  30376. }
  30377. }
  30378. // prepare binary search on the left side of the index
  30379. right = i1;
  30380. i1 = 0;
  30381. break linear_scan;
  30382. }
  30383. // the interval is valid
  30384. break validate_interval;
  30385. } // linear scan
  30386. // binary search
  30387. while ( i1 < right ) {
  30388. const mid = ( i1 + right ) >>> 1;
  30389. if ( t < pp[ mid ] ) {
  30390. right = mid;
  30391. } else {
  30392. i1 = mid + 1;
  30393. }
  30394. }
  30395. t1 = pp[ i1 ];
  30396. t0 = pp[ i1 - 1 ];
  30397. // check boundary cases, again
  30398. if ( t0 === undefined ) {
  30399. this._cachedIndex = 0;
  30400. return this.copySampleValue_( 0 );
  30401. }
  30402. if ( t1 === undefined ) {
  30403. i1 = pp.length;
  30404. this._cachedIndex = i1;
  30405. return this.copySampleValue_( i1 - 1 );
  30406. }
  30407. } // seek
  30408. this._cachedIndex = i1;
  30409. this.intervalChanged_( i1, t0, t1 );
  30410. } // validate_interval
  30411. return this.interpolate_( i1, t0, t, t1 );
  30412. }
  30413. /**
  30414. * Returns the interpolation settings.
  30415. *
  30416. * @return {Object} The interpolation settings.
  30417. */
  30418. getSettings_() {
  30419. return this.settings || this.DefaultSettings_;
  30420. }
  30421. /**
  30422. * Copies a sample value to the result buffer.
  30423. *
  30424. * @param {number} index - An index into the sample value buffer.
  30425. * @return {TypedArray} The result buffer.
  30426. */
  30427. copySampleValue_( index ) {
  30428. // copies a sample value to the result buffer
  30429. const result = this.resultBuffer,
  30430. values = this.sampleValues,
  30431. stride = this.valueSize,
  30432. offset = index * stride;
  30433. for ( let i = 0; i !== stride; ++ i ) {
  30434. result[ i ] = values[ offset + i ];
  30435. }
  30436. return result;
  30437. }
  30438. /**
  30439. * Copies a sample value to the result buffer.
  30440. *
  30441. * @abstract
  30442. * @param {number} i1 - An index into the sample value buffer.
  30443. * @param {number} t0 - The previous interpolation factor.
  30444. * @param {number} t - The current interpolation factor.
  30445. * @param {number} t1 - The next interpolation factor.
  30446. * @return {TypedArray} The result buffer.
  30447. */
  30448. interpolate_( /* i1, t0, t, t1 */ ) {
  30449. throw new Error( 'call to abstract method' );
  30450. // implementations shall return this.resultBuffer
  30451. }
  30452. /**
  30453. * Optional method that is executed when the interval has changed.
  30454. *
  30455. * @param {number} i1 - An index into the sample value buffer.
  30456. * @param {number} t0 - The previous interpolation factor.
  30457. * @param {number} t - The current interpolation factor.
  30458. */
  30459. intervalChanged_( /* i1, t0, t1 */ ) {
  30460. // empty
  30461. }
  30462. }
  30463. /**
  30464. * Fast and simple cubic spline interpolant.
  30465. *
  30466. * It was derived from a Hermitian construction setting the first derivative
  30467. * at each sample position to the linear slope between neighboring positions
  30468. * over their parameter interval.
  30469. *
  30470. * @augments Interpolant
  30471. */
  30472. class CubicInterpolant extends Interpolant {
  30473. /**
  30474. * Constructs a new cubic interpolant.
  30475. *
  30476. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30477. * @param {TypedArray} sampleValues - The sample values.
  30478. * @param {number} sampleSize - The sample size
  30479. * @param {TypedArray} [resultBuffer] - The result buffer.
  30480. */
  30481. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30482. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30483. this._weightPrev = -0;
  30484. this._offsetPrev = -0;
  30485. this._weightNext = -0;
  30486. this._offsetNext = -0;
  30487. this.DefaultSettings_ = {
  30488. endingStart: ZeroCurvatureEnding,
  30489. endingEnd: ZeroCurvatureEnding
  30490. };
  30491. }
  30492. intervalChanged_( i1, t0, t1 ) {
  30493. const pp = this.parameterPositions;
  30494. let iPrev = i1 - 2,
  30495. iNext = i1 + 1,
  30496. tPrev = pp[ iPrev ],
  30497. tNext = pp[ iNext ];
  30498. if ( tPrev === undefined ) {
  30499. switch ( this.getSettings_().endingStart ) {
  30500. case ZeroSlopeEnding:
  30501. // f'(t0) = 0
  30502. iPrev = i1;
  30503. tPrev = 2 * t0 - t1;
  30504. break;
  30505. case WrapAroundEnding:
  30506. // use the other end of the curve
  30507. iPrev = pp.length - 2;
  30508. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30509. break;
  30510. default: // ZeroCurvatureEnding
  30511. // f''(t0) = 0 a.k.a. Natural Spline
  30512. iPrev = i1;
  30513. tPrev = t1;
  30514. }
  30515. }
  30516. if ( tNext === undefined ) {
  30517. switch ( this.getSettings_().endingEnd ) {
  30518. case ZeroSlopeEnding:
  30519. // f'(tN) = 0
  30520. iNext = i1;
  30521. tNext = 2 * t1 - t0;
  30522. break;
  30523. case WrapAroundEnding:
  30524. // use the other end of the curve
  30525. iNext = 1;
  30526. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30527. break;
  30528. default: // ZeroCurvatureEnding
  30529. // f''(tN) = 0, a.k.a. Natural Spline
  30530. iNext = i1 - 1;
  30531. tNext = t0;
  30532. }
  30533. }
  30534. const halfDt = ( t1 - t0 ) * 0.5,
  30535. stride = this.valueSize;
  30536. this._weightPrev = halfDt / ( t0 - tPrev );
  30537. this._weightNext = halfDt / ( tNext - t1 );
  30538. this._offsetPrev = iPrev * stride;
  30539. this._offsetNext = iNext * stride;
  30540. }
  30541. interpolate_( i1, t0, t, t1 ) {
  30542. const result = this.resultBuffer,
  30543. values = this.sampleValues,
  30544. stride = this.valueSize,
  30545. o1 = i1 * stride, o0 = o1 - stride,
  30546. oP = this._offsetPrev, oN = this._offsetNext,
  30547. wP = this._weightPrev, wN = this._weightNext,
  30548. p = ( t - t0 ) / ( t1 - t0 ),
  30549. pp = p * p,
  30550. ppp = pp * p;
  30551. // evaluate polynomials
  30552. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30553. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30554. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30555. const sN = wN * ppp - wN * pp;
  30556. // combine data linearly
  30557. for ( let i = 0; i !== stride; ++ i ) {
  30558. result[ i ] =
  30559. sP * values[ oP + i ] +
  30560. s0 * values[ o0 + i ] +
  30561. s1 * values[ o1 + i ] +
  30562. sN * values[ oN + i ];
  30563. }
  30564. return result;
  30565. }
  30566. }
  30567. /**
  30568. * A basic linear interpolant.
  30569. *
  30570. * @augments Interpolant
  30571. */
  30572. class LinearInterpolant extends Interpolant {
  30573. /**
  30574. * Constructs a new linear interpolant.
  30575. *
  30576. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30577. * @param {TypedArray} sampleValues - The sample values.
  30578. * @param {number} sampleSize - The sample size
  30579. * @param {TypedArray} [resultBuffer] - The result buffer.
  30580. */
  30581. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30582. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30583. }
  30584. interpolate_( i1, t0, t, t1 ) {
  30585. const result = this.resultBuffer,
  30586. values = this.sampleValues,
  30587. stride = this.valueSize,
  30588. offset1 = i1 * stride,
  30589. offset0 = offset1 - stride,
  30590. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30591. weight0 = 1 - weight1;
  30592. for ( let i = 0; i !== stride; ++ i ) {
  30593. result[ i ] =
  30594. values[ offset0 + i ] * weight0 +
  30595. values[ offset1 + i ] * weight1;
  30596. }
  30597. return result;
  30598. }
  30599. }
  30600. /**
  30601. * Interpolant that evaluates to the sample value at the position preceding
  30602. * the parameter.
  30603. *
  30604. * @augments Interpolant
  30605. */
  30606. class DiscreteInterpolant extends Interpolant {
  30607. /**
  30608. * Constructs a new discrete interpolant.
  30609. *
  30610. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30611. * @param {TypedArray} sampleValues - The sample values.
  30612. * @param {number} sampleSize - The sample size
  30613. * @param {TypedArray} [resultBuffer] - The result buffer.
  30614. */
  30615. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30616. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30617. }
  30618. interpolate_( i1 /*, t0, t, t1 */ ) {
  30619. return this.copySampleValue_( i1 - 1 );
  30620. }
  30621. }
  30622. /**
  30623. * Represents s a timed sequence of keyframes, which are composed of lists of
  30624. * times and related values, and which are used to animate a specific property
  30625. * of an object.
  30626. */
  30627. class KeyframeTrack {
  30628. /**
  30629. * Constructs a new keyframe track.
  30630. *
  30631. * @param {string} name - The keyframe track's name.
  30632. * @param {Array<number>} times - A list of keyframe times.
  30633. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30634. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30635. */
  30636. constructor( name, times, values, interpolation ) {
  30637. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30638. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30639. /**
  30640. * The track's name can refer to morph targets or bones or
  30641. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30642. * for the forms of strings that can be parsed for property binding.
  30643. *
  30644. * @type {string}
  30645. */
  30646. this.name = name;
  30647. /**
  30648. * The keyframe times.
  30649. *
  30650. * @type {Float32Array}
  30651. */
  30652. this.times = convertArray( times, this.TimeBufferType );
  30653. /**
  30654. * The keyframe values.
  30655. *
  30656. * @type {Float32Array}
  30657. */
  30658. this.values = convertArray( values, this.ValueBufferType );
  30659. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30660. }
  30661. /**
  30662. * Converts the keyframe track to JSON.
  30663. *
  30664. * @static
  30665. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30666. * @return {Object} The serialized keyframe track as JSON.
  30667. */
  30668. static toJSON( track ) {
  30669. const trackType = track.constructor;
  30670. let json;
  30671. // derived classes can define a static toJSON method
  30672. if ( trackType.toJSON !== this.toJSON ) {
  30673. json = trackType.toJSON( track );
  30674. } else {
  30675. // by default, we assume the data can be serialized as-is
  30676. json = {
  30677. 'name': track.name,
  30678. 'times': convertArray( track.times, Array ),
  30679. 'values': convertArray( track.values, Array )
  30680. };
  30681. const interpolation = track.getInterpolation();
  30682. if ( interpolation !== track.DefaultInterpolation ) {
  30683. json.interpolation = interpolation;
  30684. }
  30685. }
  30686. json.type = track.ValueTypeName; // mandatory
  30687. return json;
  30688. }
  30689. /**
  30690. * Factory method for creating a new discrete interpolant.
  30691. *
  30692. * @static
  30693. * @param {TypedArray} [result] - The result buffer.
  30694. * @return {DiscreteInterpolant} The new interpolant.
  30695. */
  30696. InterpolantFactoryMethodDiscrete( result ) {
  30697. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30698. }
  30699. /**
  30700. * Factory method for creating a new linear interpolant.
  30701. *
  30702. * @static
  30703. * @param {TypedArray} [result] - The result buffer.
  30704. * @return {LinearInterpolant} The new interpolant.
  30705. */
  30706. InterpolantFactoryMethodLinear( result ) {
  30707. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30708. }
  30709. /**
  30710. * Factory method for creating a new smooth interpolant.
  30711. *
  30712. * @static
  30713. * @param {TypedArray} [result] - The result buffer.
  30714. * @return {CubicInterpolant} The new interpolant.
  30715. */
  30716. InterpolantFactoryMethodSmooth( result ) {
  30717. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30718. }
  30719. /**
  30720. * Defines the interpolation factor method for this keyframe track.
  30721. *
  30722. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30723. * @return {KeyframeTrack} A reference to this keyframe track.
  30724. */
  30725. setInterpolation( interpolation ) {
  30726. let factoryMethod;
  30727. switch ( interpolation ) {
  30728. case InterpolateDiscrete:
  30729. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30730. break;
  30731. case InterpolateLinear:
  30732. factoryMethod = this.InterpolantFactoryMethodLinear;
  30733. break;
  30734. case InterpolateSmooth:
  30735. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30736. break;
  30737. }
  30738. if ( factoryMethod === undefined ) {
  30739. const message = 'unsupported interpolation for ' +
  30740. this.ValueTypeName + ' keyframe track named ' + this.name;
  30741. if ( this.createInterpolant === undefined ) {
  30742. // fall back to default, unless the default itself is messed up
  30743. if ( interpolation !== this.DefaultInterpolation ) {
  30744. this.setInterpolation( this.DefaultInterpolation );
  30745. } else {
  30746. throw new Error( message ); // fatal, in this case
  30747. }
  30748. }
  30749. console.warn( 'THREE.KeyframeTrack:', message );
  30750. return this;
  30751. }
  30752. this.createInterpolant = factoryMethod;
  30753. return this;
  30754. }
  30755. /**
  30756. * Returns the current interpolation type.
  30757. *
  30758. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30759. */
  30760. getInterpolation() {
  30761. switch ( this.createInterpolant ) {
  30762. case this.InterpolantFactoryMethodDiscrete:
  30763. return InterpolateDiscrete;
  30764. case this.InterpolantFactoryMethodLinear:
  30765. return InterpolateLinear;
  30766. case this.InterpolantFactoryMethodSmooth:
  30767. return InterpolateSmooth;
  30768. }
  30769. }
  30770. /**
  30771. * Returns the value size.
  30772. *
  30773. * @return {number} The value size.
  30774. */
  30775. getValueSize() {
  30776. return this.values.length / this.times.length;
  30777. }
  30778. /**
  30779. * Moves all keyframes either forward or backward in time.
  30780. *
  30781. * @param {number} timeOffset - The offset to move the time values.
  30782. * @return {KeyframeTrack} A reference to this keyframe track.
  30783. */
  30784. shift( timeOffset ) {
  30785. if ( timeOffset !== 0.0 ) {
  30786. const times = this.times;
  30787. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30788. times[ i ] += timeOffset;
  30789. }
  30790. }
  30791. return this;
  30792. }
  30793. /**
  30794. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30795. *
  30796. * @param {number} timeScale - The time scale.
  30797. * @return {KeyframeTrack} A reference to this keyframe track.
  30798. */
  30799. scale( timeScale ) {
  30800. if ( timeScale !== 1.0 ) {
  30801. const times = this.times;
  30802. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30803. times[ i ] *= timeScale;
  30804. }
  30805. }
  30806. return this;
  30807. }
  30808. /**
  30809. * Removes keyframes before and after animation without changing any values within the defined time range.
  30810. *
  30811. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30812. * keys this will change their values
  30813. *
  30814. * @param {number} startTime - The start time.
  30815. * @param {number} endTime - The end time.
  30816. * @return {KeyframeTrack} A reference to this keyframe track.
  30817. */
  30818. trim( startTime, endTime ) {
  30819. const times = this.times,
  30820. nKeys = times.length;
  30821. let from = 0,
  30822. to = nKeys - 1;
  30823. while ( from !== nKeys && times[ from ] < startTime ) {
  30824. ++ from;
  30825. }
  30826. while ( to !== -1 && times[ to ] > endTime ) {
  30827. -- to;
  30828. }
  30829. ++ to; // inclusive -> exclusive bound
  30830. if ( from !== 0 || to !== nKeys ) {
  30831. // empty tracks are forbidden, so keep at least one keyframe
  30832. if ( from >= to ) {
  30833. to = Math.max( to, 1 );
  30834. from = to - 1;
  30835. }
  30836. const stride = this.getValueSize();
  30837. this.times = times.slice( from, to );
  30838. this.values = this.values.slice( from * stride, to * stride );
  30839. }
  30840. return this;
  30841. }
  30842. /**
  30843. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30844. * are valid.
  30845. *
  30846. * @return {boolean} Whether the keyframes are valid or not.
  30847. */
  30848. validate() {
  30849. let valid = true;
  30850. const valueSize = this.getValueSize();
  30851. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30852. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30853. valid = false;
  30854. }
  30855. const times = this.times,
  30856. values = this.values,
  30857. nKeys = times.length;
  30858. if ( nKeys === 0 ) {
  30859. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30860. valid = false;
  30861. }
  30862. let prevTime = null;
  30863. for ( let i = 0; i !== nKeys; i ++ ) {
  30864. const currTime = times[ i ];
  30865. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30866. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30867. valid = false;
  30868. break;
  30869. }
  30870. if ( prevTime !== null && prevTime > currTime ) {
  30871. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30872. valid = false;
  30873. break;
  30874. }
  30875. prevTime = currTime;
  30876. }
  30877. if ( values !== undefined ) {
  30878. if ( isTypedArray( values ) ) {
  30879. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30880. const value = values[ i ];
  30881. if ( isNaN( value ) ) {
  30882. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30883. valid = false;
  30884. break;
  30885. }
  30886. }
  30887. }
  30888. }
  30889. return valid;
  30890. }
  30891. /**
  30892. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30893. * common in morph target sequences).
  30894. *
  30895. * @return {AnimationClip} A reference to this animation clip.
  30896. */
  30897. optimize() {
  30898. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30899. // times or values may be shared with other tracks, so overwriting is unsafe
  30900. const times = this.times.slice(),
  30901. values = this.values.slice(),
  30902. stride = this.getValueSize(),
  30903. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30904. lastIndex = times.length - 1;
  30905. let writeIndex = 1;
  30906. for ( let i = 1; i < lastIndex; ++ i ) {
  30907. let keep = false;
  30908. const time = times[ i ];
  30909. const timeNext = times[ i + 1 ];
  30910. // remove adjacent keyframes scheduled at the same time
  30911. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30912. if ( ! smoothInterpolation ) {
  30913. // remove unnecessary keyframes same as their neighbors
  30914. const offset = i * stride,
  30915. offsetP = offset - stride,
  30916. offsetN = offset + stride;
  30917. for ( let j = 0; j !== stride; ++ j ) {
  30918. const value = values[ offset + j ];
  30919. if ( value !== values[ offsetP + j ] ||
  30920. value !== values[ offsetN + j ] ) {
  30921. keep = true;
  30922. break;
  30923. }
  30924. }
  30925. } else {
  30926. keep = true;
  30927. }
  30928. }
  30929. // in-place compaction
  30930. if ( keep ) {
  30931. if ( i !== writeIndex ) {
  30932. times[ writeIndex ] = times[ i ];
  30933. const readOffset = i * stride,
  30934. writeOffset = writeIndex * stride;
  30935. for ( let j = 0; j !== stride; ++ j ) {
  30936. values[ writeOffset + j ] = values[ readOffset + j ];
  30937. }
  30938. }
  30939. ++ writeIndex;
  30940. }
  30941. }
  30942. // flush last keyframe (compaction looks ahead)
  30943. if ( lastIndex > 0 ) {
  30944. times[ writeIndex ] = times[ lastIndex ];
  30945. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30946. values[ writeOffset + j ] = values[ readOffset + j ];
  30947. }
  30948. ++ writeIndex;
  30949. }
  30950. if ( writeIndex !== times.length ) {
  30951. this.times = times.slice( 0, writeIndex );
  30952. this.values = values.slice( 0, writeIndex * stride );
  30953. } else {
  30954. this.times = times;
  30955. this.values = values;
  30956. }
  30957. return this;
  30958. }
  30959. /**
  30960. * Returns a new keyframe track with copied values from this instance.
  30961. *
  30962. * @return {KeyframeTrack} A clone of this instance.
  30963. */
  30964. clone() {
  30965. const times = this.times.slice();
  30966. const values = this.values.slice();
  30967. const TypedKeyframeTrack = this.constructor;
  30968. const track = new TypedKeyframeTrack( this.name, times, values );
  30969. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30970. track.createInterpolant = this.createInterpolant;
  30971. return track;
  30972. }
  30973. }
  30974. /**
  30975. * The value type name.
  30976. *
  30977. * @type {String}
  30978. * @default ''
  30979. */
  30980. KeyframeTrack.prototype.ValueTypeName = '';
  30981. /**
  30982. * The time buffer type of this keyframe track.
  30983. *
  30984. * @type {TypedArray|Array}
  30985. * @default Float32Array.constructor
  30986. */
  30987. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30988. /**
  30989. * The value buffer type of this keyframe track.
  30990. *
  30991. * @type {TypedArray|Array}
  30992. * @default Float32Array.constructor
  30993. */
  30994. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30995. /**
  30996. * The default interpolation type of this keyframe track.
  30997. *
  30998. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30999. * @default InterpolateLinear
  31000. */
  31001. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31002. /**
  31003. * A track for boolean keyframe values.
  31004. *
  31005. * @augments KeyframeTrack
  31006. */
  31007. class BooleanKeyframeTrack extends KeyframeTrack {
  31008. /**
  31009. * Constructs a new boolean keyframe track.
  31010. *
  31011. * This keyframe track type has no `interpolation` parameter because the
  31012. * interpolation is always discrete.
  31013. *
  31014. * @param {string} name - The keyframe track's name.
  31015. * @param {Array<number>} times - A list of keyframe times.
  31016. * @param {Array<boolean>} values - A list of keyframe values.
  31017. */
  31018. constructor( name, times, values ) {
  31019. super( name, times, values );
  31020. }
  31021. }
  31022. /**
  31023. * The value type name.
  31024. *
  31025. * @type {String}
  31026. * @default 'bool'
  31027. */
  31028. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31029. /**
  31030. * The value buffer type of this keyframe track.
  31031. *
  31032. * @type {TypedArray|Array}
  31033. * @default Array.constructor
  31034. */
  31035. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31036. /**
  31037. * The default interpolation type of this keyframe track.
  31038. *
  31039. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31040. * @default InterpolateDiscrete
  31041. */
  31042. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31043. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31044. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31045. /**
  31046. * A track for color keyframe values.
  31047. *
  31048. * @augments KeyframeTrack
  31049. */
  31050. class ColorKeyframeTrack extends KeyframeTrack {
  31051. /**
  31052. * Constructs a new color keyframe track.
  31053. *
  31054. * @param {string} name - The keyframe track's name.
  31055. * @param {Array<number>} times - A list of keyframe times.
  31056. * @param {Array<number>} values - A list of keyframe values.
  31057. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31058. */
  31059. constructor( name, times, values, interpolation ) {
  31060. super( name, times, values, interpolation );
  31061. }
  31062. }
  31063. /**
  31064. * The value type name.
  31065. *
  31066. * @type {String}
  31067. * @default 'color'
  31068. */
  31069. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31070. /**
  31071. * A track for numeric keyframe values.
  31072. *
  31073. * @augments KeyframeTrack
  31074. */
  31075. class NumberKeyframeTrack extends KeyframeTrack {
  31076. /**
  31077. * Constructs a new number keyframe track.
  31078. *
  31079. * @param {string} name - The keyframe track's name.
  31080. * @param {Array<number>} times - A list of keyframe times.
  31081. * @param {Array<number>} values - A list of keyframe values.
  31082. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31083. */
  31084. constructor( name, times, values, interpolation ) {
  31085. super( name, times, values, interpolation );
  31086. }
  31087. }
  31088. /**
  31089. * The value type name.
  31090. *
  31091. * @type {String}
  31092. * @default 'number'
  31093. */
  31094. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31095. /**
  31096. * Spherical linear unit quaternion interpolant.
  31097. *
  31098. * @augments Interpolant
  31099. */
  31100. class QuaternionLinearInterpolant extends Interpolant {
  31101. /**
  31102. * Constructs a new SLERP interpolant.
  31103. *
  31104. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31105. * @param {TypedArray} sampleValues - The sample values.
  31106. * @param {number} sampleSize - The sample size
  31107. * @param {TypedArray} [resultBuffer] - The result buffer.
  31108. */
  31109. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31110. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31111. }
  31112. interpolate_( i1, t0, t, t1 ) {
  31113. const result = this.resultBuffer,
  31114. values = this.sampleValues,
  31115. stride = this.valueSize,
  31116. alpha = ( t - t0 ) / ( t1 - t0 );
  31117. let offset = i1 * stride;
  31118. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31119. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31120. }
  31121. return result;
  31122. }
  31123. }
  31124. /**
  31125. * A track for Quaternion keyframe values.
  31126. *
  31127. * @augments KeyframeTrack
  31128. */
  31129. class QuaternionKeyframeTrack extends KeyframeTrack {
  31130. /**
  31131. * Constructs a new Quaternion keyframe track.
  31132. *
  31133. * @param {string} name - The keyframe track's name.
  31134. * @param {Array<number>} times - A list of keyframe times.
  31135. * @param {Array<number>} values - A list of keyframe values.
  31136. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31137. */
  31138. constructor( name, times, values, interpolation ) {
  31139. super( name, times, values, interpolation );
  31140. }
  31141. /**
  31142. * Overwritten so the method returns Quaternion based interpolant.
  31143. *
  31144. * @static
  31145. * @param {TypedArray} [result] - The result buffer.
  31146. * @return {QuaternionLinearInterpolant} The new interpolant.
  31147. */
  31148. InterpolantFactoryMethodLinear( result ) {
  31149. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31150. }
  31151. }
  31152. /**
  31153. * The value type name.
  31154. *
  31155. * @type {String}
  31156. * @default 'quaternion'
  31157. */
  31158. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31159. // ValueBufferType is inherited
  31160. // DefaultInterpolation is inherited;
  31161. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31162. /**
  31163. * A track for string keyframe values.
  31164. *
  31165. * @augments KeyframeTrack
  31166. */
  31167. class StringKeyframeTrack extends KeyframeTrack {
  31168. /**
  31169. * Constructs a new string keyframe track.
  31170. *
  31171. * This keyframe track type has no `interpolation` parameter because the
  31172. * interpolation is always discrete.
  31173. *
  31174. * @param {string} name - The keyframe track's name.
  31175. * @param {Array<number>} times - A list of keyframe times.
  31176. * @param {Array<string>} values - A list of keyframe values.
  31177. */
  31178. constructor( name, times, values ) {
  31179. super( name, times, values );
  31180. }
  31181. }
  31182. /**
  31183. * The value type name.
  31184. *
  31185. * @type {String}
  31186. * @default 'string'
  31187. */
  31188. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31189. /**
  31190. * The value buffer type of this keyframe track.
  31191. *
  31192. * @type {TypedArray|Array}
  31193. * @default Array.constructor
  31194. */
  31195. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31196. /**
  31197. * The default interpolation type of this keyframe track.
  31198. *
  31199. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31200. * @default InterpolateDiscrete
  31201. */
  31202. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31203. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31204. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31205. /**
  31206. * A track for vector keyframe values.
  31207. *
  31208. * @augments KeyframeTrack
  31209. */
  31210. class VectorKeyframeTrack extends KeyframeTrack {
  31211. /**
  31212. * Constructs a new vector keyframe track.
  31213. *
  31214. * @param {string} name - The keyframe track's name.
  31215. * @param {Array<number>} times - A list of keyframe times.
  31216. * @param {Array<number>} values - A list of keyframe values.
  31217. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31218. */
  31219. constructor( name, times, values, interpolation ) {
  31220. super( name, times, values, interpolation );
  31221. }
  31222. }
  31223. /**
  31224. * The value type name.
  31225. *
  31226. * @type {String}
  31227. * @default 'vector'
  31228. */
  31229. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31230. /**
  31231. * A reusable set of keyframe tracks which represent an animation.
  31232. */
  31233. class AnimationClip {
  31234. /**
  31235. * Constructs a new animation clip.
  31236. *
  31237. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31238. * use the static interface of this class for creating clips. In most cases though, animation clips
  31239. * will automatically be created by loaders when importing animated 3D assets.
  31240. *
  31241. * @param {string} [name=''] - The clip's name.
  31242. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31243. * the duration will be calculated from the passed keyframes.
  31244. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31245. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31246. * is blended/combined when two or more animations are simultaneously played.
  31247. */
  31248. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31249. /**
  31250. * The clip's name.
  31251. *
  31252. * @type {string}
  31253. */
  31254. this.name = name;
  31255. /**
  31256. * An array of keyframe tracks.
  31257. *
  31258. * @type {Array<KeyframeTrack>}
  31259. */
  31260. this.tracks = tracks;
  31261. /**
  31262. * The clip's duration in seconds.
  31263. *
  31264. * @type {number}
  31265. */
  31266. this.duration = duration;
  31267. /**
  31268. * Defines how the animation is blended/combined when two or more animations
  31269. * are simultaneously played.
  31270. *
  31271. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31272. */
  31273. this.blendMode = blendMode;
  31274. /**
  31275. * The UUID of the animation clip.
  31276. *
  31277. * @type {string}
  31278. * @readonly
  31279. */
  31280. this.uuid = generateUUID();
  31281. // this means it should figure out its duration by scanning the tracks
  31282. if ( this.duration < 0 ) {
  31283. this.resetDuration();
  31284. }
  31285. }
  31286. /**
  31287. * Factory method for creating an animation clip from the given JSON.
  31288. *
  31289. * @static
  31290. * @param {Object} json - The serialized animation clip.
  31291. * @return {AnimationClip} The new animation clip.
  31292. */
  31293. static parse( json ) {
  31294. const tracks = [],
  31295. jsonTracks = json.tracks,
  31296. frameTime = 1.0 / ( json.fps || 1.0 );
  31297. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31298. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31299. }
  31300. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31301. clip.uuid = json.uuid;
  31302. return clip;
  31303. }
  31304. /**
  31305. * Serializes the given animation clip into JSON.
  31306. *
  31307. * @static
  31308. * @param {AnimationClip} clip - The animation clip to serialize.
  31309. * @return {Object} The JSON object.
  31310. */
  31311. static toJSON( clip ) {
  31312. const tracks = [],
  31313. clipTracks = clip.tracks;
  31314. const json = {
  31315. 'name': clip.name,
  31316. 'duration': clip.duration,
  31317. 'tracks': tracks,
  31318. 'uuid': clip.uuid,
  31319. 'blendMode': clip.blendMode
  31320. };
  31321. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31322. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31323. }
  31324. return json;
  31325. }
  31326. /**
  31327. * Returns a new animation clip from the passed morph targets array of a
  31328. * geometry, taking a name and the number of frames per second.
  31329. *
  31330. * Note: The fps parameter is required, but the animation speed can be
  31331. * overridden via {@link AnimationAction#setDuration}.
  31332. *
  31333. * @static
  31334. * @param {string} name - The name of the animation clip.
  31335. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31336. * @param {number} fps - The Frames-Per-Second value.
  31337. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31338. * @return {AnimationClip} The new animation clip.
  31339. */
  31340. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31341. const numMorphTargets = morphTargetSequence.length;
  31342. const tracks = [];
  31343. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31344. let times = [];
  31345. let values = [];
  31346. times.push(
  31347. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31348. i,
  31349. ( i + 1 ) % numMorphTargets );
  31350. values.push( 0, 1, 0 );
  31351. const order = getKeyframeOrder( times );
  31352. times = sortedArray( times, 1, order );
  31353. values = sortedArray( values, 1, order );
  31354. // if there is a key at the first frame, duplicate it as the
  31355. // last frame as well for perfect loop.
  31356. if ( ! noLoop && times[ 0 ] === 0 ) {
  31357. times.push( numMorphTargets );
  31358. values.push( values[ 0 ] );
  31359. }
  31360. tracks.push(
  31361. new NumberKeyframeTrack(
  31362. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31363. times, values
  31364. ).scale( 1.0 / fps ) );
  31365. }
  31366. return new this( name, -1, tracks );
  31367. }
  31368. /**
  31369. * Searches for an animation clip by name, taking as its first parameter
  31370. * either an array of clips, or a mesh or geometry that contains an
  31371. * array named "animations" property.
  31372. *
  31373. * @static
  31374. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31375. * @param {string} name - The name to search for.
  31376. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31377. */
  31378. static findByName( objectOrClipArray, name ) {
  31379. let clipArray = objectOrClipArray;
  31380. if ( ! Array.isArray( objectOrClipArray ) ) {
  31381. const o = objectOrClipArray;
  31382. clipArray = o.geometry && o.geometry.animations || o.animations;
  31383. }
  31384. for ( let i = 0; i < clipArray.length; i ++ ) {
  31385. if ( clipArray[ i ].name === name ) {
  31386. return clipArray[ i ];
  31387. }
  31388. }
  31389. return null;
  31390. }
  31391. /**
  31392. * Returns an array of new AnimationClips created from the morph target
  31393. * sequences of a geometry, trying to sort morph target names into
  31394. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31395. *
  31396. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31397. *
  31398. * @static
  31399. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31400. * @param {number} fps - The Frames-Per-Second value.
  31401. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31402. * @return {Array<AnimationClip>} An array of new animation clips.
  31403. */
  31404. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31405. const animationToMorphTargets = {};
  31406. // tested with https://regex101.com/ on trick sequences
  31407. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31408. const pattern = /^([\w-]*?)([\d]+)$/;
  31409. // sort morph target names into animation groups based
  31410. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31411. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31412. const morphTarget = morphTargets[ i ];
  31413. const parts = morphTarget.name.match( pattern );
  31414. if ( parts && parts.length > 1 ) {
  31415. const name = parts[ 1 ];
  31416. let animationMorphTargets = animationToMorphTargets[ name ];
  31417. if ( ! animationMorphTargets ) {
  31418. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31419. }
  31420. animationMorphTargets.push( morphTarget );
  31421. }
  31422. }
  31423. const clips = [];
  31424. for ( const name in animationToMorphTargets ) {
  31425. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31426. }
  31427. return clips;
  31428. }
  31429. /**
  31430. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31431. *
  31432. * @static
  31433. * @deprecated since r175.
  31434. * @param {Object} animation - A serialized animation clip as JSON.
  31435. * @param {Array<Bones>} bones - An array of bones.
  31436. * @return {?AnimationClip} The new animation clip.
  31437. */
  31438. static parseAnimation( animation, bones ) {
  31439. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31440. if ( ! animation ) {
  31441. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31442. return null;
  31443. }
  31444. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31445. // only return track if there are actually keys.
  31446. if ( animationKeys.length !== 0 ) {
  31447. const times = [];
  31448. const values = [];
  31449. flattenJSON( animationKeys, times, values, propertyName );
  31450. // empty keys are filtered out, so check again
  31451. if ( times.length !== 0 ) {
  31452. destTracks.push( new trackType( trackName, times, values ) );
  31453. }
  31454. }
  31455. };
  31456. const tracks = [];
  31457. const clipName = animation.name || 'default';
  31458. const fps = animation.fps || 30;
  31459. const blendMode = animation.blendMode;
  31460. // automatic length determination in AnimationClip.
  31461. let duration = animation.length || -1;
  31462. const hierarchyTracks = animation.hierarchy || [];
  31463. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31464. const animationKeys = hierarchyTracks[ h ].keys;
  31465. // skip empty tracks
  31466. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31467. // process morph targets
  31468. if ( animationKeys[ 0 ].morphTargets ) {
  31469. // figure out all morph targets used in this track
  31470. const morphTargetNames = {};
  31471. let k;
  31472. for ( k = 0; k < animationKeys.length; k ++ ) {
  31473. if ( animationKeys[ k ].morphTargets ) {
  31474. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31475. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31476. }
  31477. }
  31478. }
  31479. // create a track for each morph target with all zero
  31480. // morphTargetInfluences except for the keys in which
  31481. // the morphTarget is named.
  31482. for ( const morphTargetName in morphTargetNames ) {
  31483. const times = [];
  31484. const values = [];
  31485. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31486. const animationKey = animationKeys[ k ];
  31487. times.push( animationKey.time );
  31488. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31489. }
  31490. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31491. }
  31492. duration = morphTargetNames.length * fps;
  31493. } else {
  31494. // ...assume skeletal animation
  31495. const boneName = '.bones[' + bones[ h ].name + ']';
  31496. addNonemptyTrack(
  31497. VectorKeyframeTrack, boneName + '.position',
  31498. animationKeys, 'pos', tracks );
  31499. addNonemptyTrack(
  31500. QuaternionKeyframeTrack, boneName + '.quaternion',
  31501. animationKeys, 'rot', tracks );
  31502. addNonemptyTrack(
  31503. VectorKeyframeTrack, boneName + '.scale',
  31504. animationKeys, 'scl', tracks );
  31505. }
  31506. }
  31507. if ( tracks.length === 0 ) {
  31508. return null;
  31509. }
  31510. const clip = new this( clipName, duration, tracks, blendMode );
  31511. return clip;
  31512. }
  31513. /**
  31514. * Sets the duration of this clip to the duration of its longest keyframe track.
  31515. *
  31516. * @return {AnimationClip} A reference to this animation clip.
  31517. */
  31518. resetDuration() {
  31519. const tracks = this.tracks;
  31520. let duration = 0;
  31521. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31522. const track = this.tracks[ i ];
  31523. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31524. }
  31525. this.duration = duration;
  31526. return this;
  31527. }
  31528. /**
  31529. * Trims all tracks to the clip's duration.
  31530. *
  31531. * @return {AnimationClip} A reference to this animation clip.
  31532. */
  31533. trim() {
  31534. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31535. this.tracks[ i ].trim( 0, this.duration );
  31536. }
  31537. return this;
  31538. }
  31539. /**
  31540. * Performs minimal validation on each track in the clip. Returns `true` if all
  31541. * tracks are valid.
  31542. *
  31543. * @return {boolean} Whether the clip's keyframes are valid or not.
  31544. */
  31545. validate() {
  31546. let valid = true;
  31547. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31548. valid = valid && this.tracks[ i ].validate();
  31549. }
  31550. return valid;
  31551. }
  31552. /**
  31553. * Optimizes each track by removing equivalent sequential keys (which are
  31554. * common in morph target sequences).
  31555. *
  31556. * @return {AnimationClip} A reference to this animation clip.
  31557. */
  31558. optimize() {
  31559. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31560. this.tracks[ i ].optimize();
  31561. }
  31562. return this;
  31563. }
  31564. /**
  31565. * Returns a new animation clip with copied values from this instance.
  31566. *
  31567. * @return {AnimationClip} A clone of this instance.
  31568. */
  31569. clone() {
  31570. const tracks = [];
  31571. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31572. tracks.push( this.tracks[ i ].clone() );
  31573. }
  31574. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31575. }
  31576. /**
  31577. * Serializes this animation clip into JSON.
  31578. *
  31579. * @return {Object} The JSON object.
  31580. */
  31581. toJSON() {
  31582. return this.constructor.toJSON( this );
  31583. }
  31584. }
  31585. function getTrackTypeForValueTypeName( typeName ) {
  31586. switch ( typeName.toLowerCase() ) {
  31587. case 'scalar':
  31588. case 'double':
  31589. case 'float':
  31590. case 'number':
  31591. case 'integer':
  31592. return NumberKeyframeTrack;
  31593. case 'vector':
  31594. case 'vector2':
  31595. case 'vector3':
  31596. case 'vector4':
  31597. return VectorKeyframeTrack;
  31598. case 'color':
  31599. return ColorKeyframeTrack;
  31600. case 'quaternion':
  31601. return QuaternionKeyframeTrack;
  31602. case 'bool':
  31603. case 'boolean':
  31604. return BooleanKeyframeTrack;
  31605. case 'string':
  31606. return StringKeyframeTrack;
  31607. }
  31608. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31609. }
  31610. function parseKeyframeTrack( json ) {
  31611. if ( json.type === undefined ) {
  31612. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31613. }
  31614. const trackType = getTrackTypeForValueTypeName( json.type );
  31615. if ( json.times === undefined ) {
  31616. const times = [], values = [];
  31617. flattenJSON( json.keys, times, values, 'value' );
  31618. json.times = times;
  31619. json.values = values;
  31620. }
  31621. // derived classes can define a static parse method
  31622. if ( trackType.parse !== undefined ) {
  31623. return trackType.parse( json );
  31624. } else {
  31625. // by default, we assume a constructor compatible with the base
  31626. return new trackType( json.name, json.times, json.values, json.interpolation );
  31627. }
  31628. }
  31629. /**
  31630. * @class
  31631. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31632. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31633. * @hideconstructor
  31634. */
  31635. const Cache = {
  31636. /**
  31637. * Whether caching is enabled or not.
  31638. *
  31639. * @static
  31640. * @type {boolean}
  31641. * @default false
  31642. */
  31643. enabled: false,
  31644. /**
  31645. * A dictionary that holds cached files.
  31646. *
  31647. * @static
  31648. * @type {Object<string,Object>}
  31649. */
  31650. files: {},
  31651. /**
  31652. * Adds a cache entry with a key to reference the file. If this key already
  31653. * holds a file, it is overwritten.
  31654. *
  31655. * @static
  31656. * @param {string} key - The key to reference the cached file.
  31657. * @param {Object} file - The file to be cached.
  31658. */
  31659. add: function ( key, file ) {
  31660. if ( this.enabled === false ) return;
  31661. // console.log( 'THREE.Cache', 'Adding key:', key );
  31662. this.files[ key ] = file;
  31663. },
  31664. /**
  31665. * Gets the cached value for the given key.
  31666. *
  31667. * @static
  31668. * @param {string} key - The key to reference the cached file.
  31669. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31670. */
  31671. get: function ( key ) {
  31672. if ( this.enabled === false ) return;
  31673. // console.log( 'THREE.Cache', 'Checking key:', key );
  31674. return this.files[ key ];
  31675. },
  31676. /**
  31677. * Removes the cached file associated with the given key.
  31678. *
  31679. * @static
  31680. * @param {string} key - The key to reference the cached file.
  31681. */
  31682. remove: function ( key ) {
  31683. delete this.files[ key ];
  31684. },
  31685. /**
  31686. * Remove all values from the cache.
  31687. *
  31688. * @static
  31689. */
  31690. clear: function () {
  31691. this.files = {};
  31692. }
  31693. };
  31694. /**
  31695. * Handles and keeps track of loaded and pending data. A default global
  31696. * instance of this class is created and used by loaders if not supplied
  31697. * manually.
  31698. *
  31699. * In general that should be sufficient, however there are times when it can
  31700. * be useful to have separate loaders - for example if you want to show
  31701. * separate loading bars for objects and textures.
  31702. *
  31703. * ```js
  31704. * const manager = new THREE.LoadingManager();
  31705. * manager.onLoad = () => console.log( 'Loading complete!' );
  31706. *
  31707. * const loader1 = new OBJLoader( manager );
  31708. * const loader2 = new ColladaLoader( manager );
  31709. * ```
  31710. */
  31711. class LoadingManager {
  31712. /**
  31713. * Constructs a new loading manager.
  31714. *
  31715. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31716. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31717. * @param {Function} [onError] - Executes when an error occurs.
  31718. */
  31719. constructor( onLoad, onProgress, onError ) {
  31720. const scope = this;
  31721. let isLoading = false;
  31722. let itemsLoaded = 0;
  31723. let itemsTotal = 0;
  31724. let urlModifier = undefined;
  31725. const handlers = [];
  31726. // Refer to #5689 for the reason why we don't set .onStart
  31727. // in the constructor
  31728. /**
  31729. * Executes when an item starts loading.
  31730. *
  31731. * @type {Function|undefined}
  31732. * @default undefined
  31733. */
  31734. this.onStart = undefined;
  31735. /**
  31736. * Executes when all items have been loaded.
  31737. *
  31738. * @type {Function|undefined}
  31739. * @default undefined
  31740. */
  31741. this.onLoad = onLoad;
  31742. /**
  31743. * Executes when single items have been loaded.
  31744. *
  31745. * @type {Function|undefined}
  31746. * @default undefined
  31747. */
  31748. this.onProgress = onProgress;
  31749. /**
  31750. * Executes when an error occurs.
  31751. *
  31752. * @type {Function|undefined}
  31753. * @default undefined
  31754. */
  31755. this.onError = onError;
  31756. /**
  31757. * Used for aborting ongoing requests in loaders using this manager.
  31758. *
  31759. * @type {AbortController}
  31760. */
  31761. this.abortController = new AbortController();
  31762. /**
  31763. * This should be called by any loader using the manager when the loader
  31764. * starts loading an item.
  31765. *
  31766. * @param {string} url - The URL to load.
  31767. */
  31768. this.itemStart = function ( url ) {
  31769. itemsTotal ++;
  31770. if ( isLoading === false ) {
  31771. if ( scope.onStart !== undefined ) {
  31772. scope.onStart( url, itemsLoaded, itemsTotal );
  31773. }
  31774. }
  31775. isLoading = true;
  31776. };
  31777. /**
  31778. * This should be called by any loader using the manager when the loader
  31779. * ended loading an item.
  31780. *
  31781. * @param {string} url - The URL of the loaded item.
  31782. */
  31783. this.itemEnd = function ( url ) {
  31784. itemsLoaded ++;
  31785. if ( scope.onProgress !== undefined ) {
  31786. scope.onProgress( url, itemsLoaded, itemsTotal );
  31787. }
  31788. if ( itemsLoaded === itemsTotal ) {
  31789. isLoading = false;
  31790. if ( scope.onLoad !== undefined ) {
  31791. scope.onLoad();
  31792. }
  31793. }
  31794. };
  31795. /**
  31796. * This should be called by any loader using the manager when the loader
  31797. * encounters an error when loading an item.
  31798. *
  31799. * @param {string} url - The URL of the item that produces an error.
  31800. */
  31801. this.itemError = function ( url ) {
  31802. if ( scope.onError !== undefined ) {
  31803. scope.onError( url );
  31804. }
  31805. };
  31806. /**
  31807. * Given a URL, uses the URL modifier callback (if any) and returns a
  31808. * resolved URL. If no URL modifier is set, returns the original URL.
  31809. *
  31810. * @param {string} url - The URL to load.
  31811. * @return {string} The resolved URL.
  31812. */
  31813. this.resolveURL = function ( url ) {
  31814. if ( urlModifier ) {
  31815. return urlModifier( url );
  31816. }
  31817. return url;
  31818. };
  31819. /**
  31820. * If provided, the callback will be passed each resource URL before a
  31821. * request is sent. The callback may return the original URL, or a new URL to
  31822. * override loading behavior. This behavior can be used to load assets from
  31823. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31824. *
  31825. * ```js
  31826. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31827. *
  31828. * const manager = new THREE.LoadingManager();
  31829. *
  31830. * // Initialize loading manager with URL callback.
  31831. * const objectURLs = [];
  31832. * manager.setURLModifier( ( url ) => {
  31833. *
  31834. * url = URL.createObjectURL( blobs[ url ] );
  31835. * objectURLs.push( url );
  31836. * return url;
  31837. *
  31838. * } );
  31839. *
  31840. * // Load as usual, then revoke the blob URLs.
  31841. * const loader = new GLTFLoader( manager );
  31842. * loader.load( 'fish.gltf', (gltf) => {
  31843. *
  31844. * scene.add( gltf.scene );
  31845. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31846. *
  31847. * } );
  31848. * ```
  31849. *
  31850. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31851. * @return {LoadingManager} A reference to this loading manager.
  31852. */
  31853. this.setURLModifier = function ( transform ) {
  31854. urlModifier = transform;
  31855. return this;
  31856. };
  31857. /**
  31858. * Registers a loader with the given regular expression. Can be used to
  31859. * define what loader should be used in order to load specific files. A
  31860. * typical use case is to overwrite the default loader for textures.
  31861. *
  31862. * ```js
  31863. * // add handler for TGA textures
  31864. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31865. * ```
  31866. *
  31867. * @param {string} regex - A regular expression.
  31868. * @param {Loader} loader - A loader that should handle matched cases.
  31869. * @return {LoadingManager} A reference to this loading manager.
  31870. */
  31871. this.addHandler = function ( regex, loader ) {
  31872. handlers.push( regex, loader );
  31873. return this;
  31874. };
  31875. /**
  31876. * Removes the loader for the given regular expression.
  31877. *
  31878. * @param {string} regex - A regular expression.
  31879. * @return {LoadingManager} A reference to this loading manager.
  31880. */
  31881. this.removeHandler = function ( regex ) {
  31882. const index = handlers.indexOf( regex );
  31883. if ( index !== -1 ) {
  31884. handlers.splice( index, 2 );
  31885. }
  31886. return this;
  31887. };
  31888. /**
  31889. * Can be used to retrieve the registered loader for the given file path.
  31890. *
  31891. * @param {string} file - The file path.
  31892. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31893. */
  31894. this.getHandler = function ( file ) {
  31895. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31896. const regex = handlers[ i ];
  31897. const loader = handlers[ i + 1 ];
  31898. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31899. if ( regex.test( file ) ) {
  31900. return loader;
  31901. }
  31902. }
  31903. return null;
  31904. };
  31905. /**
  31906. * Can be used to abort ongoing loading requests in loaders using this manager.
  31907. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31908. * is supported in the browser.
  31909. *
  31910. * @return {LoadingManager} A reference to this loading manager.
  31911. */
  31912. this.abort = function () {
  31913. this.abortController.abort();
  31914. this.abortController = new AbortController();
  31915. return this;
  31916. };
  31917. }
  31918. }
  31919. /**
  31920. * The global default loading manager.
  31921. *
  31922. * @constant
  31923. * @type {LoadingManager}
  31924. */
  31925. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31926. /**
  31927. * Abstract base class for loaders.
  31928. *
  31929. * @abstract
  31930. */
  31931. class Loader {
  31932. /**
  31933. * Constructs a new loader.
  31934. *
  31935. * @param {LoadingManager} [manager] - The loading manager.
  31936. */
  31937. constructor( manager ) {
  31938. /**
  31939. * The loading manager.
  31940. *
  31941. * @type {LoadingManager}
  31942. * @default DefaultLoadingManager
  31943. */
  31944. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31945. /**
  31946. * The crossOrigin string to implement CORS for loading the url from a
  31947. * different domain that allows CORS.
  31948. *
  31949. * @type {string}
  31950. * @default 'anonymous'
  31951. */
  31952. this.crossOrigin = 'anonymous';
  31953. /**
  31954. * Whether the XMLHttpRequest uses credentials.
  31955. *
  31956. * @type {boolean}
  31957. * @default false
  31958. */
  31959. this.withCredentials = false;
  31960. /**
  31961. * The base path from which the asset will be loaded.
  31962. *
  31963. * @type {string}
  31964. */
  31965. this.path = '';
  31966. /**
  31967. * The base path from which additional resources like textures will be loaded.
  31968. *
  31969. * @type {string}
  31970. */
  31971. this.resourcePath = '';
  31972. /**
  31973. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31974. * used in HTTP request.
  31975. *
  31976. * @type {Object<string, any>}
  31977. */
  31978. this.requestHeader = {};
  31979. }
  31980. /**
  31981. * This method needs to be implemented by all concrete loaders. It holds the
  31982. * logic for loading assets from the backend.
  31983. *
  31984. * @abstract
  31985. * @param {string} url - The path/URL of the file to be loaded.
  31986. * @param {Function} onLoad - Executed when the loading process has been finished.
  31987. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31988. * @param {onErrorCallback} [onError] - Executed when errors occur.
  31989. */
  31990. load( /* url, onLoad, onProgress, onError */ ) {}
  31991. /**
  31992. * A async version of {@link Loader#load}.
  31993. *
  31994. * @param {string} url - The path/URL of the file to be loaded.
  31995. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31996. * @return {Promise} A Promise that resolves when the asset has been loaded.
  31997. */
  31998. loadAsync( url, onProgress ) {
  31999. const scope = this;
  32000. return new Promise( function ( resolve, reject ) {
  32001. scope.load( url, resolve, onProgress, reject );
  32002. } );
  32003. }
  32004. /**
  32005. * This method needs to be implemented by all concrete loaders. It holds the
  32006. * logic for parsing the asset into three.js entities.
  32007. *
  32008. * @abstract
  32009. * @param {any} data - The data to parse.
  32010. */
  32011. parse( /* data */ ) {}
  32012. /**
  32013. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32014. * from a different domain that allows CORS.
  32015. *
  32016. * @param {string} crossOrigin - The `crossOrigin` value.
  32017. * @return {Loader} A reference to this instance.
  32018. */
  32019. setCrossOrigin( crossOrigin ) {
  32020. this.crossOrigin = crossOrigin;
  32021. return this;
  32022. }
  32023. /**
  32024. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32025. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32026. *
  32027. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32028. *
  32029. * @param {boolean} value - The `withCredentials` value.
  32030. * @return {Loader} A reference to this instance.
  32031. */
  32032. setWithCredentials( value ) {
  32033. this.withCredentials = value;
  32034. return this;
  32035. }
  32036. /**
  32037. * Sets the base path for the asset.
  32038. *
  32039. * @param {string} path - The base path.
  32040. * @return {Loader} A reference to this instance.
  32041. */
  32042. setPath( path ) {
  32043. this.path = path;
  32044. return this;
  32045. }
  32046. /**
  32047. * Sets the base path for dependent resources like textures.
  32048. *
  32049. * @param {string} resourcePath - The resource path.
  32050. * @return {Loader} A reference to this instance.
  32051. */
  32052. setResourcePath( resourcePath ) {
  32053. this.resourcePath = resourcePath;
  32054. return this;
  32055. }
  32056. /**
  32057. * Sets the given request header.
  32058. *
  32059. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32060. * for configuring the HTTP request.
  32061. * @return {Loader} A reference to this instance.
  32062. */
  32063. setRequestHeader( requestHeader ) {
  32064. this.requestHeader = requestHeader;
  32065. return this;
  32066. }
  32067. /**
  32068. * This method can be implemented in loaders for aborting ongoing requests.
  32069. *
  32070. * @abstract
  32071. * @return {Loader} A reference to this instance.
  32072. */
  32073. abort() {
  32074. return this;
  32075. }
  32076. }
  32077. /**
  32078. * Callback for onProgress in loaders.
  32079. *
  32080. * @callback onProgressCallback
  32081. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32082. */
  32083. /**
  32084. * Callback for onError in loaders.
  32085. *
  32086. * @callback onErrorCallback
  32087. * @param {Error} error - The error which occurred during the loading process.
  32088. */
  32089. /**
  32090. * The default material name that is used by loaders
  32091. * when creating materials for loaded 3D objects.
  32092. *
  32093. * Note: Not all loaders might honor this setting.
  32094. *
  32095. * @static
  32096. * @type {string}
  32097. * @default '__DEFAULT'
  32098. */
  32099. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32100. const loading = {};
  32101. class HttpError extends Error {
  32102. constructor( message, response ) {
  32103. super( message );
  32104. this.response = response;
  32105. }
  32106. }
  32107. /**
  32108. * A low level class for loading resources with the Fetch API, used internally by
  32109. * most loaders. It can also be used directly to load any file type that does
  32110. * not have a loader.
  32111. *
  32112. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32113. * once to your application.
  32114. *
  32115. * ```js
  32116. * const loader = new THREE.FileLoader();
  32117. * const data = await loader.loadAsync( 'example.txt' );
  32118. * ```
  32119. *
  32120. * @augments Loader
  32121. */
  32122. class FileLoader extends Loader {
  32123. /**
  32124. * Constructs a new file loader.
  32125. *
  32126. * @param {LoadingManager} [manager] - The loading manager.
  32127. */
  32128. constructor( manager ) {
  32129. super( manager );
  32130. /**
  32131. * The expected mime type. Valid values can be found
  32132. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32133. *
  32134. * @type {string}
  32135. */
  32136. this.mimeType = '';
  32137. /**
  32138. * The expected response type.
  32139. *
  32140. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32141. * @default ''
  32142. */
  32143. this.responseType = '';
  32144. /**
  32145. * Used for aborting requests.
  32146. *
  32147. * @private
  32148. * @type {AbortController}
  32149. */
  32150. this._abortController = new AbortController();
  32151. }
  32152. /**
  32153. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32154. *
  32155. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32156. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32157. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32158. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32159. * @return {any|undefined} The cached resource if available.
  32160. */
  32161. load( url, onLoad, onProgress, onError ) {
  32162. if ( url === undefined ) url = '';
  32163. if ( this.path !== undefined ) url = this.path + url;
  32164. url = this.manager.resolveURL( url );
  32165. const cached = Cache.get( `file:${url}` );
  32166. if ( cached !== undefined ) {
  32167. this.manager.itemStart( url );
  32168. setTimeout( () => {
  32169. if ( onLoad ) onLoad( cached );
  32170. this.manager.itemEnd( url );
  32171. }, 0 );
  32172. return cached;
  32173. }
  32174. // Check if request is duplicate
  32175. if ( loading[ url ] !== undefined ) {
  32176. loading[ url ].push( {
  32177. onLoad: onLoad,
  32178. onProgress: onProgress,
  32179. onError: onError
  32180. } );
  32181. return;
  32182. }
  32183. // Initialise array for duplicate requests
  32184. loading[ url ] = [];
  32185. loading[ url ].push( {
  32186. onLoad: onLoad,
  32187. onProgress: onProgress,
  32188. onError: onError,
  32189. } );
  32190. // create request
  32191. const req = new Request( url, {
  32192. headers: new Headers( this.requestHeader ),
  32193. credentials: this.withCredentials ? 'include' : 'same-origin',
  32194. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32195. } );
  32196. // record states ( avoid data race )
  32197. const mimeType = this.mimeType;
  32198. const responseType = this.responseType;
  32199. // start the fetch
  32200. fetch( req )
  32201. .then( response => {
  32202. if ( response.status === 200 || response.status === 0 ) {
  32203. // Some browsers return HTTP Status 0 when using non-http protocol
  32204. // e.g. 'file://' or 'data://'. Handle as success.
  32205. if ( response.status === 0 ) {
  32206. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32207. }
  32208. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32209. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32210. return response;
  32211. }
  32212. const callbacks = loading[ url ];
  32213. const reader = response.body.getReader();
  32214. // Nginx needs X-File-Size check
  32215. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32216. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32217. const total = contentLength ? parseInt( contentLength ) : 0;
  32218. const lengthComputable = total !== 0;
  32219. let loaded = 0;
  32220. // periodically read data into the new stream tracking while download progress
  32221. const stream = new ReadableStream( {
  32222. start( controller ) {
  32223. readData();
  32224. function readData() {
  32225. reader.read().then( ( { done, value } ) => {
  32226. if ( done ) {
  32227. controller.close();
  32228. } else {
  32229. loaded += value.byteLength;
  32230. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32231. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32232. const callback = callbacks[ i ];
  32233. if ( callback.onProgress ) callback.onProgress( event );
  32234. }
  32235. controller.enqueue( value );
  32236. readData();
  32237. }
  32238. }, ( e ) => {
  32239. controller.error( e );
  32240. } );
  32241. }
  32242. }
  32243. } );
  32244. return new Response( stream );
  32245. } else {
  32246. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32247. }
  32248. } )
  32249. .then( response => {
  32250. switch ( responseType ) {
  32251. case 'arraybuffer':
  32252. return response.arrayBuffer();
  32253. case 'blob':
  32254. return response.blob();
  32255. case 'document':
  32256. return response.text()
  32257. .then( text => {
  32258. const parser = new DOMParser();
  32259. return parser.parseFromString( text, mimeType );
  32260. } );
  32261. case 'json':
  32262. return response.json();
  32263. default:
  32264. if ( mimeType === '' ) {
  32265. return response.text();
  32266. } else {
  32267. // sniff encoding
  32268. const re = /charset="?([^;"\s]*)"?/i;
  32269. const exec = re.exec( mimeType );
  32270. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32271. const decoder = new TextDecoder( label );
  32272. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32273. }
  32274. }
  32275. } )
  32276. .then( data => {
  32277. // Add to cache only on HTTP success, so that we do not cache
  32278. // error response bodies as proper responses to requests.
  32279. Cache.add( `file:${url}`, data );
  32280. const callbacks = loading[ url ];
  32281. delete loading[ url ];
  32282. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32283. const callback = callbacks[ i ];
  32284. if ( callback.onLoad ) callback.onLoad( data );
  32285. }
  32286. } )
  32287. .catch( err => {
  32288. // Abort errors and other errors are handled the same
  32289. const callbacks = loading[ url ];
  32290. if ( callbacks === undefined ) {
  32291. // When onLoad was called and url was deleted in `loading`
  32292. this.manager.itemError( url );
  32293. throw err;
  32294. }
  32295. delete loading[ url ];
  32296. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32297. const callback = callbacks[ i ];
  32298. if ( callback.onError ) callback.onError( err );
  32299. }
  32300. this.manager.itemError( url );
  32301. } )
  32302. .finally( () => {
  32303. this.manager.itemEnd( url );
  32304. } );
  32305. this.manager.itemStart( url );
  32306. }
  32307. /**
  32308. * Sets the expected response type.
  32309. *
  32310. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32311. * @return {FileLoader} A reference to this file loader.
  32312. */
  32313. setResponseType( value ) {
  32314. this.responseType = value;
  32315. return this;
  32316. }
  32317. /**
  32318. * Sets the expected mime type of the loaded file.
  32319. *
  32320. * @param {string} value - The mime type.
  32321. * @return {FileLoader} A reference to this file loader.
  32322. */
  32323. setMimeType( value ) {
  32324. this.mimeType = value;
  32325. return this;
  32326. }
  32327. /**
  32328. * Aborts ongoing fetch requests.
  32329. *
  32330. * @return {FileLoader} A reference to this instance.
  32331. */
  32332. abort() {
  32333. this._abortController.abort();
  32334. this._abortController = new AbortController();
  32335. return this;
  32336. }
  32337. }
  32338. /**
  32339. * Class for loading animation clips in the JSON format. The files are internally
  32340. * loaded via {@link FileLoader}.
  32341. *
  32342. * ```js
  32343. * const loader = new THREE.AnimationLoader();
  32344. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32345. * ```
  32346. *
  32347. * @augments Loader
  32348. */
  32349. class AnimationLoader extends Loader {
  32350. /**
  32351. * Constructs a new animation loader.
  32352. *
  32353. * @param {LoadingManager} [manager] - The loading manager.
  32354. */
  32355. constructor( manager ) {
  32356. super( manager );
  32357. }
  32358. /**
  32359. * Starts loading from the given URL and pass the loaded animations as an array
  32360. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32361. *
  32362. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32363. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32364. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32365. * @param {onErrorCallback} onError - Executed when errors occur.
  32366. */
  32367. load( url, onLoad, onProgress, onError ) {
  32368. const scope = this;
  32369. const loader = new FileLoader( this.manager );
  32370. loader.setPath( this.path );
  32371. loader.setRequestHeader( this.requestHeader );
  32372. loader.setWithCredentials( this.withCredentials );
  32373. loader.load( url, function ( text ) {
  32374. try {
  32375. onLoad( scope.parse( JSON.parse( text ) ) );
  32376. } catch ( e ) {
  32377. if ( onError ) {
  32378. onError( e );
  32379. } else {
  32380. console.error( e );
  32381. }
  32382. scope.manager.itemError( url );
  32383. }
  32384. }, onProgress, onError );
  32385. }
  32386. /**
  32387. * Parses the given JSON object and returns an array of animation clips.
  32388. *
  32389. * @param {Object} json - The serialized animation clips.
  32390. * @return {Array<AnimationClip>} The parsed animation clips.
  32391. */
  32392. parse( json ) {
  32393. const animations = [];
  32394. for ( let i = 0; i < json.length; i ++ ) {
  32395. const clip = AnimationClip.parse( json[ i ] );
  32396. animations.push( clip );
  32397. }
  32398. return animations;
  32399. }
  32400. }
  32401. /**
  32402. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32403. * Textures are internally loaded via {@link FileLoader}.
  32404. *
  32405. * Derived classes have to implement the `parse()` method which holds the parsing
  32406. * for the respective format.
  32407. *
  32408. * @abstract
  32409. * @augments Loader
  32410. */
  32411. class CompressedTextureLoader extends Loader {
  32412. /**
  32413. * Constructs a new compressed texture loader.
  32414. *
  32415. * @param {LoadingManager} [manager] - The loading manager.
  32416. */
  32417. constructor( manager ) {
  32418. super( manager );
  32419. }
  32420. /**
  32421. * Starts loading from the given URL and passes the loaded compressed texture
  32422. * to the `onLoad()` callback. The method also returns a new texture object which can
  32423. * directly be used for material creation. If you do it this way, the texture
  32424. * may pop up in your scene once the respective loading process is finished.
  32425. *
  32426. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32427. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32428. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32429. * @param {onErrorCallback} onError - Executed when errors occur.
  32430. * @return {CompressedTexture} The compressed texture.
  32431. */
  32432. load( url, onLoad, onProgress, onError ) {
  32433. const scope = this;
  32434. const images = [];
  32435. const texture = new CompressedTexture();
  32436. const loader = new FileLoader( this.manager );
  32437. loader.setPath( this.path );
  32438. loader.setResponseType( 'arraybuffer' );
  32439. loader.setRequestHeader( this.requestHeader );
  32440. loader.setWithCredentials( scope.withCredentials );
  32441. let loaded = 0;
  32442. function loadTexture( i ) {
  32443. loader.load( url[ i ], function ( buffer ) {
  32444. const texDatas = scope.parse( buffer, true );
  32445. images[ i ] = {
  32446. width: texDatas.width,
  32447. height: texDatas.height,
  32448. format: texDatas.format,
  32449. mipmaps: texDatas.mipmaps
  32450. };
  32451. loaded += 1;
  32452. if ( loaded === 6 ) {
  32453. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32454. texture.image = images;
  32455. texture.format = texDatas.format;
  32456. texture.needsUpdate = true;
  32457. if ( onLoad ) onLoad( texture );
  32458. }
  32459. }, onProgress, onError );
  32460. }
  32461. if ( Array.isArray( url ) ) {
  32462. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32463. loadTexture( i );
  32464. }
  32465. } else {
  32466. // compressed cubemap texture stored in a single DDS file
  32467. loader.load( url, function ( buffer ) {
  32468. const texDatas = scope.parse( buffer, true );
  32469. if ( texDatas.isCubemap ) {
  32470. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32471. for ( let f = 0; f < faces; f ++ ) {
  32472. images[ f ] = { mipmaps: [] };
  32473. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32474. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32475. images[ f ].format = texDatas.format;
  32476. images[ f ].width = texDatas.width;
  32477. images[ f ].height = texDatas.height;
  32478. }
  32479. }
  32480. texture.image = images;
  32481. } else {
  32482. texture.image.width = texDatas.width;
  32483. texture.image.height = texDatas.height;
  32484. texture.mipmaps = texDatas.mipmaps;
  32485. }
  32486. if ( texDatas.mipmapCount === 1 ) {
  32487. texture.minFilter = LinearFilter;
  32488. }
  32489. texture.format = texDatas.format;
  32490. texture.needsUpdate = true;
  32491. if ( onLoad ) onLoad( texture );
  32492. }, onProgress, onError );
  32493. }
  32494. return texture;
  32495. }
  32496. }
  32497. const _loading = new WeakMap();
  32498. /**
  32499. * A loader for loading images. The class loads images with the HTML `Image` API.
  32500. *
  32501. * ```js
  32502. * const loader = new THREE.ImageLoader();
  32503. * const image = await loader.loadAsync( 'image.png' );
  32504. * ```
  32505. * Please note that `ImageLoader` has dropped support for progress
  32506. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32507. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32508. *
  32509. * @augments Loader
  32510. */
  32511. class ImageLoader extends Loader {
  32512. /**
  32513. * Constructs a new image loader.
  32514. *
  32515. * @param {LoadingManager} [manager] - The loading manager.
  32516. */
  32517. constructor( manager ) {
  32518. super( manager );
  32519. }
  32520. /**
  32521. * Starts loading from the given URL and passes the loaded image
  32522. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32523. * directly be used for texture creation. If you do it this way, the texture
  32524. * may pop up in your scene once the respective loading process is finished.
  32525. *
  32526. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32527. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32528. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32529. * @param {onErrorCallback} onError - Executed when errors occur.
  32530. * @return {Image} The image.
  32531. */
  32532. load( url, onLoad, onProgress, onError ) {
  32533. if ( this.path !== undefined ) url = this.path + url;
  32534. url = this.manager.resolveURL( url );
  32535. const scope = this;
  32536. const cached = Cache.get( `image:${url}` );
  32537. if ( cached !== undefined ) {
  32538. if ( cached.complete === true ) {
  32539. scope.manager.itemStart( url );
  32540. setTimeout( function () {
  32541. if ( onLoad ) onLoad( cached );
  32542. scope.manager.itemEnd( url );
  32543. }, 0 );
  32544. } else {
  32545. let arr = _loading.get( cached );
  32546. if ( arr === undefined ) {
  32547. arr = [];
  32548. _loading.set( cached, arr );
  32549. }
  32550. arr.push( { onLoad, onError } );
  32551. }
  32552. return cached;
  32553. }
  32554. const image = createElementNS( 'img' );
  32555. function onImageLoad() {
  32556. removeEventListeners();
  32557. if ( onLoad ) onLoad( this );
  32558. //
  32559. const callbacks = _loading.get( this ) || [];
  32560. for ( let i = 0; i < callbacks.length; i ++ ) {
  32561. const callback = callbacks[ i ];
  32562. if ( callback.onLoad ) callback.onLoad( this );
  32563. }
  32564. _loading.delete( this );
  32565. scope.manager.itemEnd( url );
  32566. }
  32567. function onImageError( event ) {
  32568. removeEventListeners();
  32569. if ( onError ) onError( event );
  32570. Cache.remove( `image:${url}` );
  32571. //
  32572. const callbacks = _loading.get( this ) || [];
  32573. for ( let i = 0; i < callbacks.length; i ++ ) {
  32574. const callback = callbacks[ i ];
  32575. if ( callback.onError ) callback.onError( event );
  32576. }
  32577. _loading.delete( this );
  32578. scope.manager.itemError( url );
  32579. scope.manager.itemEnd( url );
  32580. }
  32581. function removeEventListeners() {
  32582. image.removeEventListener( 'load', onImageLoad, false );
  32583. image.removeEventListener( 'error', onImageError, false );
  32584. }
  32585. image.addEventListener( 'load', onImageLoad, false );
  32586. image.addEventListener( 'error', onImageError, false );
  32587. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32588. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32589. }
  32590. Cache.add( `image:${url}`, image );
  32591. scope.manager.itemStart( url );
  32592. image.src = url;
  32593. return image;
  32594. }
  32595. }
  32596. /**
  32597. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32598. *
  32599. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32600. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32601. * like vertical and horizontal cross, column and row layouts are not supported.
  32602. *
  32603. * Note that, by convention, cube maps are specified in a coordinate system
  32604. * in which positive-x is to the right when looking up the positive-z axis --
  32605. * in other words, using a left-handed coordinate system. Since three.js uses
  32606. * a right-handed coordinate system, environment maps used in three.js will
  32607. * have pos-x and neg-x swapped.
  32608. *
  32609. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32610. * is set to `SRGBColorSpace` by default.
  32611. *
  32612. * ```js
  32613. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32614. * const cubeTexture = await loader.loadAsync( [
  32615. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32616. * ] );
  32617. * scene.background = cubeTexture;
  32618. * ```
  32619. *
  32620. * @augments Loader
  32621. */
  32622. class CubeTextureLoader extends Loader {
  32623. /**
  32624. * Constructs a new cube texture loader.
  32625. *
  32626. * @param {LoadingManager} [manager] - The loading manager.
  32627. */
  32628. constructor( manager ) {
  32629. super( manager );
  32630. }
  32631. /**
  32632. * Starts loading from the given URL and pass the fully loaded cube texture
  32633. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32634. * directly be used for material creation. If you do it this way, the cube texture
  32635. * may pop up in your scene once the respective loading process is finished.
  32636. *
  32637. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32638. * cube texture. The urls should be specified in the following order: pos-x,
  32639. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32640. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32641. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32642. * @param {onErrorCallback} onError - Executed when errors occur.
  32643. * @return {CubeTexture} The cube texture.
  32644. */
  32645. load( urls, onLoad, onProgress, onError ) {
  32646. const texture = new CubeTexture();
  32647. texture.colorSpace = SRGBColorSpace;
  32648. const loader = new ImageLoader( this.manager );
  32649. loader.setCrossOrigin( this.crossOrigin );
  32650. loader.setPath( this.path );
  32651. let loaded = 0;
  32652. function loadTexture( i ) {
  32653. loader.load( urls[ i ], function ( image ) {
  32654. texture.images[ i ] = image;
  32655. loaded ++;
  32656. if ( loaded === 6 ) {
  32657. texture.needsUpdate = true;
  32658. if ( onLoad ) onLoad( texture );
  32659. }
  32660. }, undefined, onError );
  32661. }
  32662. for ( let i = 0; i < urls.length; ++ i ) {
  32663. loadTexture( i );
  32664. }
  32665. return texture;
  32666. }
  32667. }
  32668. /**
  32669. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32670. * Textures are internally loaded via {@link FileLoader}.
  32671. *
  32672. * Derived classes have to implement the `parse()` method which holds the parsing
  32673. * for the respective format.
  32674. *
  32675. * @abstract
  32676. * @augments Loader
  32677. */
  32678. class DataTextureLoader extends Loader {
  32679. /**
  32680. * Constructs a new data texture loader.
  32681. *
  32682. * @param {LoadingManager} [manager] - The loading manager.
  32683. */
  32684. constructor( manager ) {
  32685. super( manager );
  32686. }
  32687. /**
  32688. * Starts loading from the given URL and passes the loaded data texture
  32689. * to the `onLoad()` callback. The method also returns a new texture object which can
  32690. * directly be used for material creation. If you do it this way, the texture
  32691. * may pop up in your scene once the respective loading process is finished.
  32692. *
  32693. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32694. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32695. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32696. * @param {onErrorCallback} onError - Executed when errors occur.
  32697. * @return {DataTexture} The data texture.
  32698. */
  32699. load( url, onLoad, onProgress, onError ) {
  32700. const scope = this;
  32701. const texture = new DataTexture();
  32702. const loader = new FileLoader( this.manager );
  32703. loader.setResponseType( 'arraybuffer' );
  32704. loader.setRequestHeader( this.requestHeader );
  32705. loader.setPath( this.path );
  32706. loader.setWithCredentials( scope.withCredentials );
  32707. loader.load( url, function ( buffer ) {
  32708. let texData;
  32709. try {
  32710. texData = scope.parse( buffer );
  32711. } catch ( error ) {
  32712. if ( onError !== undefined ) {
  32713. onError( error );
  32714. } else {
  32715. console.error( error );
  32716. return;
  32717. }
  32718. }
  32719. if ( texData.image !== undefined ) {
  32720. texture.image = texData.image;
  32721. } else if ( texData.data !== undefined ) {
  32722. texture.image.width = texData.width;
  32723. texture.image.height = texData.height;
  32724. texture.image.data = texData.data;
  32725. }
  32726. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32727. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32728. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32729. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32730. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32731. if ( texData.colorSpace !== undefined ) {
  32732. texture.colorSpace = texData.colorSpace;
  32733. }
  32734. if ( texData.flipY !== undefined ) {
  32735. texture.flipY = texData.flipY;
  32736. }
  32737. if ( texData.format !== undefined ) {
  32738. texture.format = texData.format;
  32739. }
  32740. if ( texData.type !== undefined ) {
  32741. texture.type = texData.type;
  32742. }
  32743. if ( texData.mipmaps !== undefined ) {
  32744. texture.mipmaps = texData.mipmaps;
  32745. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32746. }
  32747. if ( texData.mipmapCount === 1 ) {
  32748. texture.minFilter = LinearFilter;
  32749. }
  32750. if ( texData.generateMipmaps !== undefined ) {
  32751. texture.generateMipmaps = texData.generateMipmaps;
  32752. }
  32753. texture.needsUpdate = true;
  32754. if ( onLoad ) onLoad( texture, texData );
  32755. }, onProgress, onError );
  32756. return texture;
  32757. }
  32758. }
  32759. /**
  32760. * Class for loading textures. Images are internally
  32761. * loaded via {@link ImageLoader}.
  32762. *
  32763. * ```js
  32764. * const loader = new THREE.TextureLoader();
  32765. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32766. *
  32767. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32768. * ```
  32769. * Please note that `TextureLoader` has dropped support for progress
  32770. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32771. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32772. *
  32773. * @augments Loader
  32774. */
  32775. class TextureLoader extends Loader {
  32776. /**
  32777. * Constructs a new texture loader.
  32778. *
  32779. * @param {LoadingManager} [manager] - The loading manager.
  32780. */
  32781. constructor( manager ) {
  32782. super( manager );
  32783. }
  32784. /**
  32785. * Starts loading from the given URL and pass the fully loaded texture
  32786. * to the `onLoad()` callback. The method also returns a new texture object which can
  32787. * directly be used for material creation. If you do it this way, the texture
  32788. * may pop up in your scene once the respective loading process is finished.
  32789. *
  32790. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32791. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32792. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32793. * @param {onErrorCallback} onError - Executed when errors occur.
  32794. * @return {Texture} The texture.
  32795. */
  32796. load( url, onLoad, onProgress, onError ) {
  32797. const texture = new Texture();
  32798. const loader = new ImageLoader( this.manager );
  32799. loader.setCrossOrigin( this.crossOrigin );
  32800. loader.setPath( this.path );
  32801. loader.load( url, function ( image ) {
  32802. texture.image = image;
  32803. texture.needsUpdate = true;
  32804. if ( onLoad !== undefined ) {
  32805. onLoad( texture );
  32806. }
  32807. }, onProgress, onError );
  32808. return texture;
  32809. }
  32810. }
  32811. /**
  32812. * Abstract base class for lights - all other light types inherit the
  32813. * properties and methods described here.
  32814. *
  32815. * @abstract
  32816. * @augments Object3D
  32817. */
  32818. class Light extends Object3D {
  32819. /**
  32820. * Constructs a new light.
  32821. *
  32822. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32823. * @param {number} [intensity=1] - The light's strength/intensity.
  32824. */
  32825. constructor( color, intensity = 1 ) {
  32826. super();
  32827. /**
  32828. * This flag can be used for type testing.
  32829. *
  32830. * @type {boolean}
  32831. * @readonly
  32832. * @default true
  32833. */
  32834. this.isLight = true;
  32835. this.type = 'Light';
  32836. /**
  32837. * The light's color.
  32838. *
  32839. * @type {Color}
  32840. */
  32841. this.color = new Color( color );
  32842. /**
  32843. * The light's intensity.
  32844. *
  32845. * @type {number}
  32846. * @default 1
  32847. */
  32848. this.intensity = intensity;
  32849. }
  32850. /**
  32851. * Frees the GPU-related resources allocated by this instance. Call this
  32852. * method whenever this instance is no longer used in your app.
  32853. */
  32854. dispose() {
  32855. // Empty here in base class; some subclasses override.
  32856. }
  32857. copy( source, recursive ) {
  32858. super.copy( source, recursive );
  32859. this.color.copy( source.color );
  32860. this.intensity = source.intensity;
  32861. return this;
  32862. }
  32863. toJSON( meta ) {
  32864. const data = super.toJSON( meta );
  32865. data.object.color = this.color.getHex();
  32866. data.object.intensity = this.intensity;
  32867. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32868. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32869. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32870. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32871. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32872. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32873. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32874. return data;
  32875. }
  32876. }
  32877. /**
  32878. * A light source positioned directly above the scene, with color fading from
  32879. * the sky color to the ground color.
  32880. *
  32881. * This light cannot be used to cast shadows.
  32882. *
  32883. * ```js
  32884. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32885. * scene.add( light );
  32886. * ```
  32887. *
  32888. * @augments Light
  32889. */
  32890. class HemisphereLight extends Light {
  32891. /**
  32892. * Constructs a new hemisphere light.
  32893. *
  32894. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32895. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32896. * @param {number} [intensity=1] - The light's strength/intensity.
  32897. */
  32898. constructor( skyColor, groundColor, intensity ) {
  32899. super( skyColor, intensity );
  32900. /**
  32901. * This flag can be used for type testing.
  32902. *
  32903. * @type {boolean}
  32904. * @readonly
  32905. * @default true
  32906. */
  32907. this.isHemisphereLight = true;
  32908. this.type = 'HemisphereLight';
  32909. this.position.copy( Object3D.DEFAULT_UP );
  32910. this.updateMatrix();
  32911. /**
  32912. * The light's ground color.
  32913. *
  32914. * @type {Color}
  32915. */
  32916. this.groundColor = new Color( groundColor );
  32917. }
  32918. copy( source, recursive ) {
  32919. super.copy( source, recursive );
  32920. this.groundColor.copy( source.groundColor );
  32921. return this;
  32922. }
  32923. }
  32924. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32925. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32926. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32927. /**
  32928. * Abstract base class for light shadow classes. These classes
  32929. * represent the shadow configuration for different light types.
  32930. *
  32931. * @abstract
  32932. */
  32933. class LightShadow {
  32934. /**
  32935. * Constructs a new light shadow.
  32936. *
  32937. * @param {Camera} camera - The light's view of the world.
  32938. */
  32939. constructor( camera ) {
  32940. /**
  32941. * The light's view of the world.
  32942. *
  32943. * @type {Camera}
  32944. */
  32945. this.camera = camera;
  32946. /**
  32947. * The intensity of the shadow. The default is `1`.
  32948. * Valid values are in the range `[0, 1]`.
  32949. *
  32950. * @type {number}
  32951. * @default 1
  32952. */
  32953. this.intensity = 1;
  32954. /**
  32955. * Shadow map bias, how much to add or subtract from the normalized depth
  32956. * when deciding whether a surface is in shadow.
  32957. *
  32958. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32959. * may help reduce artifacts in shadows.
  32960. *
  32961. * @type {number}
  32962. * @default 0
  32963. */
  32964. this.bias = 0;
  32965. /**
  32966. * Defines how much the position used to query the shadow map is offset along
  32967. * the object normal. The default is `0`. Increasing this value can be used to
  32968. * reduce shadow acne especially in large scenes where light shines onto
  32969. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32970. *
  32971. * @type {number}
  32972. * @default 0
  32973. */
  32974. this.normalBias = 0;
  32975. /**
  32976. * Setting this to values greater than 1 will blur the edges of the shadow.
  32977. * High values will cause unwanted banding effects in the shadows - a greater
  32978. * map size will allow for a higher value to be used here before these effects
  32979. * become visible.
  32980. *
  32981. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32982. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32983. *
  32984. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32985. *
  32986. * @type {number}
  32987. * @default 1
  32988. */
  32989. this.radius = 1;
  32990. /**
  32991. * The amount of samples to use when blurring a VSM shadow map.
  32992. *
  32993. * @type {number}
  32994. * @default 8
  32995. */
  32996. this.blurSamples = 8;
  32997. /**
  32998. * Defines the width and height of the shadow map. Higher values give better quality
  32999. * shadows at the cost of computation time. Values must be powers of two.
  33000. *
  33001. * @type {Vector2}
  33002. * @default (512,512)
  33003. */
  33004. this.mapSize = new Vector2( 512, 512 );
  33005. /**
  33006. * The type of shadow texture. The default is `UnsignedByteType`.
  33007. *
  33008. * @type {number}
  33009. * @default UnsignedByteType
  33010. */
  33011. this.mapType = UnsignedByteType;
  33012. /**
  33013. * The depth map generated using the internal camera; a location beyond a
  33014. * pixel's depth is in shadow. Computed internally during rendering.
  33015. *
  33016. * @type {?RenderTarget}
  33017. * @default null
  33018. */
  33019. this.map = null;
  33020. /**
  33021. * The distribution map generated using the internal camera; an occlusion is
  33022. * calculated based on the distribution of depths. Computed internally during
  33023. * rendering.
  33024. *
  33025. * @type {?RenderTarget}
  33026. * @default null
  33027. */
  33028. this.mapPass = null;
  33029. /**
  33030. * Model to shadow camera space, to compute location and depth in shadow map.
  33031. * This is computed internally during rendering.
  33032. *
  33033. * @type {Matrix4}
  33034. */
  33035. this.matrix = new Matrix4();
  33036. /**
  33037. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33038. * lighting / shadows, you may set this to `false`.
  33039. *
  33040. * @type {boolean}
  33041. * @default true
  33042. */
  33043. this.autoUpdate = true;
  33044. /**
  33045. * When set to `true`, shadow maps will be updated in the next `render` call.
  33046. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33047. * set this property to `true` and then make a render call to update the light's shadow.
  33048. *
  33049. * @type {boolean}
  33050. * @default false
  33051. */
  33052. this.needsUpdate = false;
  33053. this._frustum = new Frustum();
  33054. this._frameExtents = new Vector2( 1, 1 );
  33055. this._viewportCount = 1;
  33056. this._viewports = [
  33057. new Vector4( 0, 0, 1, 1 )
  33058. ];
  33059. }
  33060. /**
  33061. * Used internally by the renderer to get the number of viewports that need
  33062. * to be rendered for this shadow.
  33063. *
  33064. * @return {number} The viewport count.
  33065. */
  33066. getViewportCount() {
  33067. return this._viewportCount;
  33068. }
  33069. /**
  33070. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33071. *
  33072. * @return {Frustum} The shadow camera frustum.
  33073. */
  33074. getFrustum() {
  33075. return this._frustum;
  33076. }
  33077. /**
  33078. * Update the matrices for the camera and shadow, used internally by the renderer.
  33079. *
  33080. * @param {Light} light - The light for which the shadow is being rendered.
  33081. */
  33082. updateMatrices( light ) {
  33083. const shadowCamera = this.camera;
  33084. const shadowMatrix = this.matrix;
  33085. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33086. shadowCamera.position.copy( _lightPositionWorld$1 );
  33087. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33088. shadowCamera.lookAt( _lookTarget$1 );
  33089. shadowCamera.updateMatrixWorld();
  33090. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33091. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  33092. if ( shadowCamera.reversedDepth ) {
  33093. shadowMatrix.set(
  33094. 0.5, 0.0, 0.0, 0.5,
  33095. 0.0, 0.5, 0.0, 0.5,
  33096. 0.0, 0.0, 1.0, 0.0,
  33097. 0.0, 0.0, 0.0, 1.0
  33098. );
  33099. } else {
  33100. shadowMatrix.set(
  33101. 0.5, 0.0, 0.0, 0.5,
  33102. 0.0, 0.5, 0.0, 0.5,
  33103. 0.0, 0.0, 0.5, 0.5,
  33104. 0.0, 0.0, 0.0, 1.0
  33105. );
  33106. }
  33107. shadowMatrix.multiply( _projScreenMatrix$1 );
  33108. }
  33109. /**
  33110. * Returns a viewport definition for the given viewport index.
  33111. *
  33112. * @param {number} viewportIndex - The viewport index.
  33113. * @return {Vector4} The viewport.
  33114. */
  33115. getViewport( viewportIndex ) {
  33116. return this._viewports[ viewportIndex ];
  33117. }
  33118. /**
  33119. * Returns the frame extends.
  33120. *
  33121. * @return {Vector2} The frame extends.
  33122. */
  33123. getFrameExtents() {
  33124. return this._frameExtents;
  33125. }
  33126. /**
  33127. * Frees the GPU-related resources allocated by this instance. Call this
  33128. * method whenever this instance is no longer used in your app.
  33129. */
  33130. dispose() {
  33131. if ( this.map ) {
  33132. this.map.dispose();
  33133. }
  33134. if ( this.mapPass ) {
  33135. this.mapPass.dispose();
  33136. }
  33137. }
  33138. /**
  33139. * Copies the values of the given light shadow instance to this instance.
  33140. *
  33141. * @param {LightShadow} source - The light shadow to copy.
  33142. * @return {LightShadow} A reference to this light shadow instance.
  33143. */
  33144. copy( source ) {
  33145. this.camera = source.camera.clone();
  33146. this.intensity = source.intensity;
  33147. this.bias = source.bias;
  33148. this.radius = source.radius;
  33149. this.autoUpdate = source.autoUpdate;
  33150. this.needsUpdate = source.needsUpdate;
  33151. this.normalBias = source.normalBias;
  33152. this.blurSamples = source.blurSamples;
  33153. this.mapSize.copy( source.mapSize );
  33154. return this;
  33155. }
  33156. /**
  33157. * Returns a new light shadow instance with copied values from this instance.
  33158. *
  33159. * @return {LightShadow} A clone of this instance.
  33160. */
  33161. clone() {
  33162. return new this.constructor().copy( this );
  33163. }
  33164. /**
  33165. * Serializes the light shadow into JSON.
  33166. *
  33167. * @return {Object} A JSON object representing the serialized light shadow.
  33168. * @see {@link ObjectLoader#parse}
  33169. */
  33170. toJSON() {
  33171. const object = {};
  33172. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33173. if ( this.bias !== 0 ) object.bias = this.bias;
  33174. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33175. if ( this.radius !== 1 ) object.radius = this.radius;
  33176. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33177. object.camera = this.camera.toJSON( false ).object;
  33178. delete object.camera.matrix;
  33179. return object;
  33180. }
  33181. }
  33182. /**
  33183. * Represents the shadow configuration of directional lights.
  33184. *
  33185. * @augments LightShadow
  33186. */
  33187. class SpotLightShadow extends LightShadow {
  33188. /**
  33189. * Constructs a new spot light shadow.
  33190. */
  33191. constructor() {
  33192. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33193. /**
  33194. * This flag can be used for type testing.
  33195. *
  33196. * @type {boolean}
  33197. * @readonly
  33198. * @default true
  33199. */
  33200. this.isSpotLightShadow = true;
  33201. /**
  33202. * Used to focus the shadow camera. The camera's field of view is set as a
  33203. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33204. *
  33205. * @type {number}
  33206. * @default 1
  33207. */
  33208. this.focus = 1;
  33209. /**
  33210. * Texture aspect ratio.
  33211. *
  33212. * @type {number}
  33213. * @default 1
  33214. */
  33215. this.aspect = 1;
  33216. }
  33217. updateMatrices( light ) {
  33218. const camera = this.camera;
  33219. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33220. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33221. const far = light.distance || camera.far;
  33222. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33223. camera.fov = fov;
  33224. camera.aspect = aspect;
  33225. camera.far = far;
  33226. camera.updateProjectionMatrix();
  33227. }
  33228. super.updateMatrices( light );
  33229. }
  33230. copy( source ) {
  33231. super.copy( source );
  33232. this.focus = source.focus;
  33233. return this;
  33234. }
  33235. }
  33236. /**
  33237. * This light gets emitted from a single point in one direction, along a cone
  33238. * that increases in size the further from the light it gets.
  33239. *
  33240. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33241. *
  33242. * ```js
  33243. * // white spotlight shining from the side, modulated by a texture
  33244. * const spotLight = new THREE.SpotLight( 0xffffff );
  33245. * spotLight.position.set( 100, 1000, 100 );
  33246. * spotLight.map = new THREE.TextureLoader().load( url );
  33247. *
  33248. * spotLight.castShadow = true;
  33249. * spotLight.shadow.mapSize.width = 1024;
  33250. * spotLight.shadow.mapSize.height = 1024;
  33251. * spotLight.shadow.camera.near = 500;
  33252. * spotLight.shadow.camera.far = 4000;
  33253. * spotLight.shadow.camera.fov = 30;s
  33254. * ```
  33255. *
  33256. * @augments Light
  33257. */
  33258. class SpotLight extends Light {
  33259. /**
  33260. * Constructs a new spot light.
  33261. *
  33262. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33263. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33264. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33265. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33266. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33267. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33268. */
  33269. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33270. super( color, intensity );
  33271. /**
  33272. * This flag can be used for type testing.
  33273. *
  33274. * @type {boolean}
  33275. * @readonly
  33276. * @default true
  33277. */
  33278. this.isSpotLight = true;
  33279. this.type = 'SpotLight';
  33280. this.position.copy( Object3D.DEFAULT_UP );
  33281. this.updateMatrix();
  33282. /**
  33283. * The spot light points from its position to the
  33284. * target's position.
  33285. *
  33286. * For the target's position to be changed to anything other
  33287. * than the default, it must be added to the scene.
  33288. *
  33289. * It is also possible to set the target to be another 3D object
  33290. * in the scene. The light will now track the target object.
  33291. *
  33292. * @type {Object3D}
  33293. */
  33294. this.target = new Object3D();
  33295. /**
  33296. * Maximum range of the light. `0` means no limit.
  33297. *
  33298. * @type {number}
  33299. * @default 0
  33300. */
  33301. this.distance = distance;
  33302. /**
  33303. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33304. *
  33305. * @type {number}
  33306. * @default Math.PI/3
  33307. */
  33308. this.angle = angle;
  33309. /**
  33310. * Percent of the spotlight cone that is attenuated due to penumbra.
  33311. * Value range is `[0,1]`.
  33312. *
  33313. * @type {number}
  33314. * @default 0
  33315. */
  33316. this.penumbra = penumbra;
  33317. /**
  33318. * The amount the light dims along the distance of the light. In context of
  33319. * physically-correct rendering the default value should not be changed.
  33320. *
  33321. * @type {number}
  33322. * @default 2
  33323. */
  33324. this.decay = decay;
  33325. /**
  33326. * A texture used to modulate the color of the light. The spot light
  33327. * color is mixed with the RGB value of this texture, with a ratio
  33328. * corresponding to its alpha value. The cookie-like masking effect is
  33329. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33330. *
  33331. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33332. *
  33333. * @type {?Texture}
  33334. * @default null
  33335. */
  33336. this.map = null;
  33337. /**
  33338. * This property holds the light's shadow configuration.
  33339. *
  33340. * @type {SpotLightShadow}
  33341. */
  33342. this.shadow = new SpotLightShadow();
  33343. }
  33344. /**
  33345. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33346. * Changing the power will also change the light's intensity.
  33347. *
  33348. * @type {number}
  33349. */
  33350. get power() {
  33351. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33352. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33353. return this.intensity * Math.PI;
  33354. }
  33355. set power( power ) {
  33356. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33357. this.intensity = power / Math.PI;
  33358. }
  33359. dispose() {
  33360. this.shadow.dispose();
  33361. }
  33362. copy( source, recursive ) {
  33363. super.copy( source, recursive );
  33364. this.distance = source.distance;
  33365. this.angle = source.angle;
  33366. this.penumbra = source.penumbra;
  33367. this.decay = source.decay;
  33368. this.target = source.target.clone();
  33369. this.shadow = source.shadow.clone();
  33370. return this;
  33371. }
  33372. }
  33373. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33374. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33375. const _lookTarget = /*@__PURE__*/ new Vector3();
  33376. /**
  33377. * Represents the shadow configuration of point lights.
  33378. *
  33379. * @augments LightShadow
  33380. */
  33381. class PointLightShadow extends LightShadow {
  33382. /**
  33383. * Constructs a new point light shadow.
  33384. */
  33385. constructor() {
  33386. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33387. /**
  33388. * This flag can be used for type testing.
  33389. *
  33390. * @type {boolean}
  33391. * @readonly
  33392. * @default true
  33393. */
  33394. this.isPointLightShadow = true;
  33395. this._frameExtents = new Vector2( 4, 2 );
  33396. this._viewportCount = 6;
  33397. this._viewports = [
  33398. // These viewports map a cube-map onto a 2D texture with the
  33399. // following orientation:
  33400. //
  33401. // xzXZ
  33402. // y Y
  33403. //
  33404. // X - Positive x direction
  33405. // x - Negative x direction
  33406. // Y - Positive y direction
  33407. // y - Negative y direction
  33408. // Z - Positive z direction
  33409. // z - Negative z direction
  33410. // positive X
  33411. new Vector4( 2, 1, 1, 1 ),
  33412. // negative X
  33413. new Vector4( 0, 1, 1, 1 ),
  33414. // positive Z
  33415. new Vector4( 3, 1, 1, 1 ),
  33416. // negative Z
  33417. new Vector4( 1, 1, 1, 1 ),
  33418. // positive Y
  33419. new Vector4( 3, 0, 1, 1 ),
  33420. // negative Y
  33421. new Vector4( 1, 0, 1, 1 )
  33422. ];
  33423. this._cubeDirections = [
  33424. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33425. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33426. ];
  33427. this._cubeUps = [
  33428. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33429. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33430. ];
  33431. }
  33432. /**
  33433. * Update the matrices for the camera and shadow, used internally by the renderer.
  33434. *
  33435. * @param {Light} light - The light for which the shadow is being rendered.
  33436. * @param {number} [viewportIndex=0] - The viewport index.
  33437. */
  33438. updateMatrices( light, viewportIndex = 0 ) {
  33439. const camera = this.camera;
  33440. const shadowMatrix = this.matrix;
  33441. const far = light.distance || camera.far;
  33442. if ( far !== camera.far ) {
  33443. camera.far = far;
  33444. camera.updateProjectionMatrix();
  33445. }
  33446. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33447. camera.position.copy( _lightPositionWorld );
  33448. _lookTarget.copy( camera.position );
  33449. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33450. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33451. camera.lookAt( _lookTarget );
  33452. camera.updateMatrixWorld();
  33453. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33454. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33455. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  33456. }
  33457. }
  33458. /**
  33459. * A light that gets emitted from a single point in all directions. A common
  33460. * use case for this is to replicate the light emitted from a bare
  33461. * lightbulb.
  33462. *
  33463. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33464. *
  33465. * ```js
  33466. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33467. * light.position.set( 50, 50, 50 );
  33468. * scene.add( light );
  33469. * ```
  33470. *
  33471. * @augments Light
  33472. */
  33473. class PointLight extends Light {
  33474. /**
  33475. * Constructs a new point light.
  33476. *
  33477. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33478. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33479. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33480. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33481. */
  33482. constructor( color, intensity, distance = 0, decay = 2 ) {
  33483. super( color, intensity );
  33484. /**
  33485. * This flag can be used for type testing.
  33486. *
  33487. * @type {boolean}
  33488. * @readonly
  33489. * @default true
  33490. */
  33491. this.isPointLight = true;
  33492. this.type = 'PointLight';
  33493. /**
  33494. * When distance is zero, light will attenuate according to inverse-square
  33495. * law to infinite distance. When distance is non-zero, light will attenuate
  33496. * according to inverse-square law until near the distance cutoff, where it
  33497. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33498. * physically correct.
  33499. *
  33500. * @type {number}
  33501. * @default 0
  33502. */
  33503. this.distance = distance;
  33504. /**
  33505. * The amount the light dims along the distance of the light. In context of
  33506. * physically-correct rendering the default value should not be changed.
  33507. *
  33508. * @type {number}
  33509. * @default 2
  33510. */
  33511. this.decay = decay;
  33512. /**
  33513. * This property holds the light's shadow configuration.
  33514. *
  33515. * @type {PointLightShadow}
  33516. */
  33517. this.shadow = new PointLightShadow();
  33518. }
  33519. /**
  33520. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33521. * Changing the power will also change the light's intensity.
  33522. *
  33523. * @type {number}
  33524. */
  33525. get power() {
  33526. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33527. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33528. return this.intensity * 4 * Math.PI;
  33529. }
  33530. set power( power ) {
  33531. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33532. this.intensity = power / ( 4 * Math.PI );
  33533. }
  33534. dispose() {
  33535. this.shadow.dispose();
  33536. }
  33537. copy( source, recursive ) {
  33538. super.copy( source, recursive );
  33539. this.distance = source.distance;
  33540. this.decay = source.decay;
  33541. this.shadow = source.shadow.clone();
  33542. return this;
  33543. }
  33544. }
  33545. /**
  33546. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33547. *
  33548. * In this projection mode, an object's size in the rendered image stays
  33549. * constant regardless of its distance from the camera. This can be useful
  33550. * for rendering 2D scenes and UI elements, amongst other things.
  33551. *
  33552. * ```js
  33553. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33554. * scene.add( camera );
  33555. * ```
  33556. *
  33557. * @augments Camera
  33558. */
  33559. class OrthographicCamera extends Camera {
  33560. /**
  33561. * Constructs a new orthographic camera.
  33562. *
  33563. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33564. * @param {number} [right=1] - The right plane of the camera's frustum.
  33565. * @param {number} [top=1] - The top plane of the camera's frustum.
  33566. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33567. * @param {number} [near=0.1] - The camera's near plane.
  33568. * @param {number} [far=2000] - The camera's far plane.
  33569. */
  33570. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33571. super();
  33572. /**
  33573. * This flag can be used for type testing.
  33574. *
  33575. * @type {boolean}
  33576. * @readonly
  33577. * @default true
  33578. */
  33579. this.isOrthographicCamera = true;
  33580. this.type = 'OrthographicCamera';
  33581. /**
  33582. * The zoom factor of the camera.
  33583. *
  33584. * @type {number}
  33585. * @default 1
  33586. */
  33587. this.zoom = 1;
  33588. /**
  33589. * Represents the frustum window specification. This property should not be edited
  33590. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33591. *
  33592. * @type {?Object}
  33593. * @default null
  33594. */
  33595. this.view = null;
  33596. /**
  33597. * The left plane of the camera's frustum.
  33598. *
  33599. * @type {number}
  33600. * @default -1
  33601. */
  33602. this.left = left;
  33603. /**
  33604. * The right plane of the camera's frustum.
  33605. *
  33606. * @type {number}
  33607. * @default 1
  33608. */
  33609. this.right = right;
  33610. /**
  33611. * The top plane of the camera's frustum.
  33612. *
  33613. * @type {number}
  33614. * @default 1
  33615. */
  33616. this.top = top;
  33617. /**
  33618. * The bottom plane of the camera's frustum.
  33619. *
  33620. * @type {number}
  33621. * @default -1
  33622. */
  33623. this.bottom = bottom;
  33624. /**
  33625. * The camera's near plane. The valid range is greater than `0`
  33626. * and less than the current value of {@link OrthographicCamera#far}.
  33627. *
  33628. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33629. * valid value for an orthographic camera's near plane.
  33630. *
  33631. * @type {number}
  33632. * @default 0.1
  33633. */
  33634. this.near = near;
  33635. /**
  33636. * The camera's far plane. Must be greater than the
  33637. * current value of {@link OrthographicCamera#near}.
  33638. *
  33639. * @type {number}
  33640. * @default 2000
  33641. */
  33642. this.far = far;
  33643. this.updateProjectionMatrix();
  33644. }
  33645. copy( source, recursive ) {
  33646. super.copy( source, recursive );
  33647. this.left = source.left;
  33648. this.right = source.right;
  33649. this.top = source.top;
  33650. this.bottom = source.bottom;
  33651. this.near = source.near;
  33652. this.far = source.far;
  33653. this.zoom = source.zoom;
  33654. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33655. return this;
  33656. }
  33657. /**
  33658. * Sets an offset in a larger frustum. This is useful for multi-window or
  33659. * multi-monitor/multi-machine setups.
  33660. *
  33661. * @param {number} fullWidth - The full width of multiview setup.
  33662. * @param {number} fullHeight - The full height of multiview setup.
  33663. * @param {number} x - The horizontal offset of the subcamera.
  33664. * @param {number} y - The vertical offset of the subcamera.
  33665. * @param {number} width - The width of subcamera.
  33666. * @param {number} height - The height of subcamera.
  33667. * @see {@link PerspectiveCamera#setViewOffset}
  33668. */
  33669. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33670. if ( this.view === null ) {
  33671. this.view = {
  33672. enabled: true,
  33673. fullWidth: 1,
  33674. fullHeight: 1,
  33675. offsetX: 0,
  33676. offsetY: 0,
  33677. width: 1,
  33678. height: 1
  33679. };
  33680. }
  33681. this.view.enabled = true;
  33682. this.view.fullWidth = fullWidth;
  33683. this.view.fullHeight = fullHeight;
  33684. this.view.offsetX = x;
  33685. this.view.offsetY = y;
  33686. this.view.width = width;
  33687. this.view.height = height;
  33688. this.updateProjectionMatrix();
  33689. }
  33690. /**
  33691. * Removes the view offset from the projection matrix.
  33692. */
  33693. clearViewOffset() {
  33694. if ( this.view !== null ) {
  33695. this.view.enabled = false;
  33696. }
  33697. this.updateProjectionMatrix();
  33698. }
  33699. /**
  33700. * Updates the camera's projection matrix. Must be called after any change of
  33701. * camera properties.
  33702. */
  33703. updateProjectionMatrix() {
  33704. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33705. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33706. const cx = ( this.right + this.left ) / 2;
  33707. const cy = ( this.top + this.bottom ) / 2;
  33708. let left = cx - dx;
  33709. let right = cx + dx;
  33710. let top = cy + dy;
  33711. let bottom = cy - dy;
  33712. if ( this.view !== null && this.view.enabled ) {
  33713. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33714. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33715. left += scaleW * this.view.offsetX;
  33716. right = left + scaleW * this.view.width;
  33717. top -= scaleH * this.view.offsetY;
  33718. bottom = top - scaleH * this.view.height;
  33719. }
  33720. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33721. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33722. }
  33723. toJSON( meta ) {
  33724. const data = super.toJSON( meta );
  33725. data.object.zoom = this.zoom;
  33726. data.object.left = this.left;
  33727. data.object.right = this.right;
  33728. data.object.top = this.top;
  33729. data.object.bottom = this.bottom;
  33730. data.object.near = this.near;
  33731. data.object.far = this.far;
  33732. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33733. return data;
  33734. }
  33735. }
  33736. /**
  33737. * Represents the shadow configuration of directional lights.
  33738. *
  33739. * @augments LightShadow
  33740. */
  33741. class DirectionalLightShadow extends LightShadow {
  33742. /**
  33743. * Constructs a new directional light shadow.
  33744. */
  33745. constructor() {
  33746. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33747. /**
  33748. * This flag can be used for type testing.
  33749. *
  33750. * @type {boolean}
  33751. * @readonly
  33752. * @default true
  33753. */
  33754. this.isDirectionalLightShadow = true;
  33755. }
  33756. }
  33757. /**
  33758. * A light that gets emitted in a specific direction. This light will behave
  33759. * as though it is infinitely far away and the rays produced from it are all
  33760. * parallel. The common use case for this is to simulate daylight; the sun is
  33761. * far enough away that its position can be considered to be infinite, and
  33762. * all light rays coming from it are parallel.
  33763. *
  33764. * A common point of confusion for directional lights is that setting the
  33765. * rotation has no effect. This is because three.js's DirectionalLight is the
  33766. * equivalent to what is often called a 'Target Direct Light' in other
  33767. * applications.
  33768. *
  33769. * This means that its direction is calculated as pointing from the light's
  33770. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33771. * (as opposed to a 'Free Direct Light' that just has a rotation
  33772. * component).
  33773. *
  33774. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33775. *
  33776. * ```js
  33777. * // White directional light at half intensity shining from the top.
  33778. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33779. * scene.add( directionalLight );
  33780. * ```
  33781. *
  33782. * @augments Light
  33783. */
  33784. class DirectionalLight extends Light {
  33785. /**
  33786. * Constructs a new directional light.
  33787. *
  33788. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33789. * @param {number} [intensity=1] - The light's strength/intensity.
  33790. */
  33791. constructor( color, intensity ) {
  33792. super( color, intensity );
  33793. /**
  33794. * This flag can be used for type testing.
  33795. *
  33796. * @type {boolean}
  33797. * @readonly
  33798. * @default true
  33799. */
  33800. this.isDirectionalLight = true;
  33801. this.type = 'DirectionalLight';
  33802. this.position.copy( Object3D.DEFAULT_UP );
  33803. this.updateMatrix();
  33804. /**
  33805. * The directional light points from its position to the
  33806. * target's position.
  33807. *
  33808. * For the target's position to be changed to anything other
  33809. * than the default, it must be added to the scene.
  33810. *
  33811. * It is also possible to set the target to be another 3D object
  33812. * in the scene. The light will now track the target object.
  33813. *
  33814. * @type {Object3D}
  33815. */
  33816. this.target = new Object3D();
  33817. /**
  33818. * This property holds the light's shadow configuration.
  33819. *
  33820. * @type {DirectionalLightShadow}
  33821. */
  33822. this.shadow = new DirectionalLightShadow();
  33823. }
  33824. dispose() {
  33825. this.shadow.dispose();
  33826. }
  33827. copy( source ) {
  33828. super.copy( source );
  33829. this.target = source.target.clone();
  33830. this.shadow = source.shadow.clone();
  33831. return this;
  33832. }
  33833. }
  33834. /**
  33835. * This light globally illuminates all objects in the scene equally.
  33836. *
  33837. * It cannot be used to cast shadows as it does not have a direction.
  33838. *
  33839. * ```js
  33840. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33841. * scene.add( light );
  33842. * ```
  33843. *
  33844. * @augments Light
  33845. */
  33846. class AmbientLight extends Light {
  33847. /**
  33848. * Constructs a new ambient light.
  33849. *
  33850. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33851. * @param {number} [intensity=1] - The light's strength/intensity.
  33852. */
  33853. constructor( color, intensity ) {
  33854. super( color, intensity );
  33855. /**
  33856. * This flag can be used for type testing.
  33857. *
  33858. * @type {boolean}
  33859. * @readonly
  33860. * @default true
  33861. */
  33862. this.isAmbientLight = true;
  33863. this.type = 'AmbientLight';
  33864. }
  33865. }
  33866. /**
  33867. * This class emits light uniformly across the face a rectangular plane.
  33868. * This light type can be used to simulate light sources such as bright
  33869. * windows or strip lighting.
  33870. *
  33871. * Important Notes:
  33872. *
  33873. * - There is no shadow support.
  33874. * - Only PBR materials are supported.
  33875. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33876. * into your app and init the uniforms/textures.
  33877. *
  33878. * ```js
  33879. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33880. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33881. *
  33882. * const intensity = 1; const width = 10; const height = 10;
  33883. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33884. * rectLight.position.set( 5, 5, 0 );
  33885. * rectLight.lookAt( 0, 0, 0 );
  33886. * scene.add( rectLight )
  33887. * ```
  33888. *
  33889. * @augments Light
  33890. */
  33891. class RectAreaLight extends Light {
  33892. /**
  33893. * Constructs a new area light.
  33894. *
  33895. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33896. * @param {number} [intensity=1] - The light's strength/intensity.
  33897. * @param {number} [width=10] - The width of the light.
  33898. * @param {number} [height=10] - The height of the light.
  33899. */
  33900. constructor( color, intensity, width = 10, height = 10 ) {
  33901. super( color, intensity );
  33902. /**
  33903. * This flag can be used for type testing.
  33904. *
  33905. * @type {boolean}
  33906. * @readonly
  33907. * @default true
  33908. */
  33909. this.isRectAreaLight = true;
  33910. this.type = 'RectAreaLight';
  33911. /**
  33912. * The width of the light.
  33913. *
  33914. * @type {number}
  33915. * @default 10
  33916. */
  33917. this.width = width;
  33918. /**
  33919. * The height of the light.
  33920. *
  33921. * @type {number}
  33922. * @default 10
  33923. */
  33924. this.height = height;
  33925. }
  33926. /**
  33927. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33928. * Changing the power will also change the light's intensity.
  33929. *
  33930. * @type {number}
  33931. */
  33932. get power() {
  33933. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33934. return this.intensity * this.width * this.height * Math.PI;
  33935. }
  33936. set power( power ) {
  33937. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33938. this.intensity = power / ( this.width * this.height * Math.PI );
  33939. }
  33940. copy( source ) {
  33941. super.copy( source );
  33942. this.width = source.width;
  33943. this.height = source.height;
  33944. return this;
  33945. }
  33946. toJSON( meta ) {
  33947. const data = super.toJSON( meta );
  33948. data.object.width = this.width;
  33949. data.object.height = this.height;
  33950. return data;
  33951. }
  33952. }
  33953. /**
  33954. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33955. * to encode lighting information.
  33956. *
  33957. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33958. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33959. */
  33960. class SphericalHarmonics3 {
  33961. /**
  33962. * Constructs a new spherical harmonics.
  33963. */
  33964. constructor() {
  33965. /**
  33966. * This flag can be used for type testing.
  33967. *
  33968. * @type {boolean}
  33969. * @readonly
  33970. * @default true
  33971. */
  33972. this.isSphericalHarmonics3 = true;
  33973. /**
  33974. * An array holding the (9) SH coefficients.
  33975. *
  33976. * @type {Array<Vector3>}
  33977. */
  33978. this.coefficients = [];
  33979. for ( let i = 0; i < 9; i ++ ) {
  33980. this.coefficients.push( new Vector3() );
  33981. }
  33982. }
  33983. /**
  33984. * Sets the given SH coefficients to this instance by copying
  33985. * the values.
  33986. *
  33987. * @param {Array<Vector3>} coefficients - The SH coefficients.
  33988. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33989. */
  33990. set( coefficients ) {
  33991. for ( let i = 0; i < 9; i ++ ) {
  33992. this.coefficients[ i ].copy( coefficients[ i ] );
  33993. }
  33994. return this;
  33995. }
  33996. /**
  33997. * Sets all SH coefficients to `0`.
  33998. *
  33999. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34000. */
  34001. zero() {
  34002. for ( let i = 0; i < 9; i ++ ) {
  34003. this.coefficients[ i ].set( 0, 0, 0 );
  34004. }
  34005. return this;
  34006. }
  34007. /**
  34008. * Returns the radiance in the direction of the given normal.
  34009. *
  34010. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34011. * @param {Vector3} target - The target vector that is used to store the method's result.
  34012. * @return {Vector3} The radiance.
  34013. */
  34014. getAt( normal, target ) {
  34015. // normal is assumed to be unit length
  34016. const x = normal.x, y = normal.y, z = normal.z;
  34017. const coeff = this.coefficients;
  34018. // band 0
  34019. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34020. // band 1
  34021. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34022. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34023. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34024. // band 2
  34025. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34026. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34027. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34028. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34029. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34030. return target;
  34031. }
  34032. /**
  34033. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34034. * direction of the given normal.
  34035. *
  34036. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34037. * @param {Vector3} target - The target vector that is used to store the method's result.
  34038. * @return {Vector3} The irradiance.
  34039. */
  34040. getIrradianceAt( normal, target ) {
  34041. // normal is assumed to be unit length
  34042. const x = normal.x, y = normal.y, z = normal.z;
  34043. const coeff = this.coefficients;
  34044. // band 0
  34045. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34046. // band 1
  34047. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34048. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34049. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34050. // band 2
  34051. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34052. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34053. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34054. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34055. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34056. return target;
  34057. }
  34058. /**
  34059. * Adds the given SH to this instance.
  34060. *
  34061. * @param {SphericalHarmonics3} sh - The SH to add.
  34062. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34063. */
  34064. add( sh ) {
  34065. for ( let i = 0; i < 9; i ++ ) {
  34066. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34067. }
  34068. return this;
  34069. }
  34070. /**
  34071. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34072. * {@link SphericalHarmonics3#scale} at once.
  34073. *
  34074. * @param {SphericalHarmonics3} sh - The SH to add.
  34075. * @param {number} s - The scale factor.
  34076. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34077. */
  34078. addScaledSH( sh, s ) {
  34079. for ( let i = 0; i < 9; i ++ ) {
  34080. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34081. }
  34082. return this;
  34083. }
  34084. /**
  34085. * Scales this SH by the given scale factor.
  34086. *
  34087. * @param {number} s - The scale factor.
  34088. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34089. */
  34090. scale( s ) {
  34091. for ( let i = 0; i < 9; i ++ ) {
  34092. this.coefficients[ i ].multiplyScalar( s );
  34093. }
  34094. return this;
  34095. }
  34096. /**
  34097. * Linear interpolates between the given SH and this instance by the given
  34098. * alpha factor.
  34099. *
  34100. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34101. * @param {number} alpha - The alpha factor.
  34102. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34103. */
  34104. lerp( sh, alpha ) {
  34105. for ( let i = 0; i < 9; i ++ ) {
  34106. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34107. }
  34108. return this;
  34109. }
  34110. /**
  34111. * Returns `true` if this spherical harmonics is equal with the given one.
  34112. *
  34113. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34114. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34115. */
  34116. equals( sh ) {
  34117. for ( let i = 0; i < 9; i ++ ) {
  34118. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34119. return false;
  34120. }
  34121. }
  34122. return true;
  34123. }
  34124. /**
  34125. * Copies the values of the given spherical harmonics to this instance.
  34126. *
  34127. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34128. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34129. */
  34130. copy( sh ) {
  34131. return this.set( sh.coefficients );
  34132. }
  34133. /**
  34134. * Returns a new spherical harmonics with copied values from this instance.
  34135. *
  34136. * @return {SphericalHarmonics3} A clone of this instance.
  34137. */
  34138. clone() {
  34139. return new this.constructor().copy( this );
  34140. }
  34141. /**
  34142. * Sets the SH coefficients of this instance from the given array.
  34143. *
  34144. * @param {Array<number>} array - An array holding the SH coefficients.
  34145. * @param {number} [offset=0] - The array offset where to start copying.
  34146. * @return {SphericalHarmonics3} A clone of this instance.
  34147. */
  34148. fromArray( array, offset = 0 ) {
  34149. const coefficients = this.coefficients;
  34150. for ( let i = 0; i < 9; i ++ ) {
  34151. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34152. }
  34153. return this;
  34154. }
  34155. /**
  34156. * Returns an array with the SH coefficients, or copies them into the provided
  34157. * array. The coefficients are represented as numbers.
  34158. *
  34159. * @param {Array<number>} [array=[]] - The target array.
  34160. * @param {number} [offset=0] - The array offset where to start copying.
  34161. * @return {Array<number>} An array with flat SH coefficients.
  34162. */
  34163. toArray( array = [], offset = 0 ) {
  34164. const coefficients = this.coefficients;
  34165. for ( let i = 0; i < 9; i ++ ) {
  34166. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34167. }
  34168. return array;
  34169. }
  34170. /**
  34171. * Computes the SH basis for the given normal vector.
  34172. *
  34173. * @param {Vector3} normal - The normal.
  34174. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34175. */
  34176. static getBasisAt( normal, shBasis ) {
  34177. // normal is assumed to be unit length
  34178. const x = normal.x, y = normal.y, z = normal.z;
  34179. // band 0
  34180. shBasis[ 0 ] = 0.282095;
  34181. // band 1
  34182. shBasis[ 1 ] = 0.488603 * y;
  34183. shBasis[ 2 ] = 0.488603 * z;
  34184. shBasis[ 3 ] = 0.488603 * x;
  34185. // band 2
  34186. shBasis[ 4 ] = 1.092548 * x * y;
  34187. shBasis[ 5 ] = 1.092548 * y * z;
  34188. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34189. shBasis[ 7 ] = 1.092548 * x * z;
  34190. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34191. }
  34192. }
  34193. /**
  34194. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34195. * classical light sources (e.g. directional, point or spot lights), light
  34196. * probes do not emit light. Instead they store information about light
  34197. * passing through 3D space. During rendering, the light that hits a 3D
  34198. * object is approximated by using the data from the light probe.
  34199. *
  34200. * Light probes are usually created from (radiance) environment maps. The
  34201. * class {@link LightProbeGenerator} can be used to create light probes from
  34202. * cube textures or render targets. However, light estimation data could also
  34203. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34204. * augmented reality content that reacts to real world lighting.
  34205. *
  34206. * The current probe implementation in three.js supports so-called diffuse
  34207. * light probes. This type of light probe is functionally equivalent to an
  34208. * irradiance environment map.
  34209. *
  34210. * @augments Light
  34211. */
  34212. class LightProbe extends Light {
  34213. /**
  34214. * Constructs a new light probe.
  34215. *
  34216. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34217. * @param {number} [intensity=1] - The light's strength/intensity.
  34218. */
  34219. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34220. super( undefined, intensity );
  34221. /**
  34222. * This flag can be used for type testing.
  34223. *
  34224. * @type {boolean}
  34225. * @readonly
  34226. * @default true
  34227. */
  34228. this.isLightProbe = true;
  34229. /**
  34230. * A light probe uses spherical harmonics to encode lighting information.
  34231. *
  34232. * @type {SphericalHarmonics3}
  34233. */
  34234. this.sh = sh;
  34235. }
  34236. copy( source ) {
  34237. super.copy( source );
  34238. this.sh.copy( source.sh );
  34239. return this;
  34240. }
  34241. /**
  34242. * Deserializes the light prove from the given JSON.
  34243. *
  34244. * @param {Object} json - The JSON holding the serialized light probe.
  34245. * @return {LightProbe} A reference to this light probe.
  34246. */
  34247. fromJSON( json ) {
  34248. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34249. this.sh.fromArray( json.sh );
  34250. return this;
  34251. }
  34252. toJSON( meta ) {
  34253. const data = super.toJSON( meta );
  34254. data.object.sh = this.sh.toArray();
  34255. return data;
  34256. }
  34257. }
  34258. /**
  34259. * Class for loading geometries. The files are internally
  34260. * loaded via {@link FileLoader}.
  34261. *
  34262. * ```js
  34263. * const loader = new THREE.MaterialLoader();
  34264. * const material = await loader.loadAsync( 'material.json' );
  34265. * ```
  34266. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34267. *
  34268. * @augments Loader
  34269. */
  34270. class MaterialLoader extends Loader {
  34271. /**
  34272. * Constructs a new material loader.
  34273. *
  34274. * @param {LoadingManager} [manager] - The loading manager.
  34275. */
  34276. constructor( manager ) {
  34277. super( manager );
  34278. /**
  34279. * A dictionary holding textures used by the material.
  34280. *
  34281. * @type {Object<string,Texture>}
  34282. */
  34283. this.textures = {};
  34284. }
  34285. /**
  34286. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34287. *
  34288. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34289. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34290. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34291. * @param {onErrorCallback} onError - Executed when errors occur.
  34292. */
  34293. load( url, onLoad, onProgress, onError ) {
  34294. const scope = this;
  34295. const loader = new FileLoader( scope.manager );
  34296. loader.setPath( scope.path );
  34297. loader.setRequestHeader( scope.requestHeader );
  34298. loader.setWithCredentials( scope.withCredentials );
  34299. loader.load( url, function ( text ) {
  34300. try {
  34301. onLoad( scope.parse( JSON.parse( text ) ) );
  34302. } catch ( e ) {
  34303. if ( onError ) {
  34304. onError( e );
  34305. } else {
  34306. console.error( e );
  34307. }
  34308. scope.manager.itemError( url );
  34309. }
  34310. }, onProgress, onError );
  34311. }
  34312. /**
  34313. * Parses the given JSON object and returns a material.
  34314. *
  34315. * @param {Object} json - The serialized material.
  34316. * @return {Material} The parsed material.
  34317. */
  34318. parse( json ) {
  34319. const textures = this.textures;
  34320. function getTexture( name ) {
  34321. if ( textures[ name ] === undefined ) {
  34322. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34323. }
  34324. return textures[ name ];
  34325. }
  34326. const material = this.createMaterialFromType( json.type );
  34327. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34328. if ( json.name !== undefined ) material.name = json.name;
  34329. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34330. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34331. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34332. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34333. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34334. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34335. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34336. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34337. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34338. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34339. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34340. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34341. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34342. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34343. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34344. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34345. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34346. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34347. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34348. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34349. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34350. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34351. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34352. if ( json.fog !== undefined ) material.fog = json.fog;
  34353. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34354. if ( json.blending !== undefined ) material.blending = json.blending;
  34355. if ( json.combine !== undefined ) material.combine = json.combine;
  34356. if ( json.side !== undefined ) material.side = json.side;
  34357. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34358. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34359. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34360. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34361. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34362. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34363. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34364. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34365. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34366. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34367. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34368. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34369. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34370. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34371. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34372. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34373. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34374. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34375. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34376. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34377. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34378. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34379. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34380. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34381. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34382. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34383. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34384. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34385. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34386. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34387. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34388. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34389. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34390. if ( json.scale !== undefined ) material.scale = json.scale;
  34391. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34392. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34393. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34394. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34395. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34396. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34397. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34398. if ( json.visible !== undefined ) material.visible = json.visible;
  34399. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34400. if ( json.userData !== undefined ) material.userData = json.userData;
  34401. if ( json.vertexColors !== undefined ) {
  34402. if ( typeof json.vertexColors === 'number' ) {
  34403. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34404. } else {
  34405. material.vertexColors = json.vertexColors;
  34406. }
  34407. }
  34408. // Shader Material
  34409. if ( json.uniforms !== undefined ) {
  34410. for ( const name in json.uniforms ) {
  34411. const uniform = json.uniforms[ name ];
  34412. material.uniforms[ name ] = {};
  34413. switch ( uniform.type ) {
  34414. case 't':
  34415. material.uniforms[ name ].value = getTexture( uniform.value );
  34416. break;
  34417. case 'c':
  34418. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34419. break;
  34420. case 'v2':
  34421. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34422. break;
  34423. case 'v3':
  34424. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34425. break;
  34426. case 'v4':
  34427. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34428. break;
  34429. case 'm3':
  34430. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34431. break;
  34432. case 'm4':
  34433. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34434. break;
  34435. default:
  34436. material.uniforms[ name ].value = uniform.value;
  34437. }
  34438. }
  34439. }
  34440. if ( json.defines !== undefined ) material.defines = json.defines;
  34441. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34442. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34443. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34444. if ( json.extensions !== undefined ) {
  34445. for ( const key in json.extensions ) {
  34446. material.extensions[ key ] = json.extensions[ key ];
  34447. }
  34448. }
  34449. if ( json.lights !== undefined ) material.lights = json.lights;
  34450. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34451. // for PointsMaterial
  34452. if ( json.size !== undefined ) material.size = json.size;
  34453. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34454. // maps
  34455. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34456. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34457. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34458. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34459. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34460. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34461. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34462. if ( json.normalScale !== undefined ) {
  34463. let normalScale = json.normalScale;
  34464. if ( Array.isArray( normalScale ) === false ) {
  34465. // Blender exporter used to export a scalar. See #7459
  34466. normalScale = [ normalScale, normalScale ];
  34467. }
  34468. material.normalScale = new Vector2().fromArray( normalScale );
  34469. }
  34470. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34471. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34472. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34473. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34474. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34475. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34476. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34477. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34478. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34479. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34480. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34481. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34482. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34483. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34484. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34485. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34486. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34487. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34488. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34489. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34490. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34491. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34492. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34493. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34494. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34495. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34496. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34497. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34498. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34499. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34500. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34501. return material;
  34502. }
  34503. /**
  34504. * Textures are not embedded in the material JSON so they have
  34505. * to be injected before the loading process starts.
  34506. *
  34507. * @param {Object} value - A dictionary holding textures for material properties.
  34508. * @return {MaterialLoader} A reference to this material loader.
  34509. */
  34510. setTextures( value ) {
  34511. this.textures = value;
  34512. return this;
  34513. }
  34514. /**
  34515. * Creates a material for the given type.
  34516. *
  34517. * @param {string} type - The material type.
  34518. * @return {Material} The new material.
  34519. */
  34520. createMaterialFromType( type ) {
  34521. return MaterialLoader.createMaterialFromType( type );
  34522. }
  34523. /**
  34524. * Creates a material for the given type.
  34525. *
  34526. * @static
  34527. * @param {string} type - The material type.
  34528. * @return {Material} The new material.
  34529. */
  34530. static createMaterialFromType( type ) {
  34531. const materialLib = {
  34532. ShadowMaterial,
  34533. SpriteMaterial,
  34534. RawShaderMaterial,
  34535. ShaderMaterial,
  34536. PointsMaterial,
  34537. MeshPhysicalMaterial,
  34538. MeshStandardMaterial,
  34539. MeshPhongMaterial,
  34540. MeshToonMaterial,
  34541. MeshNormalMaterial,
  34542. MeshLambertMaterial,
  34543. MeshDepthMaterial,
  34544. MeshDistanceMaterial,
  34545. MeshBasicMaterial,
  34546. MeshMatcapMaterial,
  34547. LineDashedMaterial,
  34548. LineBasicMaterial,
  34549. Material
  34550. };
  34551. return new materialLib[ type ]();
  34552. }
  34553. }
  34554. /**
  34555. * A class with loader utility functions.
  34556. */
  34557. class LoaderUtils {
  34558. /**
  34559. * Extracts the base URL from the given URL.
  34560. *
  34561. * @param {string} url -The URL to extract the base URL from.
  34562. * @return {string} The extracted base URL.
  34563. */
  34564. static extractUrlBase( url ) {
  34565. const index = url.lastIndexOf( '/' );
  34566. if ( index === -1 ) return './';
  34567. return url.slice( 0, index + 1 );
  34568. }
  34569. /**
  34570. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34571. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34572. * string.
  34573. *
  34574. * @param {string} url -The URL to resolve.
  34575. * @param {string} path - The base path for relative URLs to be resolved against.
  34576. * @return {string} The resolved URL.
  34577. */
  34578. static resolveURL( url, path ) {
  34579. // Invalid URL
  34580. if ( typeof url !== 'string' || url === '' ) return '';
  34581. // Host Relative URL
  34582. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34583. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34584. }
  34585. // Absolute URL http://,https://,//
  34586. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34587. // Data URI
  34588. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34589. // Blob URL
  34590. if ( /^blob:.*$/i.test( url ) ) return url;
  34591. // Relative URL
  34592. return path + url;
  34593. }
  34594. }
  34595. /**
  34596. * An instanced version of a geometry.
  34597. */
  34598. class InstancedBufferGeometry extends BufferGeometry {
  34599. /**
  34600. * Constructs a new instanced buffer geometry.
  34601. */
  34602. constructor() {
  34603. super();
  34604. /**
  34605. * This flag can be used for type testing.
  34606. *
  34607. * @type {boolean}
  34608. * @readonly
  34609. * @default true
  34610. */
  34611. this.isInstancedBufferGeometry = true;
  34612. this.type = 'InstancedBufferGeometry';
  34613. /**
  34614. * The instance count.
  34615. *
  34616. * @type {number}
  34617. * @default Infinity
  34618. */
  34619. this.instanceCount = Infinity;
  34620. }
  34621. copy( source ) {
  34622. super.copy( source );
  34623. this.instanceCount = source.instanceCount;
  34624. return this;
  34625. }
  34626. toJSON() {
  34627. const data = super.toJSON();
  34628. data.instanceCount = this.instanceCount;
  34629. data.isInstancedBufferGeometry = true;
  34630. return data;
  34631. }
  34632. }
  34633. /**
  34634. * Class for loading geometries. The files are internally
  34635. * loaded via {@link FileLoader}.
  34636. *
  34637. * ```js
  34638. * const loader = new THREE.BufferGeometryLoader();
  34639. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34640. *
  34641. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34642. * const object = new THREE.Mesh( geometry, material );
  34643. * scene.add( object );
  34644. * ```
  34645. *
  34646. * @augments Loader
  34647. */
  34648. class BufferGeometryLoader extends Loader {
  34649. /**
  34650. * Constructs a new geometry loader.
  34651. *
  34652. * @param {LoadingManager} [manager] - The loading manager.
  34653. */
  34654. constructor( manager ) {
  34655. super( manager );
  34656. }
  34657. /**
  34658. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34659. *
  34660. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34661. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34662. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34663. * @param {onErrorCallback} onError - Executed when errors occur.
  34664. */
  34665. load( url, onLoad, onProgress, onError ) {
  34666. const scope = this;
  34667. const loader = new FileLoader( scope.manager );
  34668. loader.setPath( scope.path );
  34669. loader.setRequestHeader( scope.requestHeader );
  34670. loader.setWithCredentials( scope.withCredentials );
  34671. loader.load( url, function ( text ) {
  34672. try {
  34673. onLoad( scope.parse( JSON.parse( text ) ) );
  34674. } catch ( e ) {
  34675. if ( onError ) {
  34676. onError( e );
  34677. } else {
  34678. console.error( e );
  34679. }
  34680. scope.manager.itemError( url );
  34681. }
  34682. }, onProgress, onError );
  34683. }
  34684. /**
  34685. * Parses the given JSON object and returns a geometry.
  34686. *
  34687. * @param {Object} json - The serialized geometry.
  34688. * @return {BufferGeometry} The parsed geometry.
  34689. */
  34690. parse( json ) {
  34691. const interleavedBufferMap = {};
  34692. const arrayBufferMap = {};
  34693. function getInterleavedBuffer( json, uuid ) {
  34694. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34695. const interleavedBuffers = json.interleavedBuffers;
  34696. const interleavedBuffer = interleavedBuffers[ uuid ];
  34697. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34698. const array = getTypedArray( interleavedBuffer.type, buffer );
  34699. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34700. ib.uuid = interleavedBuffer.uuid;
  34701. interleavedBufferMap[ uuid ] = ib;
  34702. return ib;
  34703. }
  34704. function getArrayBuffer( json, uuid ) {
  34705. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34706. const arrayBuffers = json.arrayBuffers;
  34707. const arrayBuffer = arrayBuffers[ uuid ];
  34708. const ab = new Uint32Array( arrayBuffer ).buffer;
  34709. arrayBufferMap[ uuid ] = ab;
  34710. return ab;
  34711. }
  34712. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34713. const index = json.data.index;
  34714. if ( index !== undefined ) {
  34715. const typedArray = getTypedArray( index.type, index.array );
  34716. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34717. }
  34718. const attributes = json.data.attributes;
  34719. for ( const key in attributes ) {
  34720. const attribute = attributes[ key ];
  34721. let bufferAttribute;
  34722. if ( attribute.isInterleavedBufferAttribute ) {
  34723. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34724. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34725. } else {
  34726. const typedArray = getTypedArray( attribute.type, attribute.array );
  34727. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34728. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34729. }
  34730. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34731. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34732. geometry.setAttribute( key, bufferAttribute );
  34733. }
  34734. const morphAttributes = json.data.morphAttributes;
  34735. if ( morphAttributes ) {
  34736. for ( const key in morphAttributes ) {
  34737. const attributeArray = morphAttributes[ key ];
  34738. const array = [];
  34739. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34740. const attribute = attributeArray[ i ];
  34741. let bufferAttribute;
  34742. if ( attribute.isInterleavedBufferAttribute ) {
  34743. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34744. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34745. } else {
  34746. const typedArray = getTypedArray( attribute.type, attribute.array );
  34747. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34748. }
  34749. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34750. array.push( bufferAttribute );
  34751. }
  34752. geometry.morphAttributes[ key ] = array;
  34753. }
  34754. }
  34755. const morphTargetsRelative = json.data.morphTargetsRelative;
  34756. if ( morphTargetsRelative ) {
  34757. geometry.morphTargetsRelative = true;
  34758. }
  34759. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34760. if ( groups !== undefined ) {
  34761. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34762. const group = groups[ i ];
  34763. geometry.addGroup( group.start, group.count, group.materialIndex );
  34764. }
  34765. }
  34766. const boundingSphere = json.data.boundingSphere;
  34767. if ( boundingSphere !== undefined ) {
  34768. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34769. }
  34770. if ( json.name ) geometry.name = json.name;
  34771. if ( json.userData ) geometry.userData = json.userData;
  34772. return geometry;
  34773. }
  34774. }
  34775. /**
  34776. * A loader for loading a JSON resource in the [JSON Object/Scene format]{@link https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4}.
  34777. * The files are internally loaded via {@link FileLoader}.
  34778. *
  34779. * ```js
  34780. * const loader = new THREE.ObjectLoader();
  34781. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34782. * scene.add( obj );
  34783. *
  34784. * // Alternatively, to parse a previously loaded JSON structure
  34785. * const object = await loader.parseAsync( a_json_object );
  34786. * scene.add( object );
  34787. * ```
  34788. *
  34789. * @augments Loader
  34790. */
  34791. class ObjectLoader extends Loader {
  34792. /**
  34793. * Constructs a new object loader.
  34794. *
  34795. * @param {LoadingManager} [manager] - The loading manager.
  34796. */
  34797. constructor( manager ) {
  34798. super( manager );
  34799. }
  34800. /**
  34801. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34802. *
  34803. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34804. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34805. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34806. * @param {onErrorCallback} onError - Executed when errors occur.
  34807. */
  34808. load( url, onLoad, onProgress, onError ) {
  34809. const scope = this;
  34810. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34811. this.resourcePath = this.resourcePath || path;
  34812. const loader = new FileLoader( this.manager );
  34813. loader.setPath( this.path );
  34814. loader.setRequestHeader( this.requestHeader );
  34815. loader.setWithCredentials( this.withCredentials );
  34816. loader.load( url, function ( text ) {
  34817. let json = null;
  34818. try {
  34819. json = JSON.parse( text );
  34820. } catch ( error ) {
  34821. if ( onError !== undefined ) onError( error );
  34822. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34823. return;
  34824. }
  34825. const metadata = json.metadata;
  34826. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34827. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34828. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34829. return;
  34830. }
  34831. scope.parse( json, onLoad );
  34832. }, onProgress, onError );
  34833. }
  34834. /**
  34835. * Async version of {@link ObjectLoader#load}.
  34836. *
  34837. * @async
  34838. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34839. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34840. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34841. */
  34842. async loadAsync( url, onProgress ) {
  34843. const scope = this;
  34844. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34845. this.resourcePath = this.resourcePath || path;
  34846. const loader = new FileLoader( this.manager );
  34847. loader.setPath( this.path );
  34848. loader.setRequestHeader( this.requestHeader );
  34849. loader.setWithCredentials( this.withCredentials );
  34850. const text = await loader.loadAsync( url, onProgress );
  34851. const json = JSON.parse( text );
  34852. const metadata = json.metadata;
  34853. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34854. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34855. }
  34856. return await scope.parseAsync( json );
  34857. }
  34858. /**
  34859. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34860. * but can also be used directly to parse a previously loaded JSON structure.
  34861. *
  34862. * @param {Object} json - The serialized 3D object.
  34863. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34864. * @return {Object3D} The parsed 3D object.
  34865. */
  34866. parse( json, onLoad ) {
  34867. const animations = this.parseAnimations( json.animations );
  34868. const shapes = this.parseShapes( json.shapes );
  34869. const geometries = this.parseGeometries( json.geometries, shapes );
  34870. const images = this.parseImages( json.images, function () {
  34871. if ( onLoad !== undefined ) onLoad( object );
  34872. } );
  34873. const textures = this.parseTextures( json.textures, images );
  34874. const materials = this.parseMaterials( json.materials, textures );
  34875. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34876. const skeletons = this.parseSkeletons( json.skeletons, object );
  34877. this.bindSkeletons( object, skeletons );
  34878. this.bindLightTargets( object );
  34879. //
  34880. if ( onLoad !== undefined ) {
  34881. let hasImages = false;
  34882. for ( const uuid in images ) {
  34883. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34884. hasImages = true;
  34885. break;
  34886. }
  34887. }
  34888. if ( hasImages === false ) onLoad( object );
  34889. }
  34890. return object;
  34891. }
  34892. /**
  34893. * Async version of {@link ObjectLoader#parse}.
  34894. *
  34895. * @param {Object} json - The serialized 3D object.
  34896. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34897. */
  34898. async parseAsync( json ) {
  34899. const animations = this.parseAnimations( json.animations );
  34900. const shapes = this.parseShapes( json.shapes );
  34901. const geometries = this.parseGeometries( json.geometries, shapes );
  34902. const images = await this.parseImagesAsync( json.images );
  34903. const textures = this.parseTextures( json.textures, images );
  34904. const materials = this.parseMaterials( json.materials, textures );
  34905. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34906. const skeletons = this.parseSkeletons( json.skeletons, object );
  34907. this.bindSkeletons( object, skeletons );
  34908. this.bindLightTargets( object );
  34909. return object;
  34910. }
  34911. // internals
  34912. parseShapes( json ) {
  34913. const shapes = {};
  34914. if ( json !== undefined ) {
  34915. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34916. const shape = new Shape().fromJSON( json[ i ] );
  34917. shapes[ shape.uuid ] = shape;
  34918. }
  34919. }
  34920. return shapes;
  34921. }
  34922. parseSkeletons( json, object ) {
  34923. const skeletons = {};
  34924. const bones = {};
  34925. // generate bone lookup table
  34926. object.traverse( function ( child ) {
  34927. if ( child.isBone ) bones[ child.uuid ] = child;
  34928. } );
  34929. // create skeletons
  34930. if ( json !== undefined ) {
  34931. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34932. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34933. skeletons[ skeleton.uuid ] = skeleton;
  34934. }
  34935. }
  34936. return skeletons;
  34937. }
  34938. parseGeometries( json, shapes ) {
  34939. const geometries = {};
  34940. if ( json !== undefined ) {
  34941. const bufferGeometryLoader = new BufferGeometryLoader();
  34942. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34943. let geometry;
  34944. const data = json[ i ];
  34945. switch ( data.type ) {
  34946. case 'BufferGeometry':
  34947. case 'InstancedBufferGeometry':
  34948. geometry = bufferGeometryLoader.parse( data );
  34949. break;
  34950. default:
  34951. if ( data.type in Geometries ) {
  34952. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34953. } else {
  34954. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34955. }
  34956. }
  34957. geometry.uuid = data.uuid;
  34958. if ( data.name !== undefined ) geometry.name = data.name;
  34959. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34960. geometries[ data.uuid ] = geometry;
  34961. }
  34962. }
  34963. return geometries;
  34964. }
  34965. parseMaterials( json, textures ) {
  34966. const cache = {}; // MultiMaterial
  34967. const materials = {};
  34968. if ( json !== undefined ) {
  34969. const loader = new MaterialLoader();
  34970. loader.setTextures( textures );
  34971. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34972. const data = json[ i ];
  34973. if ( cache[ data.uuid ] === undefined ) {
  34974. cache[ data.uuid ] = loader.parse( data );
  34975. }
  34976. materials[ data.uuid ] = cache[ data.uuid ];
  34977. }
  34978. }
  34979. return materials;
  34980. }
  34981. parseAnimations( json ) {
  34982. const animations = {};
  34983. if ( json !== undefined ) {
  34984. for ( let i = 0; i < json.length; i ++ ) {
  34985. const data = json[ i ];
  34986. const clip = AnimationClip.parse( data );
  34987. animations[ clip.uuid ] = clip;
  34988. }
  34989. }
  34990. return animations;
  34991. }
  34992. parseImages( json, onLoad ) {
  34993. const scope = this;
  34994. const images = {};
  34995. let loader;
  34996. function loadImage( url ) {
  34997. scope.manager.itemStart( url );
  34998. return loader.load( url, function () {
  34999. scope.manager.itemEnd( url );
  35000. }, undefined, function () {
  35001. scope.manager.itemError( url );
  35002. scope.manager.itemEnd( url );
  35003. } );
  35004. }
  35005. function deserializeImage( image ) {
  35006. if ( typeof image === 'string' ) {
  35007. const url = image;
  35008. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35009. return loadImage( path );
  35010. } else {
  35011. if ( image.data ) {
  35012. return {
  35013. data: getTypedArray( image.type, image.data ),
  35014. width: image.width,
  35015. height: image.height
  35016. };
  35017. } else {
  35018. return null;
  35019. }
  35020. }
  35021. }
  35022. if ( json !== undefined && json.length > 0 ) {
  35023. const manager = new LoadingManager( onLoad );
  35024. loader = new ImageLoader( manager );
  35025. loader.setCrossOrigin( this.crossOrigin );
  35026. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35027. const image = json[ i ];
  35028. const url = image.url;
  35029. if ( Array.isArray( url ) ) {
  35030. // load array of images e.g CubeTexture
  35031. const imageArray = [];
  35032. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35033. const currentUrl = url[ j ];
  35034. const deserializedImage = deserializeImage( currentUrl );
  35035. if ( deserializedImage !== null ) {
  35036. if ( deserializedImage instanceof HTMLImageElement ) {
  35037. imageArray.push( deserializedImage );
  35038. } else {
  35039. // special case: handle array of data textures for cube textures
  35040. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35041. }
  35042. }
  35043. }
  35044. images[ image.uuid ] = new Source( imageArray );
  35045. } else {
  35046. // load single image
  35047. const deserializedImage = deserializeImage( image.url );
  35048. images[ image.uuid ] = new Source( deserializedImage );
  35049. }
  35050. }
  35051. }
  35052. return images;
  35053. }
  35054. async parseImagesAsync( json ) {
  35055. const scope = this;
  35056. const images = {};
  35057. let loader;
  35058. async function deserializeImage( image ) {
  35059. if ( typeof image === 'string' ) {
  35060. const url = image;
  35061. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35062. return await loader.loadAsync( path );
  35063. } else {
  35064. if ( image.data ) {
  35065. return {
  35066. data: getTypedArray( image.type, image.data ),
  35067. width: image.width,
  35068. height: image.height
  35069. };
  35070. } else {
  35071. return null;
  35072. }
  35073. }
  35074. }
  35075. if ( json !== undefined && json.length > 0 ) {
  35076. loader = new ImageLoader( this.manager );
  35077. loader.setCrossOrigin( this.crossOrigin );
  35078. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35079. const image = json[ i ];
  35080. const url = image.url;
  35081. if ( Array.isArray( url ) ) {
  35082. // load array of images e.g CubeTexture
  35083. const imageArray = [];
  35084. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35085. const currentUrl = url[ j ];
  35086. const deserializedImage = await deserializeImage( currentUrl );
  35087. if ( deserializedImage !== null ) {
  35088. if ( deserializedImage instanceof HTMLImageElement ) {
  35089. imageArray.push( deserializedImage );
  35090. } else {
  35091. // special case: handle array of data textures for cube textures
  35092. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35093. }
  35094. }
  35095. }
  35096. images[ image.uuid ] = new Source( imageArray );
  35097. } else {
  35098. // load single image
  35099. const deserializedImage = await deserializeImage( image.url );
  35100. images[ image.uuid ] = new Source( deserializedImage );
  35101. }
  35102. }
  35103. }
  35104. return images;
  35105. }
  35106. parseTextures( json, images ) {
  35107. function parseConstant( value, type ) {
  35108. if ( typeof value === 'number' ) return value;
  35109. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35110. return type[ value ];
  35111. }
  35112. const textures = {};
  35113. if ( json !== undefined ) {
  35114. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35115. const data = json[ i ];
  35116. if ( data.image === undefined ) {
  35117. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35118. }
  35119. if ( images[ data.image ] === undefined ) {
  35120. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35121. }
  35122. const source = images[ data.image ];
  35123. const image = source.data;
  35124. let texture;
  35125. if ( Array.isArray( image ) ) {
  35126. texture = new CubeTexture();
  35127. if ( image.length === 6 ) texture.needsUpdate = true;
  35128. } else {
  35129. if ( image && image.data ) {
  35130. texture = new DataTexture();
  35131. } else {
  35132. texture = new Texture();
  35133. }
  35134. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35135. }
  35136. texture.source = source;
  35137. texture.uuid = data.uuid;
  35138. if ( data.name !== undefined ) texture.name = data.name;
  35139. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35140. if ( data.channel !== undefined ) texture.channel = data.channel;
  35141. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35142. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35143. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35144. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35145. if ( data.wrap !== undefined ) {
  35146. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35147. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35148. }
  35149. if ( data.format !== undefined ) texture.format = data.format;
  35150. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35151. if ( data.type !== undefined ) texture.type = data.type;
  35152. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35153. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35154. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35155. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35156. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35157. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35158. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35159. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35160. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35161. if ( data.userData !== undefined ) texture.userData = data.userData;
  35162. textures[ data.uuid ] = texture;
  35163. }
  35164. }
  35165. return textures;
  35166. }
  35167. parseObject( data, geometries, materials, textures, animations ) {
  35168. let object;
  35169. function getGeometry( name ) {
  35170. if ( geometries[ name ] === undefined ) {
  35171. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35172. }
  35173. return geometries[ name ];
  35174. }
  35175. function getMaterial( name ) {
  35176. if ( name === undefined ) return undefined;
  35177. if ( Array.isArray( name ) ) {
  35178. const array = [];
  35179. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35180. const uuid = name[ i ];
  35181. if ( materials[ uuid ] === undefined ) {
  35182. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35183. }
  35184. array.push( materials[ uuid ] );
  35185. }
  35186. return array;
  35187. }
  35188. if ( materials[ name ] === undefined ) {
  35189. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35190. }
  35191. return materials[ name ];
  35192. }
  35193. function getTexture( uuid ) {
  35194. if ( textures[ uuid ] === undefined ) {
  35195. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35196. }
  35197. return textures[ uuid ];
  35198. }
  35199. let geometry, material;
  35200. switch ( data.type ) {
  35201. case 'Scene':
  35202. object = new Scene();
  35203. if ( data.background !== undefined ) {
  35204. if ( Number.isInteger( data.background ) ) {
  35205. object.background = new Color( data.background );
  35206. } else {
  35207. object.background = getTexture( data.background );
  35208. }
  35209. }
  35210. if ( data.environment !== undefined ) {
  35211. object.environment = getTexture( data.environment );
  35212. }
  35213. if ( data.fog !== undefined ) {
  35214. if ( data.fog.type === 'Fog' ) {
  35215. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35216. } else if ( data.fog.type === 'FogExp2' ) {
  35217. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35218. }
  35219. if ( data.fog.name !== '' ) {
  35220. object.fog.name = data.fog.name;
  35221. }
  35222. }
  35223. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35224. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35225. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35226. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35227. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35228. break;
  35229. case 'PerspectiveCamera':
  35230. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35231. if ( data.focus !== undefined ) object.focus = data.focus;
  35232. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35233. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35234. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35235. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35236. break;
  35237. case 'OrthographicCamera':
  35238. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35239. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35240. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35241. break;
  35242. case 'AmbientLight':
  35243. object = new AmbientLight( data.color, data.intensity );
  35244. break;
  35245. case 'DirectionalLight':
  35246. object = new DirectionalLight( data.color, data.intensity );
  35247. object.target = data.target || '';
  35248. break;
  35249. case 'PointLight':
  35250. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35251. break;
  35252. case 'RectAreaLight':
  35253. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35254. break;
  35255. case 'SpotLight':
  35256. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35257. object.target = data.target || '';
  35258. break;
  35259. case 'HemisphereLight':
  35260. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35261. break;
  35262. case 'LightProbe':
  35263. object = new LightProbe().fromJSON( data );
  35264. break;
  35265. case 'SkinnedMesh':
  35266. geometry = getGeometry( data.geometry );
  35267. material = getMaterial( data.material );
  35268. object = new SkinnedMesh( geometry, material );
  35269. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35270. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35271. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35272. break;
  35273. case 'Mesh':
  35274. geometry = getGeometry( data.geometry );
  35275. material = getMaterial( data.material );
  35276. object = new Mesh( geometry, material );
  35277. break;
  35278. case 'InstancedMesh':
  35279. geometry = getGeometry( data.geometry );
  35280. material = getMaterial( data.material );
  35281. const count = data.count;
  35282. const instanceMatrix = data.instanceMatrix;
  35283. const instanceColor = data.instanceColor;
  35284. object = new InstancedMesh( geometry, material, count );
  35285. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35286. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35287. break;
  35288. case 'BatchedMesh':
  35289. geometry = getGeometry( data.geometry );
  35290. material = getMaterial( data.material );
  35291. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35292. object.geometry = geometry;
  35293. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35294. object.sortObjects = data.sortObjects;
  35295. object._drawRanges = data.drawRanges;
  35296. object._reservedRanges = data.reservedRanges;
  35297. object._geometryInfo = data.geometryInfo.map( info => {
  35298. let box = null;
  35299. let sphere = null;
  35300. if ( info.boundingBox !== undefined ) {
  35301. box = new Box3().fromJSON( info.boundingBox );
  35302. }
  35303. if ( info.boundingSphere !== undefined ) {
  35304. sphere = new Sphere().fromJSON( info.boundingSphere );
  35305. }
  35306. return {
  35307. ...info,
  35308. boundingBox: box,
  35309. boundingSphere: sphere
  35310. };
  35311. } );
  35312. object._instanceInfo = data.instanceInfo;
  35313. object._availableInstanceIds = data._availableInstanceIds;
  35314. object._availableGeometryIds = data._availableGeometryIds;
  35315. object._nextIndexStart = data.nextIndexStart;
  35316. object._nextVertexStart = data.nextVertexStart;
  35317. object._geometryCount = data.geometryCount;
  35318. object._maxInstanceCount = data.maxInstanceCount;
  35319. object._maxVertexCount = data.maxVertexCount;
  35320. object._maxIndexCount = data.maxIndexCount;
  35321. object._geometryInitialized = data.geometryInitialized;
  35322. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35323. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35324. if ( data.colorsTexture !== undefined ) {
  35325. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35326. }
  35327. if ( data.boundingSphere !== undefined ) {
  35328. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35329. }
  35330. if ( data.boundingBox !== undefined ) {
  35331. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35332. }
  35333. break;
  35334. case 'LOD':
  35335. object = new LOD();
  35336. break;
  35337. case 'Line':
  35338. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35339. break;
  35340. case 'LineLoop':
  35341. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35342. break;
  35343. case 'LineSegments':
  35344. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35345. break;
  35346. case 'PointCloud':
  35347. case 'Points':
  35348. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35349. break;
  35350. case 'Sprite':
  35351. object = new Sprite( getMaterial( data.material ) );
  35352. break;
  35353. case 'Group':
  35354. object = new Group();
  35355. break;
  35356. case 'Bone':
  35357. object = new Bone();
  35358. break;
  35359. default:
  35360. object = new Object3D();
  35361. }
  35362. object.uuid = data.uuid;
  35363. if ( data.name !== undefined ) object.name = data.name;
  35364. if ( data.matrix !== undefined ) {
  35365. object.matrix.fromArray( data.matrix );
  35366. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35367. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35368. } else {
  35369. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35370. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35371. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35372. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35373. }
  35374. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35375. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35376. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35377. if ( data.shadow ) {
  35378. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35379. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35380. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35381. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35382. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35383. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35384. }
  35385. if ( data.visible !== undefined ) object.visible = data.visible;
  35386. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35387. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35388. if ( data.userData !== undefined ) object.userData = data.userData;
  35389. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35390. if ( data.children !== undefined ) {
  35391. const children = data.children;
  35392. for ( let i = 0; i < children.length; i ++ ) {
  35393. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35394. }
  35395. }
  35396. if ( data.animations !== undefined ) {
  35397. const objectAnimations = data.animations;
  35398. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35399. const uuid = objectAnimations[ i ];
  35400. object.animations.push( animations[ uuid ] );
  35401. }
  35402. }
  35403. if ( data.type === 'LOD' ) {
  35404. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35405. const levels = data.levels;
  35406. for ( let l = 0; l < levels.length; l ++ ) {
  35407. const level = levels[ l ];
  35408. const child = object.getObjectByProperty( 'uuid', level.object );
  35409. if ( child !== undefined ) {
  35410. object.addLevel( child, level.distance, level.hysteresis );
  35411. }
  35412. }
  35413. }
  35414. return object;
  35415. }
  35416. bindSkeletons( object, skeletons ) {
  35417. if ( Object.keys( skeletons ).length === 0 ) return;
  35418. object.traverse( function ( child ) {
  35419. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35420. const skeleton = skeletons[ child.skeleton ];
  35421. if ( skeleton === undefined ) {
  35422. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35423. } else {
  35424. child.bind( skeleton, child.bindMatrix );
  35425. }
  35426. }
  35427. } );
  35428. }
  35429. bindLightTargets( object ) {
  35430. object.traverse( function ( child ) {
  35431. if ( child.isDirectionalLight || child.isSpotLight ) {
  35432. const uuid = child.target;
  35433. const target = object.getObjectByProperty( 'uuid', uuid );
  35434. if ( target !== undefined ) {
  35435. child.target = target;
  35436. } else {
  35437. child.target = new Object3D();
  35438. }
  35439. }
  35440. } );
  35441. }
  35442. }
  35443. const TEXTURE_MAPPING = {
  35444. UVMapping: UVMapping,
  35445. CubeReflectionMapping: CubeReflectionMapping,
  35446. CubeRefractionMapping: CubeRefractionMapping,
  35447. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35448. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35449. CubeUVReflectionMapping: CubeUVReflectionMapping
  35450. };
  35451. const TEXTURE_WRAPPING = {
  35452. RepeatWrapping: RepeatWrapping,
  35453. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35454. MirroredRepeatWrapping: MirroredRepeatWrapping
  35455. };
  35456. const TEXTURE_FILTER = {
  35457. NearestFilter: NearestFilter,
  35458. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35459. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35460. LinearFilter: LinearFilter,
  35461. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35462. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35463. };
  35464. const _errorMap = new WeakMap();
  35465. /**
  35466. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35467. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35468. * textures for rendering.
  35469. *
  35470. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35471. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35472. *
  35473. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35474. *
  35475. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35476. *
  35477. * ```js
  35478. * const loader = new THREE.ImageBitmapLoader();
  35479. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35480. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35481. *
  35482. * const texture = new THREE.Texture( imageBitmap );
  35483. * texture.needsUpdate = true;
  35484. * ```
  35485. *
  35486. * @augments Loader
  35487. */
  35488. class ImageBitmapLoader extends Loader {
  35489. /**
  35490. * Constructs a new image bitmap loader.
  35491. *
  35492. * @param {LoadingManager} [manager] - The loading manager.
  35493. */
  35494. constructor( manager ) {
  35495. super( manager );
  35496. /**
  35497. * This flag can be used for type testing.
  35498. *
  35499. * @type {boolean}
  35500. * @readonly
  35501. * @default true
  35502. */
  35503. this.isImageBitmapLoader = true;
  35504. if ( typeof createImageBitmap === 'undefined' ) {
  35505. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35506. }
  35507. if ( typeof fetch === 'undefined' ) {
  35508. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35509. }
  35510. /**
  35511. * Represents the loader options.
  35512. *
  35513. * @type {Object}
  35514. * @default {premultiplyAlpha:'none'}
  35515. */
  35516. this.options = { premultiplyAlpha: 'none' };
  35517. /**
  35518. * Used for aborting requests.
  35519. *
  35520. * @private
  35521. * @type {AbortController}
  35522. */
  35523. this._abortController = new AbortController();
  35524. }
  35525. /**
  35526. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35527. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35528. *
  35529. * @param {Object} options - The loader options to set.
  35530. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35531. */
  35532. setOptions( options ) {
  35533. this.options = options;
  35534. return this;
  35535. }
  35536. /**
  35537. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35538. *
  35539. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35540. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35541. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35542. * @param {onErrorCallback} onError - Executed when errors occur.
  35543. * @return {ImageBitmap|undefined} The image bitmap.
  35544. */
  35545. load( url, onLoad, onProgress, onError ) {
  35546. if ( url === undefined ) url = '';
  35547. if ( this.path !== undefined ) url = this.path + url;
  35548. url = this.manager.resolveURL( url );
  35549. const scope = this;
  35550. const cached = Cache.get( `image-bitmap:${url}` );
  35551. if ( cached !== undefined ) {
  35552. scope.manager.itemStart( url );
  35553. // If cached is a promise, wait for it to resolve
  35554. if ( cached.then ) {
  35555. cached.then( imageBitmap => {
  35556. // check if there is an error for the cached promise
  35557. if ( _errorMap.has( cached ) === true ) {
  35558. if ( onError ) onError( _errorMap.get( cached ) );
  35559. scope.manager.itemError( url );
  35560. scope.manager.itemEnd( url );
  35561. } else {
  35562. if ( onLoad ) onLoad( imageBitmap );
  35563. scope.manager.itemEnd( url );
  35564. return imageBitmap;
  35565. }
  35566. } );
  35567. return;
  35568. }
  35569. // If cached is not a promise (i.e., it's already an imageBitmap)
  35570. setTimeout( function () {
  35571. if ( onLoad ) onLoad( cached );
  35572. scope.manager.itemEnd( url );
  35573. }, 0 );
  35574. return cached;
  35575. }
  35576. const fetchOptions = {};
  35577. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35578. fetchOptions.headers = this.requestHeader;
  35579. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35580. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35581. return res.blob();
  35582. } ).then( function ( blob ) {
  35583. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35584. } ).then( function ( imageBitmap ) {
  35585. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35586. if ( onLoad ) onLoad( imageBitmap );
  35587. scope.manager.itemEnd( url );
  35588. return imageBitmap;
  35589. } ).catch( function ( e ) {
  35590. if ( onError ) onError( e );
  35591. _errorMap.set( promise, e );
  35592. Cache.remove( `image-bitmap:${url}` );
  35593. scope.manager.itemError( url );
  35594. scope.manager.itemEnd( url );
  35595. } );
  35596. Cache.add( `image-bitmap:${url}`, promise );
  35597. scope.manager.itemStart( url );
  35598. }
  35599. /**
  35600. * Aborts ongoing fetch requests.
  35601. *
  35602. * @return {ImageBitmapLoader} A reference to this instance.
  35603. */
  35604. abort() {
  35605. this._abortController.abort();
  35606. this._abortController = new AbortController();
  35607. return this;
  35608. }
  35609. }
  35610. let _context;
  35611. /**
  35612. * Manages the global audio context in the engine.
  35613. *
  35614. * @hideconstructor
  35615. */
  35616. class AudioContext {
  35617. /**
  35618. * Returns the global native audio context.
  35619. *
  35620. * @return {AudioContext} The native audio context.
  35621. */
  35622. static getContext() {
  35623. if ( _context === undefined ) {
  35624. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35625. }
  35626. return _context;
  35627. }
  35628. /**
  35629. * Allows to set the global native audio context from outside.
  35630. *
  35631. * @param {AudioContext} value - The native context to set.
  35632. */
  35633. static setContext( value ) {
  35634. _context = value;
  35635. }
  35636. }
  35637. /**
  35638. * Class for loading audio buffers. Audios are internally
  35639. * loaded via {@link FileLoader}.
  35640. *
  35641. * ```js
  35642. * const audioListener = new THREE.AudioListener();
  35643. * const ambientSound = new THREE.Audio( audioListener );
  35644. *
  35645. * const loader = new THREE.AudioLoader();
  35646. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35647. *
  35648. * ambientSound.setBuffer( audioBuffer );
  35649. * ambientSound.play();
  35650. * ```
  35651. *
  35652. * @augments Loader
  35653. */
  35654. class AudioLoader extends Loader {
  35655. /**
  35656. * Constructs a new audio loader.
  35657. *
  35658. * @param {LoadingManager} [manager] - The loading manager.
  35659. */
  35660. constructor( manager ) {
  35661. super( manager );
  35662. }
  35663. /**
  35664. * Starts loading from the given URL and passes the loaded audio buffer
  35665. * to the `onLoad()` callback.
  35666. *
  35667. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35668. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35669. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35670. * @param {onErrorCallback} onError - Executed when errors occur.
  35671. */
  35672. load( url, onLoad, onProgress, onError ) {
  35673. const scope = this;
  35674. const loader = new FileLoader( this.manager );
  35675. loader.setResponseType( 'arraybuffer' );
  35676. loader.setPath( this.path );
  35677. loader.setRequestHeader( this.requestHeader );
  35678. loader.setWithCredentials( this.withCredentials );
  35679. loader.load( url, function ( buffer ) {
  35680. try {
  35681. // Create a copy of the buffer. The `decodeAudioData` method
  35682. // detaches the buffer when complete, preventing reuse.
  35683. const bufferCopy = buffer.slice( 0 );
  35684. const context = AudioContext.getContext();
  35685. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35686. onLoad( audioBuffer );
  35687. } ).catch( handleError );
  35688. } catch ( e ) {
  35689. handleError( e );
  35690. }
  35691. }, onProgress, onError );
  35692. function handleError( e ) {
  35693. if ( onError ) {
  35694. onError( e );
  35695. } else {
  35696. console.error( e );
  35697. }
  35698. scope.manager.itemError( url );
  35699. }
  35700. }
  35701. }
  35702. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35703. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35704. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35705. /**
  35706. * A special type of camera that uses two perspective cameras with
  35707. * stereoscopic projection. Can be used for rendering stereo effects
  35708. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35709. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35710. */
  35711. class StereoCamera {
  35712. /**
  35713. * Constructs a new stereo camera.
  35714. */
  35715. constructor() {
  35716. /**
  35717. * The type property is used for detecting the object type
  35718. * in context of serialization/deserialization.
  35719. *
  35720. * @type {string}
  35721. * @readonly
  35722. */
  35723. this.type = 'StereoCamera';
  35724. /**
  35725. * The aspect.
  35726. *
  35727. * @type {number}
  35728. * @default 1
  35729. */
  35730. this.aspect = 1;
  35731. /**
  35732. * The eye separation which represents the distance
  35733. * between the left and right camera.
  35734. *
  35735. * @type {number}
  35736. * @default 0.064
  35737. */
  35738. this.eyeSep = 0.064;
  35739. /**
  35740. * The camera representing the left eye. This is added to layer `1` so objects to be
  35741. * rendered by the left camera must also be added to this layer.
  35742. *
  35743. * @type {PerspectiveCamera}
  35744. */
  35745. this.cameraL = new PerspectiveCamera();
  35746. this.cameraL.layers.enable( 1 );
  35747. this.cameraL.matrixAutoUpdate = false;
  35748. /**
  35749. * The camera representing the right eye. This is added to layer `2` so objects to be
  35750. * rendered by the right camera must also be added to this layer.
  35751. *
  35752. * @type {PerspectiveCamera}
  35753. */
  35754. this.cameraR = new PerspectiveCamera();
  35755. this.cameraR.layers.enable( 2 );
  35756. this.cameraR.matrixAutoUpdate = false;
  35757. this._cache = {
  35758. focus: null,
  35759. fov: null,
  35760. aspect: null,
  35761. near: null,
  35762. far: null,
  35763. zoom: null,
  35764. eyeSep: null
  35765. };
  35766. }
  35767. /**
  35768. * Updates the stereo camera based on the given perspective camera.
  35769. *
  35770. * @param {PerspectiveCamera} camera - The perspective camera.
  35771. */
  35772. update( camera ) {
  35773. const cache = this._cache;
  35774. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35775. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35776. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35777. if ( needsUpdate ) {
  35778. cache.focus = camera.focus;
  35779. cache.fov = camera.fov;
  35780. cache.aspect = camera.aspect * this.aspect;
  35781. cache.near = camera.near;
  35782. cache.far = camera.far;
  35783. cache.zoom = camera.zoom;
  35784. cache.eyeSep = this.eyeSep;
  35785. // Off-axis stereoscopic effect based on
  35786. // http://paulbourke.net/stereographics/stereorender/
  35787. _projectionMatrix.copy( camera.projectionMatrix );
  35788. const eyeSepHalf = cache.eyeSep / 2;
  35789. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35790. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35791. let xmin, xmax;
  35792. // translate xOffset
  35793. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35794. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35795. // for left eye
  35796. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35797. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35798. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35799. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35800. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35801. // for right eye
  35802. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35803. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35804. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35805. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35806. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35807. }
  35808. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35809. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35810. }
  35811. }
  35812. /**
  35813. * This type of camera can be used in order to efficiently render a scene with a
  35814. * predefined set of cameras. This is an important performance aspect for
  35815. * rendering VR scenes.
  35816. *
  35817. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35818. * to define for each sub camera the `viewport` property which determines the
  35819. * part of the viewport that is rendered with this camera.
  35820. *
  35821. * @augments PerspectiveCamera
  35822. */
  35823. class ArrayCamera extends PerspectiveCamera {
  35824. /**
  35825. * Constructs a new array camera.
  35826. *
  35827. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35828. */
  35829. constructor( array = [] ) {
  35830. super();
  35831. /**
  35832. * This flag can be used for type testing.
  35833. *
  35834. * @type {boolean}
  35835. * @readonly
  35836. * @default true
  35837. */
  35838. this.isArrayCamera = true;
  35839. /**
  35840. * Whether this camera is used with multiview rendering or not.
  35841. *
  35842. * @type {boolean}
  35843. * @readonly
  35844. * @default false
  35845. */
  35846. this.isMultiViewCamera = false;
  35847. /**
  35848. * An array of perspective sub cameras.
  35849. *
  35850. * @type {Array<PerspectiveCamera>}
  35851. */
  35852. this.cameras = array;
  35853. }
  35854. }
  35855. /**
  35856. * Class for keeping track of time.
  35857. */
  35858. class Clock {
  35859. /**
  35860. * Constructs a new clock.
  35861. *
  35862. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35863. * `getDelta()` is called for the first time.
  35864. */
  35865. constructor( autoStart = true ) {
  35866. /**
  35867. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35868. * for the first time.
  35869. *
  35870. * @type {boolean}
  35871. * @default true
  35872. */
  35873. this.autoStart = autoStart;
  35874. /**
  35875. * Holds the time at which the clock's `start()` method was last called.
  35876. *
  35877. * @type {number}
  35878. * @default 0
  35879. */
  35880. this.startTime = 0;
  35881. /**
  35882. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35883. * `getDelta()` methods were last called.
  35884. *
  35885. * @type {number}
  35886. * @default 0
  35887. */
  35888. this.oldTime = 0;
  35889. /**
  35890. * Keeps track of the total time that the clock has been running.
  35891. *
  35892. * @type {number}
  35893. * @default 0
  35894. */
  35895. this.elapsedTime = 0;
  35896. /**
  35897. * Whether the clock is running or not.
  35898. *
  35899. * @type {boolean}
  35900. * @default true
  35901. */
  35902. this.running = false;
  35903. }
  35904. /**
  35905. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35906. * called by the class.
  35907. */
  35908. start() {
  35909. this.startTime = performance.now();
  35910. this.oldTime = this.startTime;
  35911. this.elapsedTime = 0;
  35912. this.running = true;
  35913. }
  35914. /**
  35915. * Stops the clock.
  35916. */
  35917. stop() {
  35918. this.getElapsedTime();
  35919. this.running = false;
  35920. this.autoStart = false;
  35921. }
  35922. /**
  35923. * Returns the elapsed time in seconds.
  35924. *
  35925. * @return {number} The elapsed time.
  35926. */
  35927. getElapsedTime() {
  35928. this.getDelta();
  35929. return this.elapsedTime;
  35930. }
  35931. /**
  35932. * Returns the delta time in seconds.
  35933. *
  35934. * @return {number} The delta time.
  35935. */
  35936. getDelta() {
  35937. let diff = 0;
  35938. if ( this.autoStart && ! this.running ) {
  35939. this.start();
  35940. return 0;
  35941. }
  35942. if ( this.running ) {
  35943. const newTime = performance.now();
  35944. diff = ( newTime - this.oldTime ) / 1000;
  35945. this.oldTime = newTime;
  35946. this.elapsedTime += diff;
  35947. }
  35948. return diff;
  35949. }
  35950. }
  35951. const _position$1 = /*@__PURE__*/ new Vector3();
  35952. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35953. const _scale$1 = /*@__PURE__*/ new Vector3();
  35954. const _forward = /*@__PURE__*/ new Vector3();
  35955. const _up = /*@__PURE__*/ new Vector3();
  35956. /**
  35957. * The class represents a virtual listener of the all positional and non-positional audio effects
  35958. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35959. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35960. *
  35961. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35962. * camera represents the 3D transformation of the listener.
  35963. *
  35964. * @augments Object3D
  35965. */
  35966. class AudioListener extends Object3D {
  35967. /**
  35968. * Constructs a new audio listener.
  35969. */
  35970. constructor() {
  35971. super();
  35972. this.type = 'AudioListener';
  35973. /**
  35974. * The native audio context.
  35975. *
  35976. * @type {AudioContext}
  35977. * @readonly
  35978. */
  35979. this.context = AudioContext.getContext();
  35980. /**
  35981. * The gain node used for volume control.
  35982. *
  35983. * @type {GainNode}
  35984. * @readonly
  35985. */
  35986. this.gain = this.context.createGain();
  35987. this.gain.connect( this.context.destination );
  35988. /**
  35989. * An optional filter.
  35990. *
  35991. * Defined via {@link AudioListener#setFilter}.
  35992. *
  35993. * @type {?AudioNode}
  35994. * @default null
  35995. * @readonly
  35996. */
  35997. this.filter = null;
  35998. /**
  35999. * Time delta values required for `linearRampToValueAtTime()` usage.
  36000. *
  36001. * @type {number}
  36002. * @default 0
  36003. * @readonly
  36004. */
  36005. this.timeDelta = 0;
  36006. // private
  36007. this._clock = new Clock();
  36008. }
  36009. /**
  36010. * Returns the listener's input node.
  36011. *
  36012. * This method is used by other audio nodes to connect to this listener.
  36013. *
  36014. * @return {GainNode} The input node.
  36015. */
  36016. getInput() {
  36017. return this.gain;
  36018. }
  36019. /**
  36020. * Removes the current filter from this listener.
  36021. *
  36022. * @return {AudioListener} A reference to this listener.
  36023. */
  36024. removeFilter() {
  36025. if ( this.filter !== null ) {
  36026. this.gain.disconnect( this.filter );
  36027. this.filter.disconnect( this.context.destination );
  36028. this.gain.connect( this.context.destination );
  36029. this.filter = null;
  36030. }
  36031. return this;
  36032. }
  36033. /**
  36034. * Returns the current set filter.
  36035. *
  36036. * @return {?AudioNode} The filter.
  36037. */
  36038. getFilter() {
  36039. return this.filter;
  36040. }
  36041. /**
  36042. * Sets the given filter to this listener.
  36043. *
  36044. * @param {AudioNode} value - The filter to set.
  36045. * @return {AudioListener} A reference to this listener.
  36046. */
  36047. setFilter( value ) {
  36048. if ( this.filter !== null ) {
  36049. this.gain.disconnect( this.filter );
  36050. this.filter.disconnect( this.context.destination );
  36051. } else {
  36052. this.gain.disconnect( this.context.destination );
  36053. }
  36054. this.filter = value;
  36055. this.gain.connect( this.filter );
  36056. this.filter.connect( this.context.destination );
  36057. return this;
  36058. }
  36059. /**
  36060. * Returns the applications master volume.
  36061. *
  36062. * @return {number} The master volume.
  36063. */
  36064. getMasterVolume() {
  36065. return this.gain.gain.value;
  36066. }
  36067. /**
  36068. * Sets the applications master volume. This volume setting affects
  36069. * all audio nodes in the scene.
  36070. *
  36071. * @param {number} value - The master volume to set.
  36072. * @return {AudioListener} A reference to this listener.
  36073. */
  36074. setMasterVolume( value ) {
  36075. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36076. return this;
  36077. }
  36078. updateMatrixWorld( force ) {
  36079. super.updateMatrixWorld( force );
  36080. const listener = this.context.listener;
  36081. this.timeDelta = this._clock.getDelta();
  36082. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36083. // the initial forward and up directions must be orthogonal
  36084. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36085. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36086. if ( listener.positionX ) {
  36087. // code path for Chrome (see #14393)
  36088. const endTime = this.context.currentTime + this.timeDelta;
  36089. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36090. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36091. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36092. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36093. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36094. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36095. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36096. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36097. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36098. } else {
  36099. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36100. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36101. }
  36102. }
  36103. }
  36104. /**
  36105. * Represents a non-positional ( global ) audio object.
  36106. *
  36107. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36108. *
  36109. * ```js
  36110. * // create an AudioListener and add it to the camera
  36111. * const listener = new THREE.AudioListener();
  36112. * camera.add( listener );
  36113. *
  36114. * // create a global audio source
  36115. * const sound = new THREE.Audio( listener );
  36116. *
  36117. * // load a sound and set it as the Audio object's buffer
  36118. * const audioLoader = new THREE.AudioLoader();
  36119. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36120. * sound.setBuffer( buffer );
  36121. * sound.setLoop( true );
  36122. * sound.setVolume( 0.5 );
  36123. * sound.play();
  36124. * });
  36125. * ```
  36126. *
  36127. * @augments Object3D
  36128. */
  36129. class Audio extends Object3D {
  36130. /**
  36131. * Constructs a new audio.
  36132. *
  36133. * @param {AudioListener} listener - The global audio listener.
  36134. */
  36135. constructor( listener ) {
  36136. super();
  36137. this.type = 'Audio';
  36138. /**
  36139. * The global audio listener.
  36140. *
  36141. * @type {AudioListener}
  36142. * @readonly
  36143. */
  36144. this.listener = listener;
  36145. /**
  36146. * The audio context.
  36147. *
  36148. * @type {AudioContext}
  36149. * @readonly
  36150. */
  36151. this.context = listener.context;
  36152. /**
  36153. * The gain node used for volume control.
  36154. *
  36155. * @type {GainNode}
  36156. * @readonly
  36157. */
  36158. this.gain = this.context.createGain();
  36159. this.gain.connect( listener.getInput() );
  36160. /**
  36161. * Whether to start playback automatically or not.
  36162. *
  36163. * @type {boolean}
  36164. * @default false
  36165. */
  36166. this.autoplay = false;
  36167. /**
  36168. * A reference to an audio buffer.
  36169. *
  36170. * Defined via {@link Audio#setBuffer}.
  36171. *
  36172. * @type {?AudioBuffer}
  36173. * @default null
  36174. * @readonly
  36175. */
  36176. this.buffer = null;
  36177. /**
  36178. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36179. * +/- 1200 is an octave.
  36180. *
  36181. * Defined via {@link Audio#setDetune}.
  36182. *
  36183. * @type {number}
  36184. * @default 0
  36185. * @readonly
  36186. */
  36187. this.detune = 0;
  36188. /**
  36189. * Whether the audio should loop or not.
  36190. *
  36191. * Defined via {@link Audio#setLoop}.
  36192. *
  36193. * @type {boolean}
  36194. * @default false
  36195. * @readonly
  36196. */
  36197. this.loop = false;
  36198. /**
  36199. * Defines where in the audio buffer the replay should
  36200. * start, in seconds.
  36201. *
  36202. * @type {number}
  36203. * @default 0
  36204. */
  36205. this.loopStart = 0;
  36206. /**
  36207. * Defines where in the audio buffer the replay should
  36208. * stop, in seconds.
  36209. *
  36210. * @type {number}
  36211. * @default 0
  36212. */
  36213. this.loopEnd = 0;
  36214. /**
  36215. * An offset to the time within the audio buffer the playback
  36216. * should begin, in seconds.
  36217. *
  36218. * @type {number}
  36219. * @default 0
  36220. */
  36221. this.offset = 0;
  36222. /**
  36223. * Overrides the default duration of the audio.
  36224. *
  36225. * @type {undefined|number}
  36226. * @default undefined
  36227. */
  36228. this.duration = undefined;
  36229. /**
  36230. * The playback speed.
  36231. *
  36232. * Defined via {@link Audio#setPlaybackRate}.
  36233. *
  36234. * @type {number}
  36235. * @readonly
  36236. * @default 1
  36237. */
  36238. this.playbackRate = 1;
  36239. /**
  36240. * Indicates whether the audio is playing or not.
  36241. *
  36242. * This flag will be automatically set when using {@link Audio#play},
  36243. * {@link Audio#pause}, {@link Audio#stop}.
  36244. *
  36245. * @type {boolean}
  36246. * @readonly
  36247. * @default false
  36248. */
  36249. this.isPlaying = false;
  36250. /**
  36251. * Indicates whether the audio playback can be controlled
  36252. * with method like {@link Audio#play} or {@link Audio#pause}.
  36253. *
  36254. * This flag will be automatically set when audio sources are
  36255. * defined.
  36256. *
  36257. * @type {boolean}
  36258. * @readonly
  36259. * @default true
  36260. */
  36261. this.hasPlaybackControl = true;
  36262. /**
  36263. * Holds a reference to the current audio source.
  36264. *
  36265. * The property is automatically by one of the `set*()` methods.
  36266. *
  36267. * @type {?AudioNode}
  36268. * @readonly
  36269. * @default null
  36270. */
  36271. this.source = null;
  36272. /**
  36273. * Defines the source type.
  36274. *
  36275. * The property is automatically by one of the `set*()` methods.
  36276. *
  36277. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36278. * @readonly
  36279. * @default 'empty'
  36280. */
  36281. this.sourceType = 'empty';
  36282. this._startedAt = 0;
  36283. this._progress = 0;
  36284. this._connected = false;
  36285. /**
  36286. * Can be used to apply a variety of low-order filters to create
  36287. * more complex sound effects e.g. via `BiquadFilterNode`.
  36288. *
  36289. * The property is automatically set by {@link Audio#setFilters}.
  36290. *
  36291. * @type {Array<AudioNode>}
  36292. * @readonly
  36293. */
  36294. this.filters = [];
  36295. }
  36296. /**
  36297. * Returns the output audio node.
  36298. *
  36299. * @return {GainNode} The output node.
  36300. */
  36301. getOutput() {
  36302. return this.gain;
  36303. }
  36304. /**
  36305. * Sets the given audio node as the source of this instance.
  36306. *
  36307. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36308. *
  36309. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36310. * @return {Audio} A reference to this instance.
  36311. */
  36312. setNodeSource( audioNode ) {
  36313. this.hasPlaybackControl = false;
  36314. this.sourceType = 'audioNode';
  36315. this.source = audioNode;
  36316. this.connect();
  36317. return this;
  36318. }
  36319. /**
  36320. * Sets the given media element as the source of this instance.
  36321. *
  36322. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36323. *
  36324. * @param {HTMLMediaElement} mediaElement - The media element.
  36325. * @return {Audio} A reference to this instance.
  36326. */
  36327. setMediaElementSource( mediaElement ) {
  36328. this.hasPlaybackControl = false;
  36329. this.sourceType = 'mediaNode';
  36330. this.source = this.context.createMediaElementSource( mediaElement );
  36331. this.connect();
  36332. return this;
  36333. }
  36334. /**
  36335. * Sets the given media stream as the source of this instance.
  36336. *
  36337. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36338. *
  36339. * @param {MediaStream} mediaStream - The media stream.
  36340. * @return {Audio} A reference to this instance.
  36341. */
  36342. setMediaStreamSource( mediaStream ) {
  36343. this.hasPlaybackControl = false;
  36344. this.sourceType = 'mediaStreamNode';
  36345. this.source = this.context.createMediaStreamSource( mediaStream );
  36346. this.connect();
  36347. return this;
  36348. }
  36349. /**
  36350. * Sets the given audio buffer as the source of this instance.
  36351. *
  36352. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36353. *
  36354. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36355. * @return {Audio} A reference to this instance.
  36356. */
  36357. setBuffer( audioBuffer ) {
  36358. this.buffer = audioBuffer;
  36359. this.sourceType = 'buffer';
  36360. if ( this.autoplay ) this.play();
  36361. return this;
  36362. }
  36363. /**
  36364. * Starts the playback of the audio.
  36365. *
  36366. * Can only be used with compatible audio sources that allow playback control.
  36367. *
  36368. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36369. * @return {Audio|undefined} A reference to this instance.
  36370. */
  36371. play( delay = 0 ) {
  36372. if ( this.isPlaying === true ) {
  36373. console.warn( 'THREE.Audio: Audio is already playing.' );
  36374. return;
  36375. }
  36376. if ( this.hasPlaybackControl === false ) {
  36377. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36378. return;
  36379. }
  36380. this._startedAt = this.context.currentTime + delay;
  36381. const source = this.context.createBufferSource();
  36382. source.buffer = this.buffer;
  36383. source.loop = this.loop;
  36384. source.loopStart = this.loopStart;
  36385. source.loopEnd = this.loopEnd;
  36386. source.onended = this.onEnded.bind( this );
  36387. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36388. this.isPlaying = true;
  36389. this.source = source;
  36390. this.setDetune( this.detune );
  36391. this.setPlaybackRate( this.playbackRate );
  36392. return this.connect();
  36393. }
  36394. /**
  36395. * Pauses the playback of the audio.
  36396. *
  36397. * Can only be used with compatible audio sources that allow playback control.
  36398. *
  36399. * @return {Audio|undefined} A reference to this instance.
  36400. */
  36401. pause() {
  36402. if ( this.hasPlaybackControl === false ) {
  36403. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36404. return;
  36405. }
  36406. if ( this.isPlaying === true ) {
  36407. // update current progress
  36408. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36409. if ( this.loop === true ) {
  36410. // ensure _progress does not exceed duration with looped audios
  36411. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36412. }
  36413. this.source.stop();
  36414. this.source.onended = null;
  36415. this.isPlaying = false;
  36416. }
  36417. return this;
  36418. }
  36419. /**
  36420. * Stops the playback of the audio.
  36421. *
  36422. * Can only be used with compatible audio sources that allow playback control.
  36423. *
  36424. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36425. * @return {Audio|undefined} A reference to this instance.
  36426. */
  36427. stop( delay = 0 ) {
  36428. if ( this.hasPlaybackControl === false ) {
  36429. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36430. return;
  36431. }
  36432. this._progress = 0;
  36433. if ( this.source !== null ) {
  36434. this.source.stop( this.context.currentTime + delay );
  36435. this.source.onended = null;
  36436. }
  36437. this.isPlaying = false;
  36438. return this;
  36439. }
  36440. /**
  36441. * Connects to the audio source. This is used internally on
  36442. * initialisation and when setting / removing filters.
  36443. *
  36444. * @return {Audio} A reference to this instance.
  36445. */
  36446. connect() {
  36447. if ( this.filters.length > 0 ) {
  36448. this.source.connect( this.filters[ 0 ] );
  36449. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36450. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36451. }
  36452. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36453. } else {
  36454. this.source.connect( this.getOutput() );
  36455. }
  36456. this._connected = true;
  36457. return this;
  36458. }
  36459. /**
  36460. * Disconnects to the audio source. This is used internally on
  36461. * initialisation and when setting / removing filters.
  36462. *
  36463. * @return {Audio|undefined} A reference to this instance.
  36464. */
  36465. disconnect() {
  36466. if ( this._connected === false ) {
  36467. return;
  36468. }
  36469. if ( this.filters.length > 0 ) {
  36470. this.source.disconnect( this.filters[ 0 ] );
  36471. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36472. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36473. }
  36474. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36475. } else {
  36476. this.source.disconnect( this.getOutput() );
  36477. }
  36478. this._connected = false;
  36479. return this;
  36480. }
  36481. /**
  36482. * Returns the current set filters.
  36483. *
  36484. * @return {Array<AudioNode>} The list of filters.
  36485. */
  36486. getFilters() {
  36487. return this.filters;
  36488. }
  36489. /**
  36490. * Sets an array of filters and connects them with the audio source.
  36491. *
  36492. * @param {Array<AudioNode>} [value] - A list of filters.
  36493. * @return {Audio} A reference to this instance.
  36494. */
  36495. setFilters( value ) {
  36496. if ( ! value ) value = [];
  36497. if ( this._connected === true ) {
  36498. this.disconnect();
  36499. this.filters = value.slice();
  36500. this.connect();
  36501. } else {
  36502. this.filters = value.slice();
  36503. }
  36504. return this;
  36505. }
  36506. /**
  36507. * Defines the detuning of oscillation in cents.
  36508. *
  36509. * @param {number} value - The detuning of oscillation in cents.
  36510. * @return {Audio} A reference to this instance.
  36511. */
  36512. setDetune( value ) {
  36513. this.detune = value;
  36514. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36515. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36516. }
  36517. return this;
  36518. }
  36519. /**
  36520. * Returns the detuning of oscillation in cents.
  36521. *
  36522. * @return {number} The detuning of oscillation in cents.
  36523. */
  36524. getDetune() {
  36525. return this.detune;
  36526. }
  36527. /**
  36528. * Returns the first filter in the list of filters.
  36529. *
  36530. * @return {AudioNode|undefined} The first filter in the list of filters.
  36531. */
  36532. getFilter() {
  36533. return this.getFilters()[ 0 ];
  36534. }
  36535. /**
  36536. * Applies a single filter node to the audio.
  36537. *
  36538. * @param {AudioNode} [filter] - The filter to set.
  36539. * @return {Audio} A reference to this instance.
  36540. */
  36541. setFilter( filter ) {
  36542. return this.setFilters( filter ? [ filter ] : [] );
  36543. }
  36544. /**
  36545. * Sets the playback rate.
  36546. *
  36547. * Can only be used with compatible audio sources that allow playback control.
  36548. *
  36549. * @param {number} [value] - The playback rate to set.
  36550. * @return {Audio|undefined} A reference to this instance.
  36551. */
  36552. setPlaybackRate( value ) {
  36553. if ( this.hasPlaybackControl === false ) {
  36554. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36555. return;
  36556. }
  36557. this.playbackRate = value;
  36558. if ( this.isPlaying === true ) {
  36559. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36560. }
  36561. return this;
  36562. }
  36563. /**
  36564. * Returns the current playback rate.
  36565. * @return {number} The playback rate.
  36566. */
  36567. getPlaybackRate() {
  36568. return this.playbackRate;
  36569. }
  36570. /**
  36571. * Automatically called when playback finished.
  36572. */
  36573. onEnded() {
  36574. this.isPlaying = false;
  36575. this._progress = 0;
  36576. }
  36577. /**
  36578. * Returns the loop flag.
  36579. *
  36580. * Can only be used with compatible audio sources that allow playback control.
  36581. *
  36582. * @return {boolean} Whether the audio should loop or not.
  36583. */
  36584. getLoop() {
  36585. if ( this.hasPlaybackControl === false ) {
  36586. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36587. return false;
  36588. }
  36589. return this.loop;
  36590. }
  36591. /**
  36592. * Sets the loop flag.
  36593. *
  36594. * Can only be used with compatible audio sources that allow playback control.
  36595. *
  36596. * @param {boolean} value - Whether the audio should loop or not.
  36597. * @return {Audio|undefined} A reference to this instance.
  36598. */
  36599. setLoop( value ) {
  36600. if ( this.hasPlaybackControl === false ) {
  36601. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36602. return;
  36603. }
  36604. this.loop = value;
  36605. if ( this.isPlaying === true ) {
  36606. this.source.loop = this.loop;
  36607. }
  36608. return this;
  36609. }
  36610. /**
  36611. * Sets the loop start value which defines where in the audio buffer the replay should
  36612. * start, in seconds.
  36613. *
  36614. * @param {number} value - The loop start value.
  36615. * @return {Audio} A reference to this instance.
  36616. */
  36617. setLoopStart( value ) {
  36618. this.loopStart = value;
  36619. return this;
  36620. }
  36621. /**
  36622. * Sets the loop end value which defines where in the audio buffer the replay should
  36623. * stop, in seconds.
  36624. *
  36625. * @param {number} value - The loop end value.
  36626. * @return {Audio} A reference to this instance.
  36627. */
  36628. setLoopEnd( value ) {
  36629. this.loopEnd = value;
  36630. return this;
  36631. }
  36632. /**
  36633. * Returns the volume.
  36634. *
  36635. * @return {number} The volume.
  36636. */
  36637. getVolume() {
  36638. return this.gain.gain.value;
  36639. }
  36640. /**
  36641. * Sets the volume.
  36642. *
  36643. * @param {number} value - The volume to set.
  36644. * @return {Audio} A reference to this instance.
  36645. */
  36646. setVolume( value ) {
  36647. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36648. return this;
  36649. }
  36650. copy( source, recursive ) {
  36651. super.copy( source, recursive );
  36652. if ( source.sourceType !== 'buffer' ) {
  36653. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36654. return this;
  36655. }
  36656. this.autoplay = source.autoplay;
  36657. this.buffer = source.buffer;
  36658. this.detune = source.detune;
  36659. this.loop = source.loop;
  36660. this.loopStart = source.loopStart;
  36661. this.loopEnd = source.loopEnd;
  36662. this.offset = source.offset;
  36663. this.duration = source.duration;
  36664. this.playbackRate = source.playbackRate;
  36665. this.hasPlaybackControl = source.hasPlaybackControl;
  36666. this.sourceType = source.sourceType;
  36667. this.filters = source.filters.slice();
  36668. return this;
  36669. }
  36670. clone( recursive ) {
  36671. return new this.constructor( this.listener ).copy( this, recursive );
  36672. }
  36673. }
  36674. const _position = /*@__PURE__*/ new Vector3();
  36675. const _quaternion = /*@__PURE__*/ new Quaternion();
  36676. const _scale = /*@__PURE__*/ new Vector3();
  36677. const _orientation = /*@__PURE__*/ new Vector3();
  36678. /**
  36679. * Represents a positional audio object.
  36680. *
  36681. * ```js
  36682. * // create an AudioListener and add it to the camera
  36683. * const listener = new THREE.AudioListener();
  36684. * camera.add( listener );
  36685. *
  36686. * // create the PositionalAudio object (passing in the listener)
  36687. * const sound = new THREE.PositionalAudio( listener );
  36688. *
  36689. * // load a sound and set it as the PositionalAudio object's buffer
  36690. * const audioLoader = new THREE.AudioLoader();
  36691. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36692. * sound.setBuffer( buffer );
  36693. * sound.setRefDistance( 20 );
  36694. * sound.play();
  36695. * });
  36696. *
  36697. * // create an object for the sound to play from
  36698. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36699. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36700. * const mesh = new THREE.Mesh( sphere, material );
  36701. * scene.add( mesh );
  36702. *
  36703. * // finally add the sound to the mesh
  36704. * mesh.add( sound );
  36705. *
  36706. * @augments Audio
  36707. */
  36708. class PositionalAudio extends Audio {
  36709. /**
  36710. * Constructs a positional audio.
  36711. *
  36712. * @param {AudioListener} listener - The global audio listener.
  36713. */
  36714. constructor( listener ) {
  36715. super( listener );
  36716. /**
  36717. * The panner node represents the location, direction, and behavior of an audio
  36718. * source in 3D space.
  36719. *
  36720. * @type {PannerNode}
  36721. * @readonly
  36722. */
  36723. this.panner = this.context.createPanner();
  36724. this.panner.panningModel = 'HRTF';
  36725. this.panner.connect( this.gain );
  36726. }
  36727. connect() {
  36728. super.connect();
  36729. this.panner.connect( this.gain );
  36730. return this;
  36731. }
  36732. disconnect() {
  36733. super.disconnect();
  36734. this.panner.disconnect( this.gain );
  36735. return this;
  36736. }
  36737. getOutput() {
  36738. return this.panner;
  36739. }
  36740. /**
  36741. * Returns the current reference distance.
  36742. *
  36743. * @return {number} The reference distance.
  36744. */
  36745. getRefDistance() {
  36746. return this.panner.refDistance;
  36747. }
  36748. /**
  36749. * Defines the reference distance for reducing volume as the audio source moves
  36750. * further from the listener – i.e. the distance at which the volume reduction
  36751. * starts taking effect.
  36752. *
  36753. * @param {number} value - The reference distance to set.
  36754. * @return {PositionalAudio} A reference to this instance.
  36755. */
  36756. setRefDistance( value ) {
  36757. this.panner.refDistance = value;
  36758. return this;
  36759. }
  36760. /**
  36761. * Returns the current rolloff factor.
  36762. *
  36763. * @return {number} The rolloff factor.
  36764. */
  36765. getRolloffFactor() {
  36766. return this.panner.rolloffFactor;
  36767. }
  36768. /**
  36769. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36770. *
  36771. * @param {number} value - The rolloff factor.
  36772. * @return {PositionalAudio} A reference to this instance.
  36773. */
  36774. setRolloffFactor( value ) {
  36775. this.panner.rolloffFactor = value;
  36776. return this;
  36777. }
  36778. /**
  36779. * Returns the current distance model.
  36780. *
  36781. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36782. */
  36783. getDistanceModel() {
  36784. return this.panner.distanceModel;
  36785. }
  36786. /**
  36787. * Defines which algorithm to use to reduce the volume of the audio source
  36788. * as it moves away from the listener.
  36789. *
  36790. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36791. * for more details.
  36792. *
  36793. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36794. * @return {PositionalAudio} A reference to this instance.
  36795. */
  36796. setDistanceModel( value ) {
  36797. this.panner.distanceModel = value;
  36798. return this;
  36799. }
  36800. /**
  36801. * Returns the current max distance.
  36802. *
  36803. * @return {number} The max distance.
  36804. */
  36805. getMaxDistance() {
  36806. return this.panner.maxDistance;
  36807. }
  36808. /**
  36809. * Defines the maximum distance between the audio source and the listener,
  36810. * after which the volume is not reduced any further.
  36811. *
  36812. * This value is used only by the `linear` distance model.
  36813. *
  36814. * @param {number} value - The max distance.
  36815. * @return {PositionalAudio} A reference to this instance.
  36816. */
  36817. setMaxDistance( value ) {
  36818. this.panner.maxDistance = value;
  36819. return this;
  36820. }
  36821. /**
  36822. * Sets the directional cone in which the audio can be listened.
  36823. *
  36824. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36825. * @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.
  36826. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36827. * @return {PositionalAudio} A reference to this instance.
  36828. */
  36829. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36830. this.panner.coneInnerAngle = coneInnerAngle;
  36831. this.panner.coneOuterAngle = coneOuterAngle;
  36832. this.panner.coneOuterGain = coneOuterGain;
  36833. return this;
  36834. }
  36835. updateMatrixWorld( force ) {
  36836. super.updateMatrixWorld( force );
  36837. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36838. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36839. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36840. const panner = this.panner;
  36841. if ( panner.positionX ) {
  36842. // code path for Chrome and Firefox (see #14393)
  36843. const endTime = this.context.currentTime + this.listener.timeDelta;
  36844. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36845. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36846. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36847. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36848. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36849. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36850. } else {
  36851. panner.setPosition( _position.x, _position.y, _position.z );
  36852. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36853. }
  36854. }
  36855. }
  36856. /**
  36857. * This class can be used to analyse audio data.
  36858. *
  36859. * ```js
  36860. * // create an AudioListener and add it to the camera
  36861. * const listener = new THREE.AudioListener();
  36862. * camera.add( listener );
  36863. *
  36864. * // create an Audio source
  36865. * const sound = new THREE.Audio( listener );
  36866. *
  36867. * // load a sound and set it as the Audio object's buffer
  36868. * const audioLoader = new THREE.AudioLoader();
  36869. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36870. * sound.setBuffer( buffer );
  36871. * sound.setLoop(true);
  36872. * sound.setVolume(0.5);
  36873. * sound.play();
  36874. * });
  36875. *
  36876. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36877. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36878. *
  36879. * // get the average frequency of the sound
  36880. * const data = analyser.getAverageFrequency();
  36881. * ```
  36882. */
  36883. class AudioAnalyser {
  36884. /**
  36885. * Constructs a new audio analyzer.
  36886. *
  36887. * @param {Audio} audio - The audio to analyze.
  36888. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36889. */
  36890. constructor( audio, fftSize = 2048 ) {
  36891. /**
  36892. * The global audio listener.
  36893. *
  36894. * @type {AnalyserNode}
  36895. */
  36896. this.analyser = audio.context.createAnalyser();
  36897. this.analyser.fftSize = fftSize;
  36898. /**
  36899. * Holds the analyzed data.
  36900. *
  36901. * @type {Uint8Array}
  36902. */
  36903. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36904. audio.getOutput().connect( this.analyser );
  36905. }
  36906. /**
  36907. * Returns an array with frequency data of the audio.
  36908. *
  36909. * Each item in the array represents the decibel value for a specific frequency.
  36910. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36911. * For example, for 48000 sample rate, the last item of the array will represent
  36912. * the decibel value for 24000 Hz.
  36913. *
  36914. * @return {Uint8Array} The frequency data.
  36915. */
  36916. getFrequencyData() {
  36917. this.analyser.getByteFrequencyData( this.data );
  36918. return this.data;
  36919. }
  36920. /**
  36921. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36922. *
  36923. * @return {number} The average frequency.
  36924. */
  36925. getAverageFrequency() {
  36926. let value = 0;
  36927. const data = this.getFrequencyData();
  36928. for ( let i = 0; i < data.length; i ++ ) {
  36929. value += data[ i ];
  36930. }
  36931. return value / data.length;
  36932. }
  36933. }
  36934. /**
  36935. * Buffered scene graph property that allows weighted accumulation; used internally.
  36936. */
  36937. class PropertyMixer {
  36938. /**
  36939. * Constructs a new property mixer.
  36940. *
  36941. * @param {PropertyBinding} binding - The property binding.
  36942. * @param {string} typeName - The keyframe track type name.
  36943. * @param {number} valueSize - The keyframe track value size.
  36944. */
  36945. constructor( binding, typeName, valueSize ) {
  36946. /**
  36947. * The property binding.
  36948. *
  36949. * @type {PropertyBinding}
  36950. */
  36951. this.binding = binding;
  36952. /**
  36953. * The keyframe track value size.
  36954. *
  36955. * @type {number}
  36956. */
  36957. this.valueSize = valueSize;
  36958. let mixFunction,
  36959. mixFunctionAdditive,
  36960. setIdentity;
  36961. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36962. //
  36963. // interpolators can use .buffer as their .result
  36964. // the data then goes to 'incoming'
  36965. //
  36966. // 'accu0' and 'accu1' are used frame-interleaved for
  36967. // the cumulative result and are compared to detect
  36968. // changes
  36969. //
  36970. // 'orig' stores the original state of the property
  36971. //
  36972. // 'add' is used for additive cumulative results
  36973. //
  36974. // 'work' is optional and is only present for quaternion types. It is used
  36975. // to store intermediate quaternion multiplication results
  36976. switch ( typeName ) {
  36977. case 'quaternion':
  36978. mixFunction = this._slerp;
  36979. mixFunctionAdditive = this._slerpAdditive;
  36980. setIdentity = this._setAdditiveIdentityQuaternion;
  36981. this.buffer = new Float64Array( valueSize * 6 );
  36982. this._workIndex = 5;
  36983. break;
  36984. case 'string':
  36985. case 'bool':
  36986. mixFunction = this._select;
  36987. // Use the regular mix function and for additive on these types,
  36988. // additive is not relevant for non-numeric types
  36989. mixFunctionAdditive = this._select;
  36990. setIdentity = this._setAdditiveIdentityOther;
  36991. this.buffer = new Array( valueSize * 5 );
  36992. break;
  36993. default:
  36994. mixFunction = this._lerp;
  36995. mixFunctionAdditive = this._lerpAdditive;
  36996. setIdentity = this._setAdditiveIdentityNumeric;
  36997. this.buffer = new Float64Array( valueSize * 5 );
  36998. }
  36999. this._mixBufferRegion = mixFunction;
  37000. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37001. this._setIdentity = setIdentity;
  37002. this._origIndex = 3;
  37003. this._addIndex = 4;
  37004. /**
  37005. * TODO
  37006. *
  37007. * @type {number}
  37008. * @default 0
  37009. */
  37010. this.cumulativeWeight = 0;
  37011. /**
  37012. * TODO
  37013. *
  37014. * @type {number}
  37015. * @default 0
  37016. */
  37017. this.cumulativeWeightAdditive = 0;
  37018. /**
  37019. * TODO
  37020. *
  37021. * @type {number}
  37022. * @default 0
  37023. */
  37024. this.useCount = 0;
  37025. /**
  37026. * TODO
  37027. *
  37028. * @type {number}
  37029. * @default 0
  37030. */
  37031. this.referenceCount = 0;
  37032. }
  37033. /**
  37034. * Accumulates data in the `incoming` region into `accu<i>`.
  37035. *
  37036. * @param {number} accuIndex - The accumulation index.
  37037. * @param {number} weight - The weight.
  37038. */
  37039. accumulate( accuIndex, weight ) {
  37040. // note: happily accumulating nothing when weight = 0, the caller knows
  37041. // the weight and shouldn't have made the call in the first place
  37042. const buffer = this.buffer,
  37043. stride = this.valueSize,
  37044. offset = accuIndex * stride + stride;
  37045. let currentWeight = this.cumulativeWeight;
  37046. if ( currentWeight === 0 ) {
  37047. // accuN := incoming * weight
  37048. for ( let i = 0; i !== stride; ++ i ) {
  37049. buffer[ offset + i ] = buffer[ i ];
  37050. }
  37051. currentWeight = weight;
  37052. } else {
  37053. // accuN := accuN + incoming * weight
  37054. currentWeight += weight;
  37055. const mix = weight / currentWeight;
  37056. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37057. }
  37058. this.cumulativeWeight = currentWeight;
  37059. }
  37060. /**
  37061. * Accumulates data in the `incoming` region into `add`.
  37062. *
  37063. * @param {number} weight - The weight.
  37064. */
  37065. accumulateAdditive( weight ) {
  37066. const buffer = this.buffer,
  37067. stride = this.valueSize,
  37068. offset = stride * this._addIndex;
  37069. if ( this.cumulativeWeightAdditive === 0 ) {
  37070. // add = identity
  37071. this._setIdentity();
  37072. }
  37073. // add := add + incoming * weight
  37074. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37075. this.cumulativeWeightAdditive += weight;
  37076. }
  37077. /**
  37078. * Applies the state of `accu<i>` to the binding when accus differ.
  37079. *
  37080. * @param {number} accuIndex - The accumulation index.
  37081. */
  37082. apply( accuIndex ) {
  37083. const stride = this.valueSize,
  37084. buffer = this.buffer,
  37085. offset = accuIndex * stride + stride,
  37086. weight = this.cumulativeWeight,
  37087. weightAdditive = this.cumulativeWeightAdditive,
  37088. binding = this.binding;
  37089. this.cumulativeWeight = 0;
  37090. this.cumulativeWeightAdditive = 0;
  37091. if ( weight < 1 ) {
  37092. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37093. const originalValueOffset = stride * this._origIndex;
  37094. this._mixBufferRegion(
  37095. buffer, offset, originalValueOffset, 1 - weight, stride );
  37096. }
  37097. if ( weightAdditive > 0 ) {
  37098. // accuN := accuN + additive accuN
  37099. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37100. }
  37101. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37102. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37103. // value has changed -> update scene graph
  37104. binding.setValue( buffer, offset );
  37105. break;
  37106. }
  37107. }
  37108. }
  37109. /**
  37110. * Remembers the state of the bound property and copy it to both accus.
  37111. */
  37112. saveOriginalState() {
  37113. const binding = this.binding;
  37114. const buffer = this.buffer,
  37115. stride = this.valueSize,
  37116. originalValueOffset = stride * this._origIndex;
  37117. binding.getValue( buffer, originalValueOffset );
  37118. // accu[0..1] := orig -- initially detect changes against the original
  37119. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37120. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37121. }
  37122. // Add to identity for additive
  37123. this._setIdentity();
  37124. this.cumulativeWeight = 0;
  37125. this.cumulativeWeightAdditive = 0;
  37126. }
  37127. /**
  37128. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37129. */
  37130. restoreOriginalState() {
  37131. const originalValueOffset = this.valueSize * 3;
  37132. this.binding.setValue( this.buffer, originalValueOffset );
  37133. }
  37134. // internals
  37135. _setAdditiveIdentityNumeric() {
  37136. const startIndex = this._addIndex * this.valueSize;
  37137. const endIndex = startIndex + this.valueSize;
  37138. for ( let i = startIndex; i < endIndex; i ++ ) {
  37139. this.buffer[ i ] = 0;
  37140. }
  37141. }
  37142. _setAdditiveIdentityQuaternion() {
  37143. this._setAdditiveIdentityNumeric();
  37144. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37145. }
  37146. _setAdditiveIdentityOther() {
  37147. const startIndex = this._origIndex * this.valueSize;
  37148. const targetIndex = this._addIndex * this.valueSize;
  37149. for ( let i = 0; i < this.valueSize; i ++ ) {
  37150. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37151. }
  37152. }
  37153. // mix functions
  37154. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37155. if ( t >= 0.5 ) {
  37156. for ( let i = 0; i !== stride; ++ i ) {
  37157. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37158. }
  37159. }
  37160. }
  37161. _slerp( buffer, dstOffset, srcOffset, t ) {
  37162. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37163. }
  37164. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37165. const workOffset = this._workIndex * stride;
  37166. // Store result in intermediate buffer offset
  37167. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37168. // Slerp to the intermediate result
  37169. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37170. }
  37171. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37172. const s = 1 - t;
  37173. for ( let i = 0; i !== stride; ++ i ) {
  37174. const j = dstOffset + i;
  37175. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37176. }
  37177. }
  37178. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37179. for ( let i = 0; i !== stride; ++ i ) {
  37180. const j = dstOffset + i;
  37181. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37182. }
  37183. }
  37184. }
  37185. // Characters [].:/ are reserved for track binding syntax.
  37186. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37187. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37188. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37189. // only latin characters, and the unicode \p{L} is not yet supported. So
  37190. // instead, we exclude reserved characters and match everything else.
  37191. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37192. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37193. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37194. // be matched to parse the rest of the track name.
  37195. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37196. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37197. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37198. // Object on target node, and accessor. May not contain reserved
  37199. // characters. Accessor may contain any character except closing bracket.
  37200. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37201. // Property and accessor. May not contain reserved characters. Accessor may
  37202. // contain any non-bracket characters.
  37203. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37204. const _trackRe = new RegExp( ''
  37205. + '^'
  37206. + _directoryRe
  37207. + _nodeRe
  37208. + _objectRe
  37209. + _propertyRe
  37210. + '$'
  37211. );
  37212. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37213. class Composite {
  37214. constructor( targetGroup, path, optionalParsedPath ) {
  37215. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37216. this._targetGroup = targetGroup;
  37217. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37218. }
  37219. getValue( array, offset ) {
  37220. this.bind(); // bind all binding
  37221. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37222. binding = this._bindings[ firstValidIndex ];
  37223. // and only call .getValue on the first
  37224. if ( binding !== undefined ) binding.getValue( array, offset );
  37225. }
  37226. setValue( array, offset ) {
  37227. const bindings = this._bindings;
  37228. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37229. bindings[ i ].setValue( array, offset );
  37230. }
  37231. }
  37232. bind() {
  37233. const bindings = this._bindings;
  37234. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37235. bindings[ i ].bind();
  37236. }
  37237. }
  37238. unbind() {
  37239. const bindings = this._bindings;
  37240. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37241. bindings[ i ].unbind();
  37242. }
  37243. }
  37244. }
  37245. // Note: This class uses a State pattern on a per-method basis:
  37246. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37247. // prototype version of these methods with one that represents
  37248. // the bound state. When the property is not found, the methods
  37249. // become no-ops.
  37250. /**
  37251. * This holds a reference to a real property in the scene graph; used internally.
  37252. */
  37253. class PropertyBinding {
  37254. /**
  37255. * Constructs a new property binding.
  37256. *
  37257. * @param {Object} rootNode - The root node.
  37258. * @param {string} path - The path.
  37259. * @param {?Object} [parsedPath] - The parsed path.
  37260. */
  37261. constructor( rootNode, path, parsedPath ) {
  37262. /**
  37263. * The object path to the animated property.
  37264. *
  37265. * @type {string}
  37266. */
  37267. this.path = path;
  37268. /**
  37269. * An object holding information about the path.
  37270. *
  37271. * @type {Object}
  37272. */
  37273. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37274. /**
  37275. * The object owns the animated property.
  37276. *
  37277. * @type {?Object}
  37278. */
  37279. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37280. /**
  37281. * The root node.
  37282. *
  37283. * @type {Object3D|Skeleton}
  37284. */
  37285. this.rootNode = rootNode;
  37286. // initial state of these methods that calls 'bind'
  37287. this.getValue = this._getValue_unbound;
  37288. this.setValue = this._setValue_unbound;
  37289. }
  37290. /**
  37291. * Factory method for creating a property binding from the given parameters.
  37292. *
  37293. * @static
  37294. * @param {Object} root - The root node.
  37295. * @param {string} path - The path.
  37296. * @param {?Object} [parsedPath] - The parsed path.
  37297. * @return {PropertyBinding|Composite} The created property binding or composite.
  37298. */
  37299. static create( root, path, parsedPath ) {
  37300. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37301. return new PropertyBinding( root, path, parsedPath );
  37302. } else {
  37303. return new PropertyBinding.Composite( root, path, parsedPath );
  37304. }
  37305. }
  37306. /**
  37307. * Replaces spaces with underscores and removes unsupported characters from
  37308. * node names, to ensure compatibility with parseTrackName().
  37309. *
  37310. * @param {string} name - Node name to be sanitized.
  37311. * @return {string} The sanitized node name.
  37312. */
  37313. static sanitizeNodeName( name ) {
  37314. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37315. }
  37316. /**
  37317. * Parses the given track name (an object path to an animated property) and
  37318. * returns an object with information about the path. Matches strings in the following forms:
  37319. *
  37320. * - nodeName.property
  37321. * - nodeName.property[accessor]
  37322. * - nodeName.material.property[accessor]
  37323. * - uuid.property[accessor]
  37324. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37325. * - parentName/nodeName.property
  37326. * - parentName/parentName/nodeName.property[index]
  37327. * - .bone[Armature.DEF_cog].position
  37328. * - scene:helium_balloon_model:helium_balloon_model.position
  37329. *
  37330. * @static
  37331. * @param {string} trackName - The track name to parse.
  37332. * @return {Object} The parsed track name as an object.
  37333. */
  37334. static parseTrackName( trackName ) {
  37335. const matches = _trackRe.exec( trackName );
  37336. if ( matches === null ) {
  37337. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37338. }
  37339. const results = {
  37340. // directoryName: matches[ 1 ], // (tschw) currently unused
  37341. nodeName: matches[ 2 ],
  37342. objectName: matches[ 3 ],
  37343. objectIndex: matches[ 4 ],
  37344. propertyName: matches[ 5 ], // required
  37345. propertyIndex: matches[ 6 ]
  37346. };
  37347. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37348. if ( lastDot !== undefined && lastDot !== -1 ) {
  37349. const objectName = results.nodeName.substring( lastDot + 1 );
  37350. // Object names must be checked against an allowlist. Otherwise, there
  37351. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37352. // 'bar' could be the objectName, or part of a nodeName (which can
  37353. // include '.' characters).
  37354. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37355. results.nodeName = results.nodeName.substring( 0, lastDot );
  37356. results.objectName = objectName;
  37357. }
  37358. }
  37359. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37360. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37361. }
  37362. return results;
  37363. }
  37364. /**
  37365. * Searches for a node in the hierarchy of the given root object by the given
  37366. * node name.
  37367. *
  37368. * @static
  37369. * @param {Object} root - The root object.
  37370. * @param {string|number} nodeName - The name of the node.
  37371. * @return {?Object} The found node. Returns `null` if no object was found.
  37372. */
  37373. static findNode( root, nodeName ) {
  37374. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37375. return root;
  37376. }
  37377. // search into skeleton bones.
  37378. if ( root.skeleton ) {
  37379. const bone = root.skeleton.getBoneByName( nodeName );
  37380. if ( bone !== undefined ) {
  37381. return bone;
  37382. }
  37383. }
  37384. // search into node subtree.
  37385. if ( root.children ) {
  37386. const searchNodeSubtree = function ( children ) {
  37387. for ( let i = 0; i < children.length; i ++ ) {
  37388. const childNode = children[ i ];
  37389. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37390. return childNode;
  37391. }
  37392. const result = searchNodeSubtree( childNode.children );
  37393. if ( result ) return result;
  37394. }
  37395. return null;
  37396. };
  37397. const subTreeNode = searchNodeSubtree( root.children );
  37398. if ( subTreeNode ) {
  37399. return subTreeNode;
  37400. }
  37401. }
  37402. return null;
  37403. }
  37404. // these are used to "bind" a nonexistent property
  37405. _getValue_unavailable() {}
  37406. _setValue_unavailable() {}
  37407. // Getters
  37408. _getValue_direct( buffer, offset ) {
  37409. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37410. }
  37411. _getValue_array( buffer, offset ) {
  37412. const source = this.resolvedProperty;
  37413. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37414. buffer[ offset ++ ] = source[ i ];
  37415. }
  37416. }
  37417. _getValue_arrayElement( buffer, offset ) {
  37418. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37419. }
  37420. _getValue_toArray( buffer, offset ) {
  37421. this.resolvedProperty.toArray( buffer, offset );
  37422. }
  37423. // Direct
  37424. _setValue_direct( buffer, offset ) {
  37425. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37426. }
  37427. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37428. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37429. this.targetObject.needsUpdate = true;
  37430. }
  37431. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37432. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37433. this.targetObject.matrixWorldNeedsUpdate = true;
  37434. }
  37435. // EntireArray
  37436. _setValue_array( buffer, offset ) {
  37437. const dest = this.resolvedProperty;
  37438. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37439. dest[ i ] = buffer[ offset ++ ];
  37440. }
  37441. }
  37442. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37443. const dest = this.resolvedProperty;
  37444. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37445. dest[ i ] = buffer[ offset ++ ];
  37446. }
  37447. this.targetObject.needsUpdate = true;
  37448. }
  37449. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37450. const dest = this.resolvedProperty;
  37451. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37452. dest[ i ] = buffer[ offset ++ ];
  37453. }
  37454. this.targetObject.matrixWorldNeedsUpdate = true;
  37455. }
  37456. // ArrayElement
  37457. _setValue_arrayElement( buffer, offset ) {
  37458. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37459. }
  37460. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37461. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37462. this.targetObject.needsUpdate = true;
  37463. }
  37464. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37465. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37466. this.targetObject.matrixWorldNeedsUpdate = true;
  37467. }
  37468. // HasToFromArray
  37469. _setValue_fromArray( buffer, offset ) {
  37470. this.resolvedProperty.fromArray( buffer, offset );
  37471. }
  37472. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37473. this.resolvedProperty.fromArray( buffer, offset );
  37474. this.targetObject.needsUpdate = true;
  37475. }
  37476. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37477. this.resolvedProperty.fromArray( buffer, offset );
  37478. this.targetObject.matrixWorldNeedsUpdate = true;
  37479. }
  37480. _getValue_unbound( targetArray, offset ) {
  37481. this.bind();
  37482. this.getValue( targetArray, offset );
  37483. }
  37484. _setValue_unbound( sourceArray, offset ) {
  37485. this.bind();
  37486. this.setValue( sourceArray, offset );
  37487. }
  37488. /**
  37489. * Creates a getter / setter pair for the property tracked by this binding.
  37490. */
  37491. bind() {
  37492. let targetObject = this.node;
  37493. const parsedPath = this.parsedPath;
  37494. const objectName = parsedPath.objectName;
  37495. const propertyName = parsedPath.propertyName;
  37496. let propertyIndex = parsedPath.propertyIndex;
  37497. if ( ! targetObject ) {
  37498. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37499. this.node = targetObject;
  37500. }
  37501. // set fail state so we can just 'return' on error
  37502. this.getValue = this._getValue_unavailable;
  37503. this.setValue = this._setValue_unavailable;
  37504. // ensure there is a value node
  37505. if ( ! targetObject ) {
  37506. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37507. return;
  37508. }
  37509. if ( objectName ) {
  37510. let objectIndex = parsedPath.objectIndex;
  37511. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37512. switch ( objectName ) {
  37513. case 'materials':
  37514. if ( ! targetObject.material ) {
  37515. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37516. return;
  37517. }
  37518. if ( ! targetObject.material.materials ) {
  37519. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37520. return;
  37521. }
  37522. targetObject = targetObject.material.materials;
  37523. break;
  37524. case 'bones':
  37525. if ( ! targetObject.skeleton ) {
  37526. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37527. return;
  37528. }
  37529. // potential future optimization: skip this if propertyIndex is already an integer
  37530. // and convert the integer string to a true integer.
  37531. targetObject = targetObject.skeleton.bones;
  37532. // support resolving morphTarget names into indices.
  37533. for ( let i = 0; i < targetObject.length; i ++ ) {
  37534. if ( targetObject[ i ].name === objectIndex ) {
  37535. objectIndex = i;
  37536. break;
  37537. }
  37538. }
  37539. break;
  37540. case 'map':
  37541. if ( 'map' in targetObject ) {
  37542. targetObject = targetObject.map;
  37543. break;
  37544. }
  37545. if ( ! targetObject.material ) {
  37546. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37547. return;
  37548. }
  37549. if ( ! targetObject.material.map ) {
  37550. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37551. return;
  37552. }
  37553. targetObject = targetObject.material.map;
  37554. break;
  37555. default:
  37556. if ( targetObject[ objectName ] === undefined ) {
  37557. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37558. return;
  37559. }
  37560. targetObject = targetObject[ objectName ];
  37561. }
  37562. if ( objectIndex !== undefined ) {
  37563. if ( targetObject[ objectIndex ] === undefined ) {
  37564. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37565. return;
  37566. }
  37567. targetObject = targetObject[ objectIndex ];
  37568. }
  37569. }
  37570. // resolve property
  37571. const nodeProperty = targetObject[ propertyName ];
  37572. if ( nodeProperty === undefined ) {
  37573. const nodeName = parsedPath.nodeName;
  37574. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37575. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37576. return;
  37577. }
  37578. // determine versioning scheme
  37579. let versioning = this.Versioning.None;
  37580. this.targetObject = targetObject;
  37581. if ( targetObject.isMaterial === true ) {
  37582. versioning = this.Versioning.NeedsUpdate;
  37583. } else if ( targetObject.isObject3D === true ) {
  37584. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37585. }
  37586. // determine how the property gets bound
  37587. let bindingType = this.BindingType.Direct;
  37588. if ( propertyIndex !== undefined ) {
  37589. // access a sub element of the property array (only primitives are supported right now)
  37590. if ( propertyName === 'morphTargetInfluences' ) {
  37591. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37592. // support resolving morphTarget names into indices.
  37593. if ( ! targetObject.geometry ) {
  37594. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37595. return;
  37596. }
  37597. if ( ! targetObject.geometry.morphAttributes ) {
  37598. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37599. return;
  37600. }
  37601. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37602. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37603. }
  37604. }
  37605. bindingType = this.BindingType.ArrayElement;
  37606. this.resolvedProperty = nodeProperty;
  37607. this.propertyIndex = propertyIndex;
  37608. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37609. // must use copy for Object3D.Euler/Quaternion
  37610. bindingType = this.BindingType.HasFromToArray;
  37611. this.resolvedProperty = nodeProperty;
  37612. } else if ( Array.isArray( nodeProperty ) ) {
  37613. bindingType = this.BindingType.EntireArray;
  37614. this.resolvedProperty = nodeProperty;
  37615. } else {
  37616. this.propertyName = propertyName;
  37617. }
  37618. // select getter / setter
  37619. this.getValue = this.GetterByBindingType[ bindingType ];
  37620. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37621. }
  37622. /**
  37623. * Unbinds the property.
  37624. */
  37625. unbind() {
  37626. this.node = null;
  37627. // back to the prototype version of getValue / setValue
  37628. // note: avoiding to mutate the shape of 'this' via 'delete'
  37629. this.getValue = this._getValue_unbound;
  37630. this.setValue = this._setValue_unbound;
  37631. }
  37632. }
  37633. PropertyBinding.Composite = Composite;
  37634. PropertyBinding.prototype.BindingType = {
  37635. Direct: 0,
  37636. EntireArray: 1,
  37637. ArrayElement: 2,
  37638. HasFromToArray: 3
  37639. };
  37640. PropertyBinding.prototype.Versioning = {
  37641. None: 0,
  37642. NeedsUpdate: 1,
  37643. MatrixWorldNeedsUpdate: 2
  37644. };
  37645. PropertyBinding.prototype.GetterByBindingType = [
  37646. PropertyBinding.prototype._getValue_direct,
  37647. PropertyBinding.prototype._getValue_array,
  37648. PropertyBinding.prototype._getValue_arrayElement,
  37649. PropertyBinding.prototype._getValue_toArray,
  37650. ];
  37651. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37652. [
  37653. // Direct
  37654. PropertyBinding.prototype._setValue_direct,
  37655. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37656. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37657. ], [
  37658. // EntireArray
  37659. PropertyBinding.prototype._setValue_array,
  37660. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37661. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37662. ], [
  37663. // ArrayElement
  37664. PropertyBinding.prototype._setValue_arrayElement,
  37665. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37666. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37667. ], [
  37668. // HasToFromArray
  37669. PropertyBinding.prototype._setValue_fromArray,
  37670. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37671. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37672. ]
  37673. ];
  37674. /**
  37675. * A group of objects that receives a shared animation state.
  37676. *
  37677. * Usage:
  37678. *
  37679. * - Add objects you would otherwise pass as 'root' to the
  37680. * constructor or the .clipAction method of AnimationMixer.
  37681. * - Instead pass this object as 'root'.
  37682. * - You can also add and remove objects later when the mixer is running.
  37683. *
  37684. * Note:
  37685. *
  37686. * - Objects of this class appear as one object to the mixer,
  37687. * so cache control of the individual objects must be done on the group.
  37688. *
  37689. * Limitation:
  37690. *
  37691. * - The animated properties must be compatible among the all objects in the group.
  37692. * - A single property can either be controlled through a target group or directly, but not both.
  37693. */
  37694. class AnimationObjectGroup {
  37695. /**
  37696. * Constructs a new animation group.
  37697. *
  37698. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37699. */
  37700. constructor() {
  37701. /**
  37702. * This flag can be used for type testing.
  37703. *
  37704. * @type {boolean}
  37705. * @readonly
  37706. * @default true
  37707. */
  37708. this.isAnimationObjectGroup = true;
  37709. /**
  37710. * The UUID of the 3D object.
  37711. *
  37712. * @type {string}
  37713. * @readonly
  37714. */
  37715. this.uuid = generateUUID();
  37716. // cached objects followed by the active ones
  37717. this._objects = Array.prototype.slice.call( arguments );
  37718. this.nCachedObjects_ = 0; // threshold
  37719. // note: read by PropertyBinding.Composite
  37720. const indices = {};
  37721. this._indicesByUUID = indices; // for bookkeeping
  37722. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37723. indices[ arguments[ i ].uuid ] = i;
  37724. }
  37725. this._paths = []; // inside: string
  37726. this._parsedPaths = []; // inside: { we don't care, here }
  37727. this._bindings = []; // inside: Array< PropertyBinding >
  37728. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37729. const scope = this;
  37730. this.stats = {
  37731. objects: {
  37732. get total() {
  37733. return scope._objects.length;
  37734. },
  37735. get inUse() {
  37736. return this.total - scope.nCachedObjects_;
  37737. }
  37738. },
  37739. get bindingsPerObject() {
  37740. return scope._bindings.length;
  37741. }
  37742. };
  37743. }
  37744. /**
  37745. * Adds an arbitrary number of objects to this animation group.
  37746. *
  37747. * @param {...Object3D} arguments - The 3D objects to add.
  37748. */
  37749. add() {
  37750. const objects = this._objects,
  37751. indicesByUUID = this._indicesByUUID,
  37752. paths = this._paths,
  37753. parsedPaths = this._parsedPaths,
  37754. bindings = this._bindings,
  37755. nBindings = bindings.length;
  37756. let knownObject = undefined,
  37757. nObjects = objects.length,
  37758. nCachedObjects = this.nCachedObjects_;
  37759. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37760. const object = arguments[ i ],
  37761. uuid = object.uuid;
  37762. let index = indicesByUUID[ uuid ];
  37763. if ( index === undefined ) {
  37764. // unknown object -> add it to the ACTIVE region
  37765. index = nObjects ++;
  37766. indicesByUUID[ uuid ] = index;
  37767. objects.push( object );
  37768. // accounting is done, now do the same for all bindings
  37769. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37770. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37771. }
  37772. } else if ( index < nCachedObjects ) {
  37773. knownObject = objects[ index ];
  37774. // move existing object to the ACTIVE region
  37775. const firstActiveIndex = -- nCachedObjects,
  37776. lastCachedObject = objects[ firstActiveIndex ];
  37777. indicesByUUID[ lastCachedObject.uuid ] = index;
  37778. objects[ index ] = lastCachedObject;
  37779. indicesByUUID[ uuid ] = firstActiveIndex;
  37780. objects[ firstActiveIndex ] = object;
  37781. // accounting is done, now do the same for all bindings
  37782. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37783. const bindingsForPath = bindings[ j ],
  37784. lastCached = bindingsForPath[ firstActiveIndex ];
  37785. let binding = bindingsForPath[ index ];
  37786. bindingsForPath[ index ] = lastCached;
  37787. if ( binding === undefined ) {
  37788. // since we do not bother to create new bindings
  37789. // for objects that are cached, the binding may
  37790. // or may not exist
  37791. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37792. }
  37793. bindingsForPath[ firstActiveIndex ] = binding;
  37794. }
  37795. } else if ( objects[ index ] !== knownObject ) {
  37796. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37797. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37798. } // else the object is already where we want it to be
  37799. } // for arguments
  37800. this.nCachedObjects_ = nCachedObjects;
  37801. }
  37802. /**
  37803. * Removes an arbitrary number of objects to this animation group
  37804. *
  37805. * @param {...Object3D} arguments - The 3D objects to remove.
  37806. */
  37807. remove() {
  37808. const objects = this._objects,
  37809. indicesByUUID = this._indicesByUUID,
  37810. bindings = this._bindings,
  37811. nBindings = bindings.length;
  37812. let nCachedObjects = this.nCachedObjects_;
  37813. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37814. const object = arguments[ i ],
  37815. uuid = object.uuid,
  37816. index = indicesByUUID[ uuid ];
  37817. if ( index !== undefined && index >= nCachedObjects ) {
  37818. // move existing object into the CACHED region
  37819. const lastCachedIndex = nCachedObjects ++,
  37820. firstActiveObject = objects[ lastCachedIndex ];
  37821. indicesByUUID[ firstActiveObject.uuid ] = index;
  37822. objects[ index ] = firstActiveObject;
  37823. indicesByUUID[ uuid ] = lastCachedIndex;
  37824. objects[ lastCachedIndex ] = object;
  37825. // accounting is done, now do the same for all bindings
  37826. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37827. const bindingsForPath = bindings[ j ],
  37828. firstActive = bindingsForPath[ lastCachedIndex ],
  37829. binding = bindingsForPath[ index ];
  37830. bindingsForPath[ index ] = firstActive;
  37831. bindingsForPath[ lastCachedIndex ] = binding;
  37832. }
  37833. }
  37834. } // for arguments
  37835. this.nCachedObjects_ = nCachedObjects;
  37836. }
  37837. /**
  37838. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37839. *
  37840. * @param {...Object3D} arguments - The 3D objects to uncache.
  37841. */
  37842. uncache() {
  37843. const objects = this._objects,
  37844. indicesByUUID = this._indicesByUUID,
  37845. bindings = this._bindings,
  37846. nBindings = bindings.length;
  37847. let nCachedObjects = this.nCachedObjects_,
  37848. nObjects = objects.length;
  37849. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37850. const object = arguments[ i ],
  37851. uuid = object.uuid,
  37852. index = indicesByUUID[ uuid ];
  37853. if ( index !== undefined ) {
  37854. delete indicesByUUID[ uuid ];
  37855. if ( index < nCachedObjects ) {
  37856. // object is cached, shrink the CACHED region
  37857. const firstActiveIndex = -- nCachedObjects,
  37858. lastCachedObject = objects[ firstActiveIndex ],
  37859. lastIndex = -- nObjects,
  37860. lastObject = objects[ lastIndex ];
  37861. // last cached object takes this object's place
  37862. indicesByUUID[ lastCachedObject.uuid ] = index;
  37863. objects[ index ] = lastCachedObject;
  37864. // last object goes to the activated slot and pop
  37865. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37866. objects[ firstActiveIndex ] = lastObject;
  37867. objects.pop();
  37868. // accounting is done, now do the same for all bindings
  37869. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37870. const bindingsForPath = bindings[ j ],
  37871. lastCached = bindingsForPath[ firstActiveIndex ],
  37872. last = bindingsForPath[ lastIndex ];
  37873. bindingsForPath[ index ] = lastCached;
  37874. bindingsForPath[ firstActiveIndex ] = last;
  37875. bindingsForPath.pop();
  37876. }
  37877. } else {
  37878. // object is active, just swap with the last and pop
  37879. const lastIndex = -- nObjects,
  37880. lastObject = objects[ lastIndex ];
  37881. if ( lastIndex > 0 ) {
  37882. indicesByUUID[ lastObject.uuid ] = index;
  37883. }
  37884. objects[ index ] = lastObject;
  37885. objects.pop();
  37886. // accounting is done, now do the same for all bindings
  37887. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37888. const bindingsForPath = bindings[ j ];
  37889. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37890. bindingsForPath.pop();
  37891. }
  37892. } // cached or active
  37893. } // if object is known
  37894. } // for arguments
  37895. this.nCachedObjects_ = nCachedObjects;
  37896. }
  37897. // Internal interface used by befriended PropertyBinding.Composite:
  37898. subscribe_( path, parsedPath ) {
  37899. // returns an array of bindings for the given path that is changed
  37900. // according to the contained objects in the group
  37901. const indicesByPath = this._bindingsIndicesByPath;
  37902. let index = indicesByPath[ path ];
  37903. const bindings = this._bindings;
  37904. if ( index !== undefined ) return bindings[ index ];
  37905. const paths = this._paths,
  37906. parsedPaths = this._parsedPaths,
  37907. objects = this._objects,
  37908. nObjects = objects.length,
  37909. nCachedObjects = this.nCachedObjects_,
  37910. bindingsForPath = new Array( nObjects );
  37911. index = bindings.length;
  37912. indicesByPath[ path ] = index;
  37913. paths.push( path );
  37914. parsedPaths.push( parsedPath );
  37915. bindings.push( bindingsForPath );
  37916. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37917. const object = objects[ i ];
  37918. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37919. }
  37920. return bindingsForPath;
  37921. }
  37922. unsubscribe_( path ) {
  37923. // tells the group to forget about a property path and no longer
  37924. // update the array previously obtained with 'subscribe_'
  37925. const indicesByPath = this._bindingsIndicesByPath,
  37926. index = indicesByPath[ path ];
  37927. if ( index !== undefined ) {
  37928. const paths = this._paths,
  37929. parsedPaths = this._parsedPaths,
  37930. bindings = this._bindings,
  37931. lastBindingsIndex = bindings.length - 1,
  37932. lastBindings = bindings[ lastBindingsIndex ],
  37933. lastBindingsPath = path[ lastBindingsIndex ];
  37934. indicesByPath[ lastBindingsPath ] = index;
  37935. bindings[ index ] = lastBindings;
  37936. bindings.pop();
  37937. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37938. parsedPaths.pop();
  37939. paths[ index ] = paths[ lastBindingsIndex ];
  37940. paths.pop();
  37941. }
  37942. }
  37943. }
  37944. /**
  37945. * An instance of `AnimationAction` schedules the playback of an animation which is
  37946. * stored in {@link AnimationClip}.
  37947. */
  37948. class AnimationAction {
  37949. /**
  37950. * Constructs a new animation action.
  37951. *
  37952. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37953. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37954. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37955. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37956. */
  37957. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37958. this._mixer = mixer;
  37959. this._clip = clip;
  37960. this._localRoot = localRoot;
  37961. /**
  37962. * Defines how the animation is blended/combined when two or more animations
  37963. * are simultaneously played.
  37964. *
  37965. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37966. */
  37967. this.blendMode = blendMode;
  37968. const tracks = clip.tracks,
  37969. nTracks = tracks.length,
  37970. interpolants = new Array( nTracks );
  37971. const interpolantSettings = {
  37972. endingStart: ZeroCurvatureEnding,
  37973. endingEnd: ZeroCurvatureEnding
  37974. };
  37975. for ( let i = 0; i !== nTracks; ++ i ) {
  37976. const interpolant = tracks[ i ].createInterpolant( null );
  37977. interpolants[ i ] = interpolant;
  37978. interpolant.settings = interpolantSettings;
  37979. }
  37980. this._interpolantSettings = interpolantSettings;
  37981. this._interpolants = interpolants; // bound by the mixer
  37982. // inside: PropertyMixer (managed by the mixer)
  37983. this._propertyBindings = new Array( nTracks );
  37984. this._cacheIndex = null; // for the memory manager
  37985. this._byClipCacheIndex = null; // for the memory manager
  37986. this._timeScaleInterpolant = null;
  37987. this._weightInterpolant = null;
  37988. /**
  37989. * The loop mode, set via {@link AnimationAction#setLoop}.
  37990. *
  37991. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  37992. * @default LoopRepeat
  37993. */
  37994. this.loop = LoopRepeat;
  37995. this._loopCount = -1;
  37996. // global mixer time when the action is to be started
  37997. // it's set back to 'null' upon start of the action
  37998. this._startTime = null;
  37999. /**
  38000. * The local time of this action (in seconds, starting with `0`).
  38001. *
  38002. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38003. * loop state).
  38004. *
  38005. * @type {number}
  38006. * @default Infinity
  38007. */
  38008. this.time = 0;
  38009. /**
  38010. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38011. * animation to pause. Negative values cause the animation to play backwards.
  38012. *
  38013. * @type {number}
  38014. * @default 1
  38015. */
  38016. this.timeScale = 1;
  38017. this._effectiveTimeScale = 1;
  38018. /**
  38019. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38020. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38021. * several actions.
  38022. *
  38023. * @type {number}
  38024. * @default 1
  38025. */
  38026. this.weight = 1;
  38027. this._effectiveWeight = 1;
  38028. /**
  38029. * The number of repetitions of the performed clip over the course of this action.
  38030. * Can be set via {@link AnimationAction#setLoop}.
  38031. *
  38032. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38033. * `THREE:LoopOnce`.
  38034. *
  38035. * @type {number}
  38036. * @default Infinity
  38037. */
  38038. this.repetitions = Infinity;
  38039. /**
  38040. * If set to `true`, the playback of the action is paused.
  38041. *
  38042. * @type {boolean}
  38043. * @default false
  38044. */
  38045. this.paused = false;
  38046. /**
  38047. * If set to `false`, the action is disabled so it has no impact.
  38048. *
  38049. * When the action is re-enabled, the animation continues from its current
  38050. * time (setting `enabled` to `false` doesn't reset the action).
  38051. *
  38052. * @type {boolean}
  38053. * @default true
  38054. */
  38055. this.enabled = true;
  38056. /**
  38057. * If set to true the animation will automatically be paused on its last frame.
  38058. *
  38059. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38060. * to `false` when the last loop of the action has finished, so that this action has
  38061. * no further impact.
  38062. *
  38063. * Note: This member has no impact if the action is interrupted (it
  38064. * has only an effect if its last loop has really finished).
  38065. *
  38066. * @type {boolean}
  38067. * @default false
  38068. */
  38069. this.clampWhenFinished = false;
  38070. /**
  38071. * Enables smooth interpolation without separate clips for start, loop and end.
  38072. *
  38073. * @type {boolean}
  38074. * @default true
  38075. */
  38076. this.zeroSlopeAtStart = true;
  38077. /**
  38078. * Enables smooth interpolation without separate clips for start, loop and end.
  38079. *
  38080. * @type {boolean}
  38081. * @default true
  38082. */
  38083. this.zeroSlopeAtEnd = true;
  38084. }
  38085. /**
  38086. * Starts the playback of the animation.
  38087. *
  38088. * @return {AnimationAction} A reference to this animation action.
  38089. */
  38090. play() {
  38091. this._mixer._activateAction( this );
  38092. return this;
  38093. }
  38094. /**
  38095. * Stops the playback of the animation.
  38096. *
  38097. * @return {AnimationAction} A reference to this animation action.
  38098. */
  38099. stop() {
  38100. this._mixer._deactivateAction( this );
  38101. return this.reset();
  38102. }
  38103. /**
  38104. * Resets the playback of the animation.
  38105. *
  38106. * @return {AnimationAction} A reference to this animation action.
  38107. */
  38108. reset() {
  38109. this.paused = false;
  38110. this.enabled = true;
  38111. this.time = 0; // restart clip
  38112. this._loopCount = -1;// forget previous loops
  38113. this._startTime = null;// forget scheduling
  38114. return this.stopFading().stopWarping();
  38115. }
  38116. /**
  38117. * Returns `true` if the animation is running.
  38118. *
  38119. * @return {boolean} Whether the animation is running or not.
  38120. */
  38121. isRunning() {
  38122. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38123. this._startTime === null && this._mixer._isActiveAction( this );
  38124. }
  38125. /**
  38126. * Returns `true` when {@link AnimationAction#play} has been called.
  38127. *
  38128. * @return {boolean} Whether the animation is scheduled or not.
  38129. */
  38130. isScheduled() {
  38131. return this._mixer._isActiveAction( this );
  38132. }
  38133. /**
  38134. * Defines the time when the animation should start.
  38135. *
  38136. * @param {number} time - The start time in seconds.
  38137. * @return {AnimationAction} A reference to this animation action.
  38138. */
  38139. startAt( time ) {
  38140. this._startTime = time;
  38141. return this;
  38142. }
  38143. /**
  38144. * Configures the loop settings for this action.
  38145. *
  38146. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38147. * @param {number} repetitions - The number of repetitions.
  38148. * @return {AnimationAction} A reference to this animation action.
  38149. */
  38150. setLoop( mode, repetitions ) {
  38151. this.loop = mode;
  38152. this.repetitions = repetitions;
  38153. return this;
  38154. }
  38155. /**
  38156. * Sets the effective weight of this action.
  38157. *
  38158. * An action has no effect and thus an effective weight of zero when the
  38159. * action is disabled.
  38160. *
  38161. * @param {number} weight - The weight to set.
  38162. * @return {AnimationAction} A reference to this animation action.
  38163. */
  38164. setEffectiveWeight( weight ) {
  38165. this.weight = weight;
  38166. // note: same logic as when updated at runtime
  38167. this._effectiveWeight = this.enabled ? weight : 0;
  38168. return this.stopFading();
  38169. }
  38170. /**
  38171. * Returns the effective weight of this action.
  38172. *
  38173. * @return {number} The effective weight.
  38174. */
  38175. getEffectiveWeight() {
  38176. return this._effectiveWeight;
  38177. }
  38178. /**
  38179. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38180. * within the passed time interval.
  38181. *
  38182. * @param {number} duration - The duration of the fade.
  38183. * @return {AnimationAction} A reference to this animation action.
  38184. */
  38185. fadeIn( duration ) {
  38186. return this._scheduleFading( duration, 0, 1 );
  38187. }
  38188. /**
  38189. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38190. * within the passed time interval.
  38191. *
  38192. * @param {number} duration - The duration of the fade.
  38193. * @return {AnimationAction} A reference to this animation action.
  38194. */
  38195. fadeOut( duration ) {
  38196. return this._scheduleFading( duration, 1, 0 );
  38197. }
  38198. /**
  38199. * Causes this action to fade in and the given action to fade out,
  38200. * within the passed time interval.
  38201. *
  38202. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38203. * @param {number} duration - The duration of the fade.
  38204. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38205. * @return {AnimationAction} A reference to this animation action.
  38206. */
  38207. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38208. fadeOutAction.fadeOut( duration );
  38209. this.fadeIn( duration );
  38210. if ( warp === true ) {
  38211. const fadeInDuration = this._clip.duration,
  38212. fadeOutDuration = fadeOutAction._clip.duration,
  38213. startEndRatio = fadeOutDuration / fadeInDuration,
  38214. endStartRatio = fadeInDuration / fadeOutDuration;
  38215. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38216. this.warp( endStartRatio, 1.0, duration );
  38217. }
  38218. return this;
  38219. }
  38220. /**
  38221. * Causes this action to fade out and the given action to fade in,
  38222. * within the passed time interval.
  38223. *
  38224. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38225. * @param {number} duration - The duration of the fade.
  38226. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38227. * @return {AnimationAction} A reference to this animation action.
  38228. */
  38229. crossFadeTo( fadeInAction, duration, warp = false ) {
  38230. return fadeInAction.crossFadeFrom( this, duration, warp );
  38231. }
  38232. /**
  38233. * Stops any fading which is applied to this action.
  38234. *
  38235. * @return {AnimationAction} A reference to this animation action.
  38236. */
  38237. stopFading() {
  38238. const weightInterpolant = this._weightInterpolant;
  38239. if ( weightInterpolant !== null ) {
  38240. this._weightInterpolant = null;
  38241. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38242. }
  38243. return this;
  38244. }
  38245. /**
  38246. * Sets the effective time scale of this action.
  38247. *
  38248. * An action has no effect and thus an effective time scale of zero when the
  38249. * action is paused.
  38250. *
  38251. * @param {number} timeScale - The time scale to set.
  38252. * @return {AnimationAction} A reference to this animation action.
  38253. */
  38254. setEffectiveTimeScale( timeScale ) {
  38255. this.timeScale = timeScale;
  38256. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38257. return this.stopWarping();
  38258. }
  38259. /**
  38260. * Returns the effective time scale of this action.
  38261. *
  38262. * @return {number} The effective time scale.
  38263. */
  38264. getEffectiveTimeScale() {
  38265. return this._effectiveTimeScale;
  38266. }
  38267. /**
  38268. * Sets the duration for a single loop of this action.
  38269. *
  38270. * @param {number} duration - The duration to set.
  38271. * @return {AnimationAction} A reference to this animation action.
  38272. */
  38273. setDuration( duration ) {
  38274. this.timeScale = this._clip.duration / duration;
  38275. return this.stopWarping();
  38276. }
  38277. /**
  38278. * Synchronizes this action with the passed other action.
  38279. *
  38280. * @param {AnimationAction} action - The action to sync with.
  38281. * @return {AnimationAction} A reference to this animation action.
  38282. */
  38283. syncWith( action ) {
  38284. this.time = action.time;
  38285. this.timeScale = action.timeScale;
  38286. return this.stopWarping();
  38287. }
  38288. /**
  38289. * Decelerates this animation's speed to `0` within the passed time interval.
  38290. *
  38291. * @param {number} duration - The duration.
  38292. * @return {AnimationAction} A reference to this animation action.
  38293. */
  38294. halt( duration ) {
  38295. return this.warp( this._effectiveTimeScale, 0, duration );
  38296. }
  38297. /**
  38298. * Changes the playback speed, within the passed time interval, by modifying
  38299. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38300. * `endTimeScale`.
  38301. *
  38302. * @param {number} startTimeScale - The start time scale.
  38303. * @param {number} endTimeScale - The end time scale.
  38304. * @param {number} duration - The duration.
  38305. * @return {AnimationAction} A reference to this animation action.
  38306. */
  38307. warp( startTimeScale, endTimeScale, duration ) {
  38308. const mixer = this._mixer,
  38309. now = mixer.time,
  38310. timeScale = this.timeScale;
  38311. let interpolant = this._timeScaleInterpolant;
  38312. if ( interpolant === null ) {
  38313. interpolant = mixer._lendControlInterpolant();
  38314. this._timeScaleInterpolant = interpolant;
  38315. }
  38316. const times = interpolant.parameterPositions,
  38317. values = interpolant.sampleValues;
  38318. times[ 0 ] = now;
  38319. times[ 1 ] = now + duration;
  38320. values[ 0 ] = startTimeScale / timeScale;
  38321. values[ 1 ] = endTimeScale / timeScale;
  38322. return this;
  38323. }
  38324. /**
  38325. * Stops any scheduled warping which is applied to this action.
  38326. *
  38327. * @return {AnimationAction} A reference to this animation action.
  38328. */
  38329. stopWarping() {
  38330. const timeScaleInterpolant = this._timeScaleInterpolant;
  38331. if ( timeScaleInterpolant !== null ) {
  38332. this._timeScaleInterpolant = null;
  38333. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38334. }
  38335. return this;
  38336. }
  38337. /**
  38338. * Returns the animation mixer of this animation action.
  38339. *
  38340. * @return {AnimationMixer} The animation mixer.
  38341. */
  38342. getMixer() {
  38343. return this._mixer;
  38344. }
  38345. /**
  38346. * Returns the animation clip of this animation action.
  38347. *
  38348. * @return {AnimationClip} The animation clip.
  38349. */
  38350. getClip() {
  38351. return this._clip;
  38352. }
  38353. /**
  38354. * Returns the root object of this animation action.
  38355. *
  38356. * @return {Object3D} The root object.
  38357. */
  38358. getRoot() {
  38359. return this._localRoot || this._mixer._root;
  38360. }
  38361. // Interna
  38362. _update( time, deltaTime, timeDirection, accuIndex ) {
  38363. // called by the mixer
  38364. if ( ! this.enabled ) {
  38365. // call ._updateWeight() to update ._effectiveWeight
  38366. this._updateWeight( time );
  38367. return;
  38368. }
  38369. const startTime = this._startTime;
  38370. if ( startTime !== null ) {
  38371. // check for scheduled start of action
  38372. const timeRunning = ( time - startTime ) * timeDirection;
  38373. if ( timeRunning < 0 || timeDirection === 0 ) {
  38374. deltaTime = 0;
  38375. } else {
  38376. this._startTime = null; // unschedule
  38377. deltaTime = timeDirection * timeRunning;
  38378. }
  38379. }
  38380. // apply time scale and advance time
  38381. deltaTime *= this._updateTimeScale( time );
  38382. const clipTime = this._updateTime( deltaTime );
  38383. // note: _updateTime may disable the action resulting in
  38384. // an effective weight of 0
  38385. const weight = this._updateWeight( time );
  38386. if ( weight > 0 ) {
  38387. const interpolants = this._interpolants;
  38388. const propertyMixers = this._propertyBindings;
  38389. switch ( this.blendMode ) {
  38390. case AdditiveAnimationBlendMode:
  38391. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38392. interpolants[ j ].evaluate( clipTime );
  38393. propertyMixers[ j ].accumulateAdditive( weight );
  38394. }
  38395. break;
  38396. case NormalAnimationBlendMode:
  38397. default:
  38398. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38399. interpolants[ j ].evaluate( clipTime );
  38400. propertyMixers[ j ].accumulate( accuIndex, weight );
  38401. }
  38402. }
  38403. }
  38404. }
  38405. _updateWeight( time ) {
  38406. let weight = 0;
  38407. if ( this.enabled ) {
  38408. weight = this.weight;
  38409. const interpolant = this._weightInterpolant;
  38410. if ( interpolant !== null ) {
  38411. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38412. weight *= interpolantValue;
  38413. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38414. this.stopFading();
  38415. if ( interpolantValue === 0 ) {
  38416. // faded out, disable
  38417. this.enabled = false;
  38418. }
  38419. }
  38420. }
  38421. }
  38422. this._effectiveWeight = weight;
  38423. return weight;
  38424. }
  38425. _updateTimeScale( time ) {
  38426. let timeScale = 0;
  38427. if ( ! this.paused ) {
  38428. timeScale = this.timeScale;
  38429. const interpolant = this._timeScaleInterpolant;
  38430. if ( interpolant !== null ) {
  38431. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38432. timeScale *= interpolantValue;
  38433. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38434. this.stopWarping();
  38435. if ( timeScale === 0 ) {
  38436. // motion has halted, pause
  38437. this.paused = true;
  38438. } else {
  38439. // warp done - apply final time scale
  38440. this.timeScale = timeScale;
  38441. }
  38442. }
  38443. }
  38444. }
  38445. this._effectiveTimeScale = timeScale;
  38446. return timeScale;
  38447. }
  38448. _updateTime( deltaTime ) {
  38449. const duration = this._clip.duration;
  38450. const loop = this.loop;
  38451. let time = this.time + deltaTime;
  38452. let loopCount = this._loopCount;
  38453. const pingPong = ( loop === LoopPingPong );
  38454. if ( deltaTime === 0 ) {
  38455. if ( loopCount === -1 ) return time;
  38456. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38457. }
  38458. if ( loop === LoopOnce ) {
  38459. if ( loopCount === -1 ) {
  38460. // just started
  38461. this._loopCount = 0;
  38462. this._setEndings( true, true, false );
  38463. }
  38464. handle_stop: {
  38465. if ( time >= duration ) {
  38466. time = duration;
  38467. } else if ( time < 0 ) {
  38468. time = 0;
  38469. } else {
  38470. this.time = time;
  38471. break handle_stop;
  38472. }
  38473. if ( this.clampWhenFinished ) this.paused = true;
  38474. else this.enabled = false;
  38475. this.time = time;
  38476. this._mixer.dispatchEvent( {
  38477. type: 'finished', action: this,
  38478. direction: deltaTime < 0 ? -1 : 1
  38479. } );
  38480. }
  38481. } else { // repetitive Repeat or PingPong
  38482. if ( loopCount === -1 ) {
  38483. // just started
  38484. if ( deltaTime >= 0 ) {
  38485. loopCount = 0;
  38486. this._setEndings( true, this.repetitions === 0, pingPong );
  38487. } else {
  38488. // when looping in reverse direction, the initial
  38489. // transition through zero counts as a repetition,
  38490. // so leave loopCount at -1
  38491. this._setEndings( this.repetitions === 0, true, pingPong );
  38492. }
  38493. }
  38494. if ( time >= duration || time < 0 ) {
  38495. // wrap around
  38496. const loopDelta = Math.floor( time / duration ); // signed
  38497. time -= duration * loopDelta;
  38498. loopCount += Math.abs( loopDelta );
  38499. const pending = this.repetitions - loopCount;
  38500. if ( pending <= 0 ) {
  38501. // have to stop (switch state, clamp time, fire event)
  38502. if ( this.clampWhenFinished ) this.paused = true;
  38503. else this.enabled = false;
  38504. time = deltaTime > 0 ? duration : 0;
  38505. this.time = time;
  38506. this._mixer.dispatchEvent( {
  38507. type: 'finished', action: this,
  38508. direction: deltaTime > 0 ? 1 : -1
  38509. } );
  38510. } else {
  38511. // keep running
  38512. if ( pending === 1 ) {
  38513. // entering the last round
  38514. const atStart = deltaTime < 0;
  38515. this._setEndings( atStart, ! atStart, pingPong );
  38516. } else {
  38517. this._setEndings( false, false, pingPong );
  38518. }
  38519. this._loopCount = loopCount;
  38520. this.time = time;
  38521. this._mixer.dispatchEvent( {
  38522. type: 'loop', action: this, loopDelta: loopDelta
  38523. } );
  38524. }
  38525. } else {
  38526. this.time = time;
  38527. }
  38528. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38529. // invert time for the "pong round"
  38530. return duration - time;
  38531. }
  38532. }
  38533. return time;
  38534. }
  38535. _setEndings( atStart, atEnd, pingPong ) {
  38536. const settings = this._interpolantSettings;
  38537. if ( pingPong ) {
  38538. settings.endingStart = ZeroSlopeEnding;
  38539. settings.endingEnd = ZeroSlopeEnding;
  38540. } else {
  38541. // assuming for LoopOnce atStart == atEnd == true
  38542. if ( atStart ) {
  38543. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38544. } else {
  38545. settings.endingStart = WrapAroundEnding;
  38546. }
  38547. if ( atEnd ) {
  38548. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38549. } else {
  38550. settings.endingEnd = WrapAroundEnding;
  38551. }
  38552. }
  38553. }
  38554. _scheduleFading( duration, weightNow, weightThen ) {
  38555. const mixer = this._mixer, now = mixer.time;
  38556. let interpolant = this._weightInterpolant;
  38557. if ( interpolant === null ) {
  38558. interpolant = mixer._lendControlInterpolant();
  38559. this._weightInterpolant = interpolant;
  38560. }
  38561. const times = interpolant.parameterPositions,
  38562. values = interpolant.sampleValues;
  38563. times[ 0 ] = now;
  38564. values[ 0 ] = weightNow;
  38565. times[ 1 ] = now + duration;
  38566. values[ 1 ] = weightThen;
  38567. return this;
  38568. }
  38569. }
  38570. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38571. /**
  38572. * `AnimationMixer` is a player for animations on a particular object in
  38573. * the scene. When multiple objects in the scene are animated independently,
  38574. * one `AnimationMixer` may be used for each object.
  38575. */
  38576. class AnimationMixer extends EventDispatcher {
  38577. /**
  38578. * Constructs a new animation mixer.
  38579. *
  38580. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38581. */
  38582. constructor( root ) {
  38583. super();
  38584. this._root = root;
  38585. this._initMemoryManager();
  38586. this._accuIndex = 0;
  38587. /**
  38588. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38589. *
  38590. * @type {number}
  38591. * @default 0
  38592. */
  38593. this.time = 0;
  38594. /**
  38595. * A scaling factor for the global time.
  38596. *
  38597. * Note: Setting this member to `0` and later back to `1` is a
  38598. * possibility to pause/unpause all actions that are controlled by this
  38599. * mixer.
  38600. *
  38601. * @type {number}
  38602. * @default 1
  38603. */
  38604. this.timeScale = 1.0;
  38605. }
  38606. _bindAction( action, prototypeAction ) {
  38607. const root = action._localRoot || this._root,
  38608. tracks = action._clip.tracks,
  38609. nTracks = tracks.length,
  38610. bindings = action._propertyBindings,
  38611. interpolants = action._interpolants,
  38612. rootUuid = root.uuid,
  38613. bindingsByRoot = this._bindingsByRootAndName;
  38614. let bindingsByName = bindingsByRoot[ rootUuid ];
  38615. if ( bindingsByName === undefined ) {
  38616. bindingsByName = {};
  38617. bindingsByRoot[ rootUuid ] = bindingsByName;
  38618. }
  38619. for ( let i = 0; i !== nTracks; ++ i ) {
  38620. const track = tracks[ i ],
  38621. trackName = track.name;
  38622. let binding = bindingsByName[ trackName ];
  38623. if ( binding !== undefined ) {
  38624. ++ binding.referenceCount;
  38625. bindings[ i ] = binding;
  38626. } else {
  38627. binding = bindings[ i ];
  38628. if ( binding !== undefined ) {
  38629. // existing binding, make sure the cache knows
  38630. if ( binding._cacheIndex === null ) {
  38631. ++ binding.referenceCount;
  38632. this._addInactiveBinding( binding, rootUuid, trackName );
  38633. }
  38634. continue;
  38635. }
  38636. const path = prototypeAction && prototypeAction.
  38637. _propertyBindings[ i ].binding.parsedPath;
  38638. binding = new PropertyMixer(
  38639. PropertyBinding.create( root, trackName, path ),
  38640. track.ValueTypeName, track.getValueSize() );
  38641. ++ binding.referenceCount;
  38642. this._addInactiveBinding( binding, rootUuid, trackName );
  38643. bindings[ i ] = binding;
  38644. }
  38645. interpolants[ i ].resultBuffer = binding.buffer;
  38646. }
  38647. }
  38648. _activateAction( action ) {
  38649. if ( ! this._isActiveAction( action ) ) {
  38650. if ( action._cacheIndex === null ) {
  38651. // this action has been forgotten by the cache, but the user
  38652. // appears to be still using it -> rebind
  38653. const rootUuid = ( action._localRoot || this._root ).uuid,
  38654. clipUuid = action._clip.uuid,
  38655. actionsForClip = this._actionsByClip[ clipUuid ];
  38656. this._bindAction( action,
  38657. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38658. this._addInactiveAction( action, clipUuid, rootUuid );
  38659. }
  38660. const bindings = action._propertyBindings;
  38661. // increment reference counts / sort out state
  38662. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38663. const binding = bindings[ i ];
  38664. if ( binding.useCount ++ === 0 ) {
  38665. this._lendBinding( binding );
  38666. binding.saveOriginalState();
  38667. }
  38668. }
  38669. this._lendAction( action );
  38670. }
  38671. }
  38672. _deactivateAction( action ) {
  38673. if ( this._isActiveAction( action ) ) {
  38674. const bindings = action._propertyBindings;
  38675. // decrement reference counts / sort out state
  38676. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38677. const binding = bindings[ i ];
  38678. if ( -- binding.useCount === 0 ) {
  38679. binding.restoreOriginalState();
  38680. this._takeBackBinding( binding );
  38681. }
  38682. }
  38683. this._takeBackAction( action );
  38684. }
  38685. }
  38686. // Memory manager
  38687. _initMemoryManager() {
  38688. this._actions = []; // 'nActiveActions' followed by inactive ones
  38689. this._nActiveActions = 0;
  38690. this._actionsByClip = {};
  38691. // inside:
  38692. // {
  38693. // knownActions: Array< AnimationAction > - used as prototypes
  38694. // actionByRoot: AnimationAction - lookup
  38695. // }
  38696. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38697. this._nActiveBindings = 0;
  38698. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38699. this._controlInterpolants = []; // same game as above
  38700. this._nActiveControlInterpolants = 0;
  38701. const scope = this;
  38702. this.stats = {
  38703. actions: {
  38704. get total() {
  38705. return scope._actions.length;
  38706. },
  38707. get inUse() {
  38708. return scope._nActiveActions;
  38709. }
  38710. },
  38711. bindings: {
  38712. get total() {
  38713. return scope._bindings.length;
  38714. },
  38715. get inUse() {
  38716. return scope._nActiveBindings;
  38717. }
  38718. },
  38719. controlInterpolants: {
  38720. get total() {
  38721. return scope._controlInterpolants.length;
  38722. },
  38723. get inUse() {
  38724. return scope._nActiveControlInterpolants;
  38725. }
  38726. }
  38727. };
  38728. }
  38729. // Memory management for AnimationAction objects
  38730. _isActiveAction( action ) {
  38731. const index = action._cacheIndex;
  38732. return index !== null && index < this._nActiveActions;
  38733. }
  38734. _addInactiveAction( action, clipUuid, rootUuid ) {
  38735. const actions = this._actions,
  38736. actionsByClip = this._actionsByClip;
  38737. let actionsForClip = actionsByClip[ clipUuid ];
  38738. if ( actionsForClip === undefined ) {
  38739. actionsForClip = {
  38740. knownActions: [ action ],
  38741. actionByRoot: {}
  38742. };
  38743. action._byClipCacheIndex = 0;
  38744. actionsByClip[ clipUuid ] = actionsForClip;
  38745. } else {
  38746. const knownActions = actionsForClip.knownActions;
  38747. action._byClipCacheIndex = knownActions.length;
  38748. knownActions.push( action );
  38749. }
  38750. action._cacheIndex = actions.length;
  38751. actions.push( action );
  38752. actionsForClip.actionByRoot[ rootUuid ] = action;
  38753. }
  38754. _removeInactiveAction( action ) {
  38755. const actions = this._actions,
  38756. lastInactiveAction = actions[ actions.length - 1 ],
  38757. cacheIndex = action._cacheIndex;
  38758. lastInactiveAction._cacheIndex = cacheIndex;
  38759. actions[ cacheIndex ] = lastInactiveAction;
  38760. actions.pop();
  38761. action._cacheIndex = null;
  38762. const clipUuid = action._clip.uuid,
  38763. actionsByClip = this._actionsByClip,
  38764. actionsForClip = actionsByClip[ clipUuid ],
  38765. knownActionsForClip = actionsForClip.knownActions,
  38766. lastKnownAction =
  38767. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38768. byClipCacheIndex = action._byClipCacheIndex;
  38769. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38770. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38771. knownActionsForClip.pop();
  38772. action._byClipCacheIndex = null;
  38773. const actionByRoot = actionsForClip.actionByRoot,
  38774. rootUuid = ( action._localRoot || this._root ).uuid;
  38775. delete actionByRoot[ rootUuid ];
  38776. if ( knownActionsForClip.length === 0 ) {
  38777. delete actionsByClip[ clipUuid ];
  38778. }
  38779. this._removeInactiveBindingsForAction( action );
  38780. }
  38781. _removeInactiveBindingsForAction( action ) {
  38782. const bindings = action._propertyBindings;
  38783. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38784. const binding = bindings[ i ];
  38785. if ( -- binding.referenceCount === 0 ) {
  38786. this._removeInactiveBinding( binding );
  38787. }
  38788. }
  38789. }
  38790. _lendAction( action ) {
  38791. // [ active actions | inactive actions ]
  38792. // [ active actions >| inactive actions ]
  38793. // s a
  38794. // <-swap->
  38795. // a s
  38796. const actions = this._actions,
  38797. prevIndex = action._cacheIndex,
  38798. lastActiveIndex = this._nActiveActions ++,
  38799. firstInactiveAction = actions[ lastActiveIndex ];
  38800. action._cacheIndex = lastActiveIndex;
  38801. actions[ lastActiveIndex ] = action;
  38802. firstInactiveAction._cacheIndex = prevIndex;
  38803. actions[ prevIndex ] = firstInactiveAction;
  38804. }
  38805. _takeBackAction( action ) {
  38806. // [ active actions | inactive actions ]
  38807. // [ active actions |< inactive actions ]
  38808. // a s
  38809. // <-swap->
  38810. // s a
  38811. const actions = this._actions,
  38812. prevIndex = action._cacheIndex,
  38813. firstInactiveIndex = -- this._nActiveActions,
  38814. lastActiveAction = actions[ firstInactiveIndex ];
  38815. action._cacheIndex = firstInactiveIndex;
  38816. actions[ firstInactiveIndex ] = action;
  38817. lastActiveAction._cacheIndex = prevIndex;
  38818. actions[ prevIndex ] = lastActiveAction;
  38819. }
  38820. // Memory management for PropertyMixer objects
  38821. _addInactiveBinding( binding, rootUuid, trackName ) {
  38822. const bindingsByRoot = this._bindingsByRootAndName,
  38823. bindings = this._bindings;
  38824. let bindingByName = bindingsByRoot[ rootUuid ];
  38825. if ( bindingByName === undefined ) {
  38826. bindingByName = {};
  38827. bindingsByRoot[ rootUuid ] = bindingByName;
  38828. }
  38829. bindingByName[ trackName ] = binding;
  38830. binding._cacheIndex = bindings.length;
  38831. bindings.push( binding );
  38832. }
  38833. _removeInactiveBinding( binding ) {
  38834. const bindings = this._bindings,
  38835. propBinding = binding.binding,
  38836. rootUuid = propBinding.rootNode.uuid,
  38837. trackName = propBinding.path,
  38838. bindingsByRoot = this._bindingsByRootAndName,
  38839. bindingByName = bindingsByRoot[ rootUuid ],
  38840. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38841. cacheIndex = binding._cacheIndex;
  38842. lastInactiveBinding._cacheIndex = cacheIndex;
  38843. bindings[ cacheIndex ] = lastInactiveBinding;
  38844. bindings.pop();
  38845. delete bindingByName[ trackName ];
  38846. if ( Object.keys( bindingByName ).length === 0 ) {
  38847. delete bindingsByRoot[ rootUuid ];
  38848. }
  38849. }
  38850. _lendBinding( binding ) {
  38851. const bindings = this._bindings,
  38852. prevIndex = binding._cacheIndex,
  38853. lastActiveIndex = this._nActiveBindings ++,
  38854. firstInactiveBinding = bindings[ lastActiveIndex ];
  38855. binding._cacheIndex = lastActiveIndex;
  38856. bindings[ lastActiveIndex ] = binding;
  38857. firstInactiveBinding._cacheIndex = prevIndex;
  38858. bindings[ prevIndex ] = firstInactiveBinding;
  38859. }
  38860. _takeBackBinding( binding ) {
  38861. const bindings = this._bindings,
  38862. prevIndex = binding._cacheIndex,
  38863. firstInactiveIndex = -- this._nActiveBindings,
  38864. lastActiveBinding = bindings[ firstInactiveIndex ];
  38865. binding._cacheIndex = firstInactiveIndex;
  38866. bindings[ firstInactiveIndex ] = binding;
  38867. lastActiveBinding._cacheIndex = prevIndex;
  38868. bindings[ prevIndex ] = lastActiveBinding;
  38869. }
  38870. // Memory management of Interpolants for weight and time scale
  38871. _lendControlInterpolant() {
  38872. const interpolants = this._controlInterpolants,
  38873. lastActiveIndex = this._nActiveControlInterpolants ++;
  38874. let interpolant = interpolants[ lastActiveIndex ];
  38875. if ( interpolant === undefined ) {
  38876. interpolant = new LinearInterpolant(
  38877. new Float32Array( 2 ), new Float32Array( 2 ),
  38878. 1, _controlInterpolantsResultBuffer );
  38879. interpolant.__cacheIndex = lastActiveIndex;
  38880. interpolants[ lastActiveIndex ] = interpolant;
  38881. }
  38882. return interpolant;
  38883. }
  38884. _takeBackControlInterpolant( interpolant ) {
  38885. const interpolants = this._controlInterpolants,
  38886. prevIndex = interpolant.__cacheIndex,
  38887. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38888. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38889. interpolant.__cacheIndex = firstInactiveIndex;
  38890. interpolants[ firstInactiveIndex ] = interpolant;
  38891. lastActiveInterpolant.__cacheIndex = prevIndex;
  38892. interpolants[ prevIndex ] = lastActiveInterpolant;
  38893. }
  38894. /**
  38895. * Returns an instance of {@link AnimationAction} for the passed clip.
  38896. *
  38897. * If an action fitting the clip and root parameters doesn't yet exist, it
  38898. * will be created by this method. Calling this method several times with the
  38899. * same clip and root parameters always returns the same action.
  38900. *
  38901. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38902. * @param {Object3D} [optionalRoot] - An alternative root object.
  38903. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38904. * @return {?AnimationAction} The animation action.
  38905. */
  38906. clipAction( clip, optionalRoot, blendMode ) {
  38907. const root = optionalRoot || this._root,
  38908. rootUuid = root.uuid;
  38909. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38910. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38911. const actionsForClip = this._actionsByClip[ clipUuid ];
  38912. let prototypeAction = null;
  38913. if ( blendMode === undefined ) {
  38914. if ( clipObject !== null ) {
  38915. blendMode = clipObject.blendMode;
  38916. } else {
  38917. blendMode = NormalAnimationBlendMode;
  38918. }
  38919. }
  38920. if ( actionsForClip !== undefined ) {
  38921. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38922. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38923. return existingAction;
  38924. }
  38925. // we know the clip, so we don't have to parse all
  38926. // the bindings again but can just copy
  38927. prototypeAction = actionsForClip.knownActions[ 0 ];
  38928. // also, take the clip from the prototype action
  38929. if ( clipObject === null )
  38930. clipObject = prototypeAction._clip;
  38931. }
  38932. // clip must be known when specified via string
  38933. if ( clipObject === null ) return null;
  38934. // allocate all resources required to run it
  38935. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38936. this._bindAction( newAction, prototypeAction );
  38937. // and make the action known to the memory manager
  38938. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38939. return newAction;
  38940. }
  38941. /**
  38942. * Returns an existing animation action for the passed clip.
  38943. *
  38944. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38945. * @param {Object3D} [optionalRoot] - An alternative root object.
  38946. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38947. */
  38948. existingAction( clip, optionalRoot ) {
  38949. const root = optionalRoot || this._root,
  38950. rootUuid = root.uuid,
  38951. clipObject = typeof clip === 'string' ?
  38952. AnimationClip.findByName( root, clip ) : clip,
  38953. clipUuid = clipObject ? clipObject.uuid : clip,
  38954. actionsForClip = this._actionsByClip[ clipUuid ];
  38955. if ( actionsForClip !== undefined ) {
  38956. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38957. }
  38958. return null;
  38959. }
  38960. /**
  38961. * Deactivates all previously scheduled actions on this mixer.
  38962. *
  38963. * @return {AnimationMixer} A reference to thi animation mixer.
  38964. */
  38965. stopAllAction() {
  38966. const actions = this._actions,
  38967. nActions = this._nActiveActions;
  38968. for ( let i = nActions - 1; i >= 0; -- i ) {
  38969. actions[ i ].stop();
  38970. }
  38971. return this;
  38972. }
  38973. /**
  38974. * Advances the global mixer time and updates the animation.
  38975. *
  38976. * This is usually done in the render loop by passing the delta
  38977. * time from {@link Clock} or {@link Timer}.
  38978. *
  38979. * @param {number} deltaTime - The delta time in seconds.
  38980. * @return {AnimationMixer} A reference to thi animation mixer.
  38981. */
  38982. update( deltaTime ) {
  38983. deltaTime *= this.timeScale;
  38984. const actions = this._actions,
  38985. nActions = this._nActiveActions,
  38986. time = this.time += deltaTime,
  38987. timeDirection = Math.sign( deltaTime ),
  38988. accuIndex = this._accuIndex ^= 1;
  38989. // run active actions
  38990. for ( let i = 0; i !== nActions; ++ i ) {
  38991. const action = actions[ i ];
  38992. action._update( time, deltaTime, timeDirection, accuIndex );
  38993. }
  38994. // update scene graph
  38995. const bindings = this._bindings,
  38996. nBindings = this._nActiveBindings;
  38997. for ( let i = 0; i !== nBindings; ++ i ) {
  38998. bindings[ i ].apply( accuIndex );
  38999. }
  39000. return this;
  39001. }
  39002. /**
  39003. * Sets the global mixer to a specific time and updates the animation accordingly.
  39004. *
  39005. * This is useful when you need to jump to an exact time in an animation. The
  39006. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39007. *
  39008. * @param {number} time - The time to set in seconds.
  39009. * @return {AnimationMixer} A reference to thi animation mixer.
  39010. */
  39011. setTime( time ) {
  39012. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39013. for ( let i = 0; i < this._actions.length; i ++ ) {
  39014. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39015. }
  39016. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39017. }
  39018. /**
  39019. * Returns this mixer's root object.
  39020. *
  39021. * @return {Object3D} The mixer's root object.
  39022. */
  39023. getRoot() {
  39024. return this._root;
  39025. }
  39026. /**
  39027. * Deallocates all memory resources for a clip. Before using this method make
  39028. * sure to call {@link AnimationAction#stop} for all related actions.
  39029. *
  39030. * @param {AnimationClip} clip - The clip to uncache.
  39031. */
  39032. uncacheClip( clip ) {
  39033. const actions = this._actions,
  39034. clipUuid = clip.uuid,
  39035. actionsByClip = this._actionsByClip,
  39036. actionsForClip = actionsByClip[ clipUuid ];
  39037. if ( actionsForClip !== undefined ) {
  39038. // note: just calling _removeInactiveAction would mess up the
  39039. // iteration state and also require updating the state we can
  39040. // just throw away
  39041. const actionsToRemove = actionsForClip.knownActions;
  39042. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39043. const action = actionsToRemove[ i ];
  39044. this._deactivateAction( action );
  39045. const cacheIndex = action._cacheIndex,
  39046. lastInactiveAction = actions[ actions.length - 1 ];
  39047. action._cacheIndex = null;
  39048. action._byClipCacheIndex = null;
  39049. lastInactiveAction._cacheIndex = cacheIndex;
  39050. actions[ cacheIndex ] = lastInactiveAction;
  39051. actions.pop();
  39052. this._removeInactiveBindingsForAction( action );
  39053. }
  39054. delete actionsByClip[ clipUuid ];
  39055. }
  39056. }
  39057. /**
  39058. * Deallocates all memory resources for a root object. Before using this
  39059. * method make sure to call {@link AnimationAction#stop} for all related
  39060. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39061. * mixer operates on a single root.
  39062. *
  39063. * @param {Object3D} root - The root object to uncache.
  39064. */
  39065. uncacheRoot( root ) {
  39066. const rootUuid = root.uuid,
  39067. actionsByClip = this._actionsByClip;
  39068. for ( const clipUuid in actionsByClip ) {
  39069. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39070. action = actionByRoot[ rootUuid ];
  39071. if ( action !== undefined ) {
  39072. this._deactivateAction( action );
  39073. this._removeInactiveAction( action );
  39074. }
  39075. }
  39076. const bindingsByRoot = this._bindingsByRootAndName,
  39077. bindingByName = bindingsByRoot[ rootUuid ];
  39078. if ( bindingByName !== undefined ) {
  39079. for ( const trackName in bindingByName ) {
  39080. const binding = bindingByName[ trackName ];
  39081. binding.restoreOriginalState();
  39082. this._removeInactiveBinding( binding );
  39083. }
  39084. }
  39085. }
  39086. /**
  39087. * Deallocates all memory resources for an action. The action is identified by the
  39088. * given clip and an optional root object. Before using this method make
  39089. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39090. *
  39091. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39092. * @param {Object3D} [optionalRoot] - An alternative root object.
  39093. */
  39094. uncacheAction( clip, optionalRoot ) {
  39095. const action = this.existingAction( clip, optionalRoot );
  39096. if ( action !== null ) {
  39097. this._deactivateAction( action );
  39098. this._removeInactiveAction( action );
  39099. }
  39100. }
  39101. }
  39102. /**
  39103. * Represents a 3D render target.
  39104. *
  39105. * @augments RenderTarget
  39106. */
  39107. class RenderTarget3D extends RenderTarget {
  39108. /**
  39109. * Constructs a new 3D render target.
  39110. *
  39111. * @param {number} [width=1] - The width of the render target.
  39112. * @param {number} [height=1] - The height of the render target.
  39113. * @param {number} [depth=1] - The height of the render target.
  39114. * @param {RenderTarget~Options} [options] - The configuration object.
  39115. */
  39116. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39117. super( width, height, options );
  39118. /**
  39119. * This flag can be used for type testing.
  39120. *
  39121. * @type {boolean}
  39122. * @readonly
  39123. * @default true
  39124. */
  39125. this.isRenderTarget3D = true;
  39126. this.depth = depth;
  39127. /**
  39128. * Overwritten with a different texture type.
  39129. *
  39130. * @type {Data3DTexture}
  39131. */
  39132. this.texture = new Data3DTexture( null, width, height, depth );
  39133. this._setTextureOptions( options );
  39134. this.texture.isRenderTargetTexture = true;
  39135. }
  39136. }
  39137. /**
  39138. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39139. *
  39140. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39141. * ```js
  39142. * uniforms: {
  39143. * time: { value: 1.0 },
  39144. * resolution: new Uniform( new Vector2() )
  39145. * };
  39146. * ```
  39147. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39148. * in {@link WebGLRenderer}.
  39149. */
  39150. class Uniform {
  39151. /**
  39152. * Constructs a new uniform.
  39153. *
  39154. * @param {any} value - The uniform value.
  39155. */
  39156. constructor( value ) {
  39157. /**
  39158. * The uniform value.
  39159. *
  39160. * @type {any}
  39161. */
  39162. this.value = value;
  39163. }
  39164. /**
  39165. * Returns a new uniform with copied values from this instance.
  39166. * If the value has a `clone()` method, the value is cloned as well.
  39167. *
  39168. * @return {Uniform} A clone of this instance.
  39169. */
  39170. clone() {
  39171. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39172. }
  39173. }
  39174. let _id = 0;
  39175. /**
  39176. * A class for managing multiple uniforms in a single group. The renderer will process
  39177. * such a definition as a single UBO.
  39178. *
  39179. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39180. * in {@link WebGLRenderer}.
  39181. *
  39182. * @augments EventDispatcher
  39183. */
  39184. class UniformsGroup extends EventDispatcher {
  39185. /**
  39186. * Constructs a new uniforms group.
  39187. */
  39188. constructor() {
  39189. super();
  39190. /**
  39191. * This flag can be used for type testing.
  39192. *
  39193. * @type {boolean}
  39194. * @readonly
  39195. * @default true
  39196. */
  39197. this.isUniformsGroup = true;
  39198. /**
  39199. * The ID of the 3D object.
  39200. *
  39201. * @name UniformsGroup#id
  39202. * @type {number}
  39203. * @readonly
  39204. */
  39205. Object.defineProperty( this, 'id', { value: _id ++ } );
  39206. /**
  39207. * The name of the uniforms group.
  39208. *
  39209. * @type {string}
  39210. */
  39211. this.name = '';
  39212. /**
  39213. * The buffer usage.
  39214. *
  39215. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39216. * @default StaticDrawUsage
  39217. */
  39218. this.usage = StaticDrawUsage;
  39219. /**
  39220. * An array holding the uniforms.
  39221. *
  39222. * @type {Array<Uniform>}
  39223. */
  39224. this.uniforms = [];
  39225. }
  39226. /**
  39227. * Adds the given uniform to this uniforms group.
  39228. *
  39229. * @param {Uniform} uniform - The uniform to add.
  39230. * @return {UniformsGroup} A reference to this uniforms group.
  39231. */
  39232. add( uniform ) {
  39233. this.uniforms.push( uniform );
  39234. return this;
  39235. }
  39236. /**
  39237. * Removes the given uniform from this uniforms group.
  39238. *
  39239. * @param {Uniform} uniform - The uniform to remove.
  39240. * @return {UniformsGroup} A reference to this uniforms group.
  39241. */
  39242. remove( uniform ) {
  39243. const index = this.uniforms.indexOf( uniform );
  39244. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39245. return this;
  39246. }
  39247. /**
  39248. * Sets the name of this uniforms group.
  39249. *
  39250. * @param {string} name - The name to set.
  39251. * @return {UniformsGroup} A reference to this uniforms group.
  39252. */
  39253. setName( name ) {
  39254. this.name = name;
  39255. return this;
  39256. }
  39257. /**
  39258. * Sets the usage of this uniforms group.
  39259. *
  39260. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39261. * @return {UniformsGroup} A reference to this uniforms group.
  39262. */
  39263. setUsage( value ) {
  39264. this.usage = value;
  39265. return this;
  39266. }
  39267. /**
  39268. * Frees the GPU-related resources allocated by this instance. Call this
  39269. * method whenever this instance is no longer used in your app.
  39270. *
  39271. * @fires Texture#dispose
  39272. */
  39273. dispose() {
  39274. this.dispatchEvent( { type: 'dispose' } );
  39275. }
  39276. /**
  39277. * Copies the values of the given uniforms group to this instance.
  39278. *
  39279. * @param {UniformsGroup} source - The uniforms group to copy.
  39280. * @return {UniformsGroup} A reference to this uniforms group.
  39281. */
  39282. copy( source ) {
  39283. this.name = source.name;
  39284. this.usage = source.usage;
  39285. const uniformsSource = source.uniforms;
  39286. this.uniforms.length = 0;
  39287. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39288. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39289. for ( let j = 0; j < uniforms.length; j ++ ) {
  39290. this.uniforms.push( uniforms[ j ].clone() );
  39291. }
  39292. }
  39293. return this;
  39294. }
  39295. /**
  39296. * Returns a new uniforms group with copied values from this instance.
  39297. *
  39298. * @return {UniformsGroup} A clone of this instance.
  39299. */
  39300. clone() {
  39301. return new this.constructor().copy( this );
  39302. }
  39303. }
  39304. /**
  39305. * An instanced version of an interleaved buffer.
  39306. *
  39307. * @augments InterleavedBuffer
  39308. */
  39309. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39310. /**
  39311. * Constructs a new instanced interleaved buffer.
  39312. *
  39313. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39314. * @param {number} stride - The number of typed-array elements per vertex.
  39315. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39316. */
  39317. constructor( array, stride, meshPerAttribute = 1 ) {
  39318. super( array, stride );
  39319. /**
  39320. * This flag can be used for type testing.
  39321. *
  39322. * @type {boolean}
  39323. * @readonly
  39324. * @default true
  39325. */
  39326. this.isInstancedInterleavedBuffer = true;
  39327. /**
  39328. * Defines how often a value of this buffer attribute should be repeated,
  39329. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39330. *
  39331. * @type {number}
  39332. * @default 1
  39333. */
  39334. this.meshPerAttribute = meshPerAttribute;
  39335. }
  39336. copy( source ) {
  39337. super.copy( source );
  39338. this.meshPerAttribute = source.meshPerAttribute;
  39339. return this;
  39340. }
  39341. clone( data ) {
  39342. const ib = super.clone( data );
  39343. ib.meshPerAttribute = this.meshPerAttribute;
  39344. return ib;
  39345. }
  39346. toJSON( data ) {
  39347. const json = super.toJSON( data );
  39348. json.isInstancedInterleavedBuffer = true;
  39349. json.meshPerAttribute = this.meshPerAttribute;
  39350. return json;
  39351. }
  39352. }
  39353. /**
  39354. * An alternative version of a buffer attribute with more control over the VBO.
  39355. *
  39356. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39357. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39358. *
  39359. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39360. * or even produces the VBOs in question.
  39361. *
  39362. * Notice that this class can only be used with {@link WebGLRenderer}.
  39363. */
  39364. class GLBufferAttribute {
  39365. /**
  39366. * Constructs a new GL buffer attribute.
  39367. *
  39368. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39369. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39370. * @param {number} itemSize - The item size.
  39371. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39372. * @param {number} count - The expected number of vertices in VBO.
  39373. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39374. */
  39375. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39376. /**
  39377. * This flag can be used for type testing.
  39378. *
  39379. * @type {boolean}
  39380. * @readonly
  39381. * @default true
  39382. */
  39383. this.isGLBufferAttribute = true;
  39384. /**
  39385. * The name of the buffer attribute.
  39386. *
  39387. * @type {string}
  39388. */
  39389. this.name = '';
  39390. /**
  39391. * The native WebGL buffer.
  39392. *
  39393. * @type {WebGLBuffer}
  39394. */
  39395. this.buffer = buffer;
  39396. /**
  39397. * The native data type.
  39398. *
  39399. * @type {number}
  39400. */
  39401. this.type = type;
  39402. /**
  39403. * The item size, see {@link BufferAttribute#itemSize}.
  39404. *
  39405. * @type {number}
  39406. */
  39407. this.itemSize = itemSize;
  39408. /**
  39409. * The corresponding size (in bytes) for the given `type` parameter.
  39410. *
  39411. * @type {number}
  39412. */
  39413. this.elementSize = elementSize;
  39414. /**
  39415. * The expected number of vertices in VBO.
  39416. *
  39417. * @type {number}
  39418. */
  39419. this.count = count;
  39420. /**
  39421. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39422. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39423. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39424. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39425. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39426. *
  39427. * @type {boolean}
  39428. */
  39429. this.normalized = normalized;
  39430. /**
  39431. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39432. *
  39433. * @type {number}
  39434. */
  39435. this.version = 0;
  39436. }
  39437. /**
  39438. * Flag to indicate that this attribute has changed and should be re-sent to
  39439. * the GPU. Set this to `true` when you modify the value of the array.
  39440. *
  39441. * @type {number}
  39442. * @default false
  39443. * @param {boolean} value
  39444. */
  39445. set needsUpdate( value ) {
  39446. if ( value === true ) this.version ++;
  39447. }
  39448. /**
  39449. * Sets the given native WebGL buffer.
  39450. *
  39451. * @param {WebGLBuffer} buffer - The buffer to set.
  39452. * @return {BufferAttribute} A reference to this instance.
  39453. */
  39454. setBuffer( buffer ) {
  39455. this.buffer = buffer;
  39456. return this;
  39457. }
  39458. /**
  39459. * Sets the given native data type and element size.
  39460. *
  39461. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39462. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39463. * @return {BufferAttribute} A reference to this instance.
  39464. */
  39465. setType( type, elementSize ) {
  39466. this.type = type;
  39467. this.elementSize = elementSize;
  39468. return this;
  39469. }
  39470. /**
  39471. * Sets the item size.
  39472. *
  39473. * @param {number} itemSize - The item size.
  39474. * @return {BufferAttribute} A reference to this instance.
  39475. */
  39476. setItemSize( itemSize ) {
  39477. this.itemSize = itemSize;
  39478. return this;
  39479. }
  39480. /**
  39481. * Sets the count (the expected number of vertices in VBO).
  39482. *
  39483. * @param {number} count - The count.
  39484. * @return {BufferAttribute} A reference to this instance.
  39485. */
  39486. setCount( count ) {
  39487. this.count = count;
  39488. return this;
  39489. }
  39490. }
  39491. const _matrix = /*@__PURE__*/ new Matrix4();
  39492. /**
  39493. * This class is designed to assist with raycasting. Raycasting is used for
  39494. * mouse picking (working out what objects in the 3d space the mouse is over)
  39495. * amongst other things.
  39496. */
  39497. class Raycaster {
  39498. /**
  39499. * Constructs a new raycaster.
  39500. *
  39501. * @param {Vector3} origin - The origin vector where the ray casts from.
  39502. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39503. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39504. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39505. */
  39506. constructor( origin, direction, near = 0, far = Infinity ) {
  39507. /**
  39508. * The ray used for raycasting.
  39509. *
  39510. * @type {Ray}
  39511. */
  39512. this.ray = new Ray( origin, direction );
  39513. /**
  39514. * All results returned are further away than near. Near can't be negative.
  39515. *
  39516. * @type {number}
  39517. * @default 0
  39518. */
  39519. this.near = near;
  39520. /**
  39521. * All results returned are further away than near. Near can't be negative.
  39522. *
  39523. * @type {number}
  39524. * @default Infinity
  39525. */
  39526. this.far = far;
  39527. /**
  39528. * The camera to use when raycasting against view-dependent objects such as
  39529. * billboarded objects like sprites. This field can be set manually or
  39530. * is set when calling `setFromCamera()`.
  39531. *
  39532. * @type {?Camera}
  39533. * @default null
  39534. */
  39535. this.camera = null;
  39536. /**
  39537. * Allows to selectively ignore 3D objects when performing intersection tests.
  39538. * The following code example ensures that only 3D objects on layer `1` will be
  39539. * honored by raycaster.
  39540. * ```js
  39541. * raycaster.layers.set( 1 );
  39542. * object.layers.enable( 1 );
  39543. * ```
  39544. *
  39545. * @type {Layers}
  39546. */
  39547. this.layers = new Layers();
  39548. /**
  39549. * A parameter object that configures the raycasting. It has the structure:
  39550. *
  39551. * ```
  39552. * {
  39553. * Mesh: {},
  39554. * Line: { threshold: 1 },
  39555. * LOD: {},
  39556. * Points: { threshold: 1 },
  39557. * Sprite: {}
  39558. * }
  39559. * ```
  39560. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39561. *
  39562. * @type {Object}
  39563. */
  39564. this.params = {
  39565. Mesh: {},
  39566. Line: { threshold: 1 },
  39567. LOD: {},
  39568. Points: { threshold: 1 },
  39569. Sprite: {}
  39570. };
  39571. }
  39572. /**
  39573. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39574. *
  39575. * @param {Vector3} origin - The origin vector where the ray casts from.
  39576. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39577. */
  39578. set( origin, direction ) {
  39579. // direction is assumed to be normalized (for accurate distance calculations)
  39580. this.ray.set( origin, direction );
  39581. }
  39582. /**
  39583. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39584. *
  39585. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39586. * X and Y components should be between `-1` and `1`.
  39587. * @param {Camera} camera - The camera from which the ray should originate.
  39588. */
  39589. setFromCamera( coords, camera ) {
  39590. if ( camera.isPerspectiveCamera ) {
  39591. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39592. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39593. this.camera = camera;
  39594. } else if ( camera.isOrthographicCamera ) {
  39595. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39596. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39597. this.camera = camera;
  39598. } else {
  39599. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39600. }
  39601. }
  39602. /**
  39603. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39604. *
  39605. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39606. * @return {Raycaster} A reference to this raycaster.
  39607. */
  39608. setFromXRController( controller ) {
  39609. _matrix.identity().extractRotation( controller.matrixWorld );
  39610. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39611. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39612. return this;
  39613. }
  39614. /**
  39615. * The intersection point of a raycaster intersection test.
  39616. * @typedef {Object} Raycaster~Intersection
  39617. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39618. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39619. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39620. * @property {Vector3} point - The intersection point, in world coordinates.
  39621. * @property {Object} face - The face that has been intersected.
  39622. * @property {number} faceIndex - The face index.
  39623. * @property {Object3D} object - The 3D object that has been intersected.
  39624. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39625. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39626. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39627. * @property {number} instanceId - The index number of the instance where the ray
  39628. * intersects the {@link InstancedMesh}.
  39629. */
  39630. /**
  39631. * Checks all intersection between the ray and the object with or without the
  39632. * descendants. Intersections are returned sorted by distance, closest first.
  39633. *
  39634. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39635. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39636. * differently to ray casting than lines or points.
  39637. *
  39638. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39639. * to be detected; intersections of the ray passing through the back of a face will not
  39640. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39641. * to `THREE.DoubleSide`.
  39642. *
  39643. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39644. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39645. * Otherwise it only checks intersection with the object.
  39646. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39647. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39648. */
  39649. intersectObject( object, recursive = true, intersects = [] ) {
  39650. intersect( object, this, intersects, recursive );
  39651. intersects.sort( ascSort );
  39652. return intersects;
  39653. }
  39654. /**
  39655. * Checks all intersection between the ray and the objects with or without
  39656. * the descendants. Intersections are returned sorted by distance, closest first.
  39657. *
  39658. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39659. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39660. * Otherwise it only checks intersection with the object.
  39661. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39662. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39663. */
  39664. intersectObjects( objects, recursive = true, intersects = [] ) {
  39665. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39666. intersect( objects[ i ], this, intersects, recursive );
  39667. }
  39668. intersects.sort( ascSort );
  39669. return intersects;
  39670. }
  39671. }
  39672. function ascSort( a, b ) {
  39673. return a.distance - b.distance;
  39674. }
  39675. function intersect( object, raycaster, intersects, recursive ) {
  39676. let propagate = true;
  39677. if ( object.layers.test( raycaster.layers ) ) {
  39678. const result = object.raycast( raycaster, intersects );
  39679. if ( result === false ) propagate = false;
  39680. }
  39681. if ( propagate === true && recursive === true ) {
  39682. const children = object.children;
  39683. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39684. intersect( children[ i ], raycaster, intersects, true );
  39685. }
  39686. }
  39687. }
  39688. /**
  39689. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39690. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39691. *
  39692. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39693. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39694. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39695. * is inactive (e.g. tab switched or browser hidden).
  39696. *
  39697. * ```js
  39698. * const timer = new Timer();
  39699. * timer.connect( document ); // use Page Visibility API
  39700. * ```
  39701. */
  39702. class Timer {
  39703. /**
  39704. * Constructs a new timer.
  39705. */
  39706. constructor() {
  39707. this._previousTime = 0;
  39708. this._currentTime = 0;
  39709. this._startTime = performance.now();
  39710. this._delta = 0;
  39711. this._elapsed = 0;
  39712. this._timescale = 1;
  39713. this._document = null;
  39714. this._pageVisibilityHandler = null;
  39715. }
  39716. /**
  39717. * Connect the timer to the given document.Calling this method is not mandatory to
  39718. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39719. * delta values.
  39720. *
  39721. * @param {Document} document - The document.
  39722. */
  39723. connect( document ) {
  39724. this._document = document;
  39725. // use Page Visibility API to avoid large time delta values
  39726. if ( document.hidden !== undefined ) {
  39727. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39728. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39729. }
  39730. }
  39731. /**
  39732. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39733. */
  39734. disconnect() {
  39735. if ( this._pageVisibilityHandler !== null ) {
  39736. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39737. this._pageVisibilityHandler = null;
  39738. }
  39739. this._document = null;
  39740. }
  39741. /**
  39742. * Returns the time delta in seconds.
  39743. *
  39744. * @return {number} The time delta in second.
  39745. */
  39746. getDelta() {
  39747. return this._delta / 1000;
  39748. }
  39749. /**
  39750. * Returns the elapsed time in seconds.
  39751. *
  39752. * @return {number} The elapsed time in second.
  39753. */
  39754. getElapsed() {
  39755. return this._elapsed / 1000;
  39756. }
  39757. /**
  39758. * Returns the timescale.
  39759. *
  39760. * @return {number} The timescale.
  39761. */
  39762. getTimescale() {
  39763. return this._timescale;
  39764. }
  39765. /**
  39766. * Sets the given timescale which scale the time delta computation
  39767. * in `update()`.
  39768. *
  39769. * @param {number} timescale - The timescale to set.
  39770. * @return {Timer} A reference to this timer.
  39771. */
  39772. setTimescale( timescale ) {
  39773. this._timescale = timescale;
  39774. return this;
  39775. }
  39776. /**
  39777. * Resets the time computation for the current simulation step.
  39778. *
  39779. * @return {Timer} A reference to this timer.
  39780. */
  39781. reset() {
  39782. this._currentTime = performance.now() - this._startTime;
  39783. return this;
  39784. }
  39785. /**
  39786. * Can be used to free all internal resources. Usually called when
  39787. * the timer instance isn't required anymore.
  39788. */
  39789. dispose() {
  39790. this.disconnect();
  39791. }
  39792. /**
  39793. * Updates the internal state of the timer. This method should be called
  39794. * once per simulation step and before you perform queries against the timer
  39795. * (e.g. via `getDelta()`).
  39796. *
  39797. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39798. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39799. * time will be determined with `performance.now`.
  39800. * @return {Timer} A reference to this timer.
  39801. */
  39802. update( timestamp ) {
  39803. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39804. this._delta = 0;
  39805. } else {
  39806. this._previousTime = this._currentTime;
  39807. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39808. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39809. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39810. }
  39811. return this;
  39812. }
  39813. }
  39814. function handleVisibilityChange() {
  39815. if ( this._document.hidden === false ) this.reset();
  39816. }
  39817. /**
  39818. * This class can be used to represent points in 3D space as
  39819. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39820. */
  39821. class Spherical {
  39822. /**
  39823. * Constructs a new spherical.
  39824. *
  39825. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39826. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39827. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39828. */
  39829. constructor( radius = 1, phi = 0, theta = 0 ) {
  39830. /**
  39831. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39832. *
  39833. * @type {number}
  39834. * @default 1
  39835. */
  39836. this.radius = radius;
  39837. /**
  39838. * The polar angle in radians from the y (up) axis.
  39839. *
  39840. * @type {number}
  39841. * @default 0
  39842. */
  39843. this.phi = phi;
  39844. /**
  39845. * The equator/azimuthal angle in radians around the y (up) axis.
  39846. *
  39847. * @type {number}
  39848. * @default 0
  39849. */
  39850. this.theta = theta;
  39851. }
  39852. /**
  39853. * Sets the spherical components by copying the given values.
  39854. *
  39855. * @param {number} radius - The radius.
  39856. * @param {number} phi - The polar angle.
  39857. * @param {number} theta - The azimuthal angle.
  39858. * @return {Spherical} A reference to this spherical.
  39859. */
  39860. set( radius, phi, theta ) {
  39861. this.radius = radius;
  39862. this.phi = phi;
  39863. this.theta = theta;
  39864. return this;
  39865. }
  39866. /**
  39867. * Copies the values of the given spherical to this instance.
  39868. *
  39869. * @param {Spherical} other - The spherical to copy.
  39870. * @return {Spherical} A reference to this spherical.
  39871. */
  39872. copy( other ) {
  39873. this.radius = other.radius;
  39874. this.phi = other.phi;
  39875. this.theta = other.theta;
  39876. return this;
  39877. }
  39878. /**
  39879. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39880. * `0.000001`.
  39881. *
  39882. * @return {Spherical} A reference to this spherical.
  39883. */
  39884. makeSafe() {
  39885. const EPS = 0.000001;
  39886. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39887. return this;
  39888. }
  39889. /**
  39890. * Sets the spherical components from the given vector which is assumed to hold
  39891. * Cartesian coordinates.
  39892. *
  39893. * @param {Vector3} v - The vector to set.
  39894. * @return {Spherical} A reference to this spherical.
  39895. */
  39896. setFromVector3( v ) {
  39897. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39898. }
  39899. /**
  39900. * Sets the spherical components from the given Cartesian coordinates.
  39901. *
  39902. * @param {number} x - The x value.
  39903. * @param {number} y - The y value.
  39904. * @param {number} z - The z value.
  39905. * @return {Spherical} A reference to this spherical.
  39906. */
  39907. setFromCartesianCoords( x, y, z ) {
  39908. this.radius = Math.sqrt( x * x + y * y + z * z );
  39909. if ( this.radius === 0 ) {
  39910. this.theta = 0;
  39911. this.phi = 0;
  39912. } else {
  39913. this.theta = Math.atan2( x, z );
  39914. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39915. }
  39916. return this;
  39917. }
  39918. /**
  39919. * Returns a new spherical with copied values from this instance.
  39920. *
  39921. * @return {Spherical} A clone of this instance.
  39922. */
  39923. clone() {
  39924. return new this.constructor().copy( this );
  39925. }
  39926. }
  39927. /**
  39928. * This class can be used to represent points in 3D space as
  39929. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39930. */
  39931. class Cylindrical {
  39932. /**
  39933. * Constructs a new cylindrical.
  39934. *
  39935. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39936. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39937. * @param {number} [y=0] - The height above the x-z plane.
  39938. */
  39939. constructor( radius = 1, theta = 0, y = 0 ) {
  39940. /**
  39941. * The distance from the origin to a point in the x-z plane.
  39942. *
  39943. * @type {number}
  39944. * @default 1
  39945. */
  39946. this.radius = radius;
  39947. /**
  39948. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39949. *
  39950. * @type {number}
  39951. * @default 0
  39952. */
  39953. this.theta = theta;
  39954. /**
  39955. * The height above the x-z plane.
  39956. *
  39957. * @type {number}
  39958. * @default 0
  39959. */
  39960. this.y = y;
  39961. }
  39962. /**
  39963. * Sets the cylindrical components by copying the given values.
  39964. *
  39965. * @param {number} radius - The radius.
  39966. * @param {number} theta - The theta angle.
  39967. * @param {number} y - The height value.
  39968. * @return {Cylindrical} A reference to this cylindrical.
  39969. */
  39970. set( radius, theta, y ) {
  39971. this.radius = radius;
  39972. this.theta = theta;
  39973. this.y = y;
  39974. return this;
  39975. }
  39976. /**
  39977. * Copies the values of the given cylindrical to this instance.
  39978. *
  39979. * @param {Cylindrical} other - The cylindrical to copy.
  39980. * @return {Cylindrical} A reference to this cylindrical.
  39981. */
  39982. copy( other ) {
  39983. this.radius = other.radius;
  39984. this.theta = other.theta;
  39985. this.y = other.y;
  39986. return this;
  39987. }
  39988. /**
  39989. * Sets the cylindrical components from the given vector which is assumed to hold
  39990. * Cartesian coordinates.
  39991. *
  39992. * @param {Vector3} v - The vector to set.
  39993. * @return {Cylindrical} A reference to this cylindrical.
  39994. */
  39995. setFromVector3( v ) {
  39996. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39997. }
  39998. /**
  39999. * Sets the cylindrical components from the given Cartesian coordinates.
  40000. *
  40001. * @param {number} x - The x value.
  40002. * @param {number} y - The x value.
  40003. * @param {number} z - The x value.
  40004. * @return {Cylindrical} A reference to this cylindrical.
  40005. */
  40006. setFromCartesianCoords( x, y, z ) {
  40007. this.radius = Math.sqrt( x * x + z * z );
  40008. this.theta = Math.atan2( x, z );
  40009. this.y = y;
  40010. return this;
  40011. }
  40012. /**
  40013. * Returns a new cylindrical with copied values from this instance.
  40014. *
  40015. * @return {Cylindrical} A clone of this instance.
  40016. */
  40017. clone() {
  40018. return new this.constructor().copy( this );
  40019. }
  40020. }
  40021. /**
  40022. * Represents a 2x2 matrix.
  40023. *
  40024. * A Note on Row-Major and Column-Major Ordering:
  40025. *
  40026. * The constructor and {@link Matrix2#set} method take arguments in
  40027. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40028. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40029. * This means that calling:
  40030. * ```js
  40031. * const m = new THREE.Matrix2();
  40032. * m.set( 11, 12,
  40033. * 21, 22 );
  40034. * ```
  40035. * will result in the elements array containing:
  40036. * ```js
  40037. * m.elements = [ 11, 21,
  40038. * 12, 22 ];
  40039. * ```
  40040. * and internally all calculations are performed using column-major ordering.
  40041. * However, as the actual ordering makes no difference mathematically and
  40042. * most people are used to thinking about matrices in row-major order, the
  40043. * three.js documentation shows matrices in row-major order. Just bear in
  40044. * mind that if you are reading the source code, you'll have to take the
  40045. * transpose of any matrices outlined here to make sense of the calculations.
  40046. */
  40047. class Matrix2 {
  40048. /**
  40049. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40050. * in row-major order. If no arguments are provided, the constructor
  40051. * initializes the matrix as an identity matrix.
  40052. *
  40053. * @param {number} [n11] - 1-1 matrix element.
  40054. * @param {number} [n12] - 1-2 matrix element.
  40055. * @param {number} [n21] - 2-1 matrix element.
  40056. * @param {number} [n22] - 2-2 matrix element.
  40057. */
  40058. constructor( n11, n12, n21, n22 ) {
  40059. /**
  40060. * This flag can be used for type testing.
  40061. *
  40062. * @type {boolean}
  40063. * @readonly
  40064. * @default true
  40065. */
  40066. Matrix2.prototype.isMatrix2 = true;
  40067. /**
  40068. * A column-major list of matrix values.
  40069. *
  40070. * @type {Array<number>}
  40071. */
  40072. this.elements = [
  40073. 1, 0,
  40074. 0, 1,
  40075. ];
  40076. if ( n11 !== undefined ) {
  40077. this.set( n11, n12, n21, n22 );
  40078. }
  40079. }
  40080. /**
  40081. * Sets this matrix to the 2x2 identity matrix.
  40082. *
  40083. * @return {Matrix2} A reference to this matrix.
  40084. */
  40085. identity() {
  40086. this.set(
  40087. 1, 0,
  40088. 0, 1,
  40089. );
  40090. return this;
  40091. }
  40092. /**
  40093. * Sets the elements of the matrix from the given array.
  40094. *
  40095. * @param {Array<number>} array - The matrix elements in column-major order.
  40096. * @param {number} [offset=0] - Index of the first element in the array.
  40097. * @return {Matrix2} A reference to this matrix.
  40098. */
  40099. fromArray( array, offset = 0 ) {
  40100. for ( let i = 0; i < 4; i ++ ) {
  40101. this.elements[ i ] = array[ i + offset ];
  40102. }
  40103. return this;
  40104. }
  40105. /**
  40106. * Sets the elements of the matrix.The arguments are supposed to be
  40107. * in row-major order.
  40108. *
  40109. * @param {number} n11 - 1-1 matrix element.
  40110. * @param {number} n12 - 1-2 matrix element.
  40111. * @param {number} n21 - 2-1 matrix element.
  40112. * @param {number} n22 - 2-2 matrix element.
  40113. * @return {Matrix2} A reference to this matrix.
  40114. */
  40115. set( n11, n12, n21, n22 ) {
  40116. const te = this.elements;
  40117. te[ 0 ] = n11; te[ 2 ] = n12;
  40118. te[ 1 ] = n21; te[ 3 ] = n22;
  40119. return this;
  40120. }
  40121. }
  40122. const _vector$4 = /*@__PURE__*/ new Vector2();
  40123. /**
  40124. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40125. */
  40126. class Box2 {
  40127. /**
  40128. * Constructs a new bounding box.
  40129. *
  40130. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40131. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40132. */
  40133. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40134. /**
  40135. * This flag can be used for type testing.
  40136. *
  40137. * @type {boolean}
  40138. * @readonly
  40139. * @default true
  40140. */
  40141. this.isBox2 = true;
  40142. /**
  40143. * The lower boundary of the box.
  40144. *
  40145. * @type {Vector2}
  40146. */
  40147. this.min = min;
  40148. /**
  40149. * The upper boundary of the box.
  40150. *
  40151. * @type {Vector2}
  40152. */
  40153. this.max = max;
  40154. }
  40155. /**
  40156. * Sets the lower and upper boundaries of this box.
  40157. * Please note that this method only copies the values from the given objects.
  40158. *
  40159. * @param {Vector2} min - The lower boundary of the box.
  40160. * @param {Vector2} max - The upper boundary of the box.
  40161. * @return {Box2} A reference to this bounding box.
  40162. */
  40163. set( min, max ) {
  40164. this.min.copy( min );
  40165. this.max.copy( max );
  40166. return this;
  40167. }
  40168. /**
  40169. * Sets the upper and lower bounds of this box so it encloses the position data
  40170. * in the given array.
  40171. *
  40172. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40173. * @return {Box2} A reference to this bounding box.
  40174. */
  40175. setFromPoints( points ) {
  40176. this.makeEmpty();
  40177. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40178. this.expandByPoint( points[ i ] );
  40179. }
  40180. return this;
  40181. }
  40182. /**
  40183. * Centers this box on the given center vector and sets this box's width, height and
  40184. * depth to the given size values.
  40185. *
  40186. * @param {Vector2} center - The center of the box.
  40187. * @param {Vector2} size - The x and y dimensions of the box.
  40188. * @return {Box2} A reference to this bounding box.
  40189. */
  40190. setFromCenterAndSize( center, size ) {
  40191. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40192. this.min.copy( center ).sub( halfSize );
  40193. this.max.copy( center ).add( halfSize );
  40194. return this;
  40195. }
  40196. /**
  40197. * Returns a new box with copied values from this instance.
  40198. *
  40199. * @return {Box2} A clone of this instance.
  40200. */
  40201. clone() {
  40202. return new this.constructor().copy( this );
  40203. }
  40204. /**
  40205. * Copies the values of the given box to this instance.
  40206. *
  40207. * @param {Box2} box - The box to copy.
  40208. * @return {Box2} A reference to this bounding box.
  40209. */
  40210. copy( box ) {
  40211. this.min.copy( box.min );
  40212. this.max.copy( box.max );
  40213. return this;
  40214. }
  40215. /**
  40216. * Makes this box empty which means in encloses a zero space in 2D.
  40217. *
  40218. * @return {Box2} A reference to this bounding box.
  40219. */
  40220. makeEmpty() {
  40221. this.min.x = this.min.y = + Infinity;
  40222. this.max.x = this.max.y = - Infinity;
  40223. return this;
  40224. }
  40225. /**
  40226. * Returns true if this box includes zero points within its bounds.
  40227. * Note that a box with equal lower and upper bounds still includes one
  40228. * point, the one both bounds share.
  40229. *
  40230. * @return {boolean} Whether this box is empty or not.
  40231. */
  40232. isEmpty() {
  40233. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40234. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40235. }
  40236. /**
  40237. * Returns the center point of this box.
  40238. *
  40239. * @param {Vector2} target - The target vector that is used to store the method's result.
  40240. * @return {Vector2} The center point.
  40241. */
  40242. getCenter( target ) {
  40243. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40244. }
  40245. /**
  40246. * Returns the dimensions of this box.
  40247. *
  40248. * @param {Vector2} target - The target vector that is used to store the method's result.
  40249. * @return {Vector2} The size.
  40250. */
  40251. getSize( target ) {
  40252. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40253. }
  40254. /**
  40255. * Expands the boundaries of this box to include the given point.
  40256. *
  40257. * @param {Vector2} point - The point that should be included by the bounding box.
  40258. * @return {Box2} A reference to this bounding box.
  40259. */
  40260. expandByPoint( point ) {
  40261. this.min.min( point );
  40262. this.max.max( point );
  40263. return this;
  40264. }
  40265. /**
  40266. * Expands this box equilaterally by the given vector. The width of this
  40267. * box will be expanded by the x component of the vector in both
  40268. * directions. The height of this box will be expanded by the y component of
  40269. * the vector in both directions.
  40270. *
  40271. * @param {Vector2} vector - The vector that should expand the bounding box.
  40272. * @return {Box2} A reference to this bounding box.
  40273. */
  40274. expandByVector( vector ) {
  40275. this.min.sub( vector );
  40276. this.max.add( vector );
  40277. return this;
  40278. }
  40279. /**
  40280. * Expands each dimension of the box by the given scalar. If negative, the
  40281. * dimensions of the box will be contracted.
  40282. *
  40283. * @param {number} scalar - The scalar value that should expand the bounding box.
  40284. * @return {Box2} A reference to this bounding box.
  40285. */
  40286. expandByScalar( scalar ) {
  40287. this.min.addScalar( - scalar );
  40288. this.max.addScalar( scalar );
  40289. return this;
  40290. }
  40291. /**
  40292. * Returns `true` if the given point lies within or on the boundaries of this box.
  40293. *
  40294. * @param {Vector2} point - The point to test.
  40295. * @return {boolean} Whether the bounding box contains the given point or not.
  40296. */
  40297. containsPoint( point ) {
  40298. return point.x >= this.min.x && point.x <= this.max.x &&
  40299. point.y >= this.min.y && point.y <= this.max.y;
  40300. }
  40301. /**
  40302. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40303. * If this box and the given one are identical, this function also returns `true`.
  40304. *
  40305. * @param {Box2} box - The bounding box to test.
  40306. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40307. */
  40308. containsBox( box ) {
  40309. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40310. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40311. }
  40312. /**
  40313. * Returns a point as a proportion of this box's width and height.
  40314. *
  40315. * @param {Vector2} point - A point in 2D space.
  40316. * @param {Vector2} target - The target vector that is used to store the method's result.
  40317. * @return {Vector2} A point as a proportion of this box's width and height.
  40318. */
  40319. getParameter( point, target ) {
  40320. // This can potentially have a divide by zero if the box
  40321. // has a size dimension of 0.
  40322. return target.set(
  40323. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40324. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40325. );
  40326. }
  40327. /**
  40328. * Returns `true` if the given bounding box intersects with this bounding box.
  40329. *
  40330. * @param {Box2} box - The bounding box to test.
  40331. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40332. */
  40333. intersectsBox( box ) {
  40334. // using 4 splitting planes to rule out intersections
  40335. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40336. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40337. }
  40338. /**
  40339. * Clamps the given point within the bounds of this box.
  40340. *
  40341. * @param {Vector2} point - The point to clamp.
  40342. * @param {Vector2} target - The target vector that is used to store the method's result.
  40343. * @return {Vector2} The clamped point.
  40344. */
  40345. clampPoint( point, target ) {
  40346. return target.copy( point ).clamp( this.min, this.max );
  40347. }
  40348. /**
  40349. * Returns the euclidean distance from any edge of this box to the specified point. If
  40350. * the given point lies inside of this box, the distance will be `0`.
  40351. *
  40352. * @param {Vector2} point - The point to compute the distance to.
  40353. * @return {number} The euclidean distance.
  40354. */
  40355. distanceToPoint( point ) {
  40356. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40357. }
  40358. /**
  40359. * Computes the intersection of this bounding box and the given one, setting the upper
  40360. * bound of this box to the lesser of the two boxes' upper bounds and the
  40361. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40362. * there's no overlap, makes this box empty.
  40363. *
  40364. * @param {Box2} box - The bounding box to intersect with.
  40365. * @return {Box2} A reference to this bounding box.
  40366. */
  40367. intersect( box ) {
  40368. this.min.max( box.min );
  40369. this.max.min( box.max );
  40370. if ( this.isEmpty() ) this.makeEmpty();
  40371. return this;
  40372. }
  40373. /**
  40374. * Computes the union of this box and another and the given one, setting the upper
  40375. * bound of this box to the greater of the two boxes' upper bounds and the
  40376. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40377. *
  40378. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40379. * @return {Box2} A reference to this bounding box.
  40380. */
  40381. union( box ) {
  40382. this.min.min( box.min );
  40383. this.max.max( box.max );
  40384. return this;
  40385. }
  40386. /**
  40387. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40388. * effectively moving it in 2D space.
  40389. *
  40390. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40391. * @return {Box2} A reference to this bounding box.
  40392. */
  40393. translate( offset ) {
  40394. this.min.add( offset );
  40395. this.max.add( offset );
  40396. return this;
  40397. }
  40398. /**
  40399. * Returns `true` if this bounding box is equal with the given one.
  40400. *
  40401. * @param {Box2} box - The box to test for equality.
  40402. * @return {boolean} Whether this bounding box is equal with the given one.
  40403. */
  40404. equals( box ) {
  40405. return box.min.equals( this.min ) && box.max.equals( this.max );
  40406. }
  40407. }
  40408. const _startP = /*@__PURE__*/ new Vector3();
  40409. const _startEnd = /*@__PURE__*/ new Vector3();
  40410. const _d1 = /*@__PURE__*/ new Vector3();
  40411. const _d2 = /*@__PURE__*/ new Vector3();
  40412. const _r = /*@__PURE__*/ new Vector3();
  40413. const _c1 = /*@__PURE__*/ new Vector3();
  40414. const _c2 = /*@__PURE__*/ new Vector3();
  40415. /**
  40416. * An analytical line segment in 3D space represented by a start and end point.
  40417. */
  40418. class Line3 {
  40419. /**
  40420. * Constructs a new line segment.
  40421. *
  40422. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40423. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40424. */
  40425. constructor( start = new Vector3(), end = new Vector3() ) {
  40426. /**
  40427. * Start of the line segment.
  40428. *
  40429. * @type {Vector3}
  40430. */
  40431. this.start = start;
  40432. /**
  40433. * End of the line segment.
  40434. *
  40435. * @type {Vector3}
  40436. */
  40437. this.end = end;
  40438. }
  40439. /**
  40440. * Sets the start and end values by copying the given vectors.
  40441. *
  40442. * @param {Vector3} start - The start point.
  40443. * @param {Vector3} end - The end point.
  40444. * @return {Line3} A reference to this line segment.
  40445. */
  40446. set( start, end ) {
  40447. this.start.copy( start );
  40448. this.end.copy( end );
  40449. return this;
  40450. }
  40451. /**
  40452. * Copies the values of the given line segment to this instance.
  40453. *
  40454. * @param {Line3} line - The line segment to copy.
  40455. * @return {Line3} A reference to this line segment.
  40456. */
  40457. copy( line ) {
  40458. this.start.copy( line.start );
  40459. this.end.copy( line.end );
  40460. return this;
  40461. }
  40462. /**
  40463. * Returns the center of the line segment.
  40464. *
  40465. * @param {Vector3} target - The target vector that is used to store the method's result.
  40466. * @return {Vector3} The center point.
  40467. */
  40468. getCenter( target ) {
  40469. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40470. }
  40471. /**
  40472. * Returns the delta vector of the line segment's start and end point.
  40473. *
  40474. * @param {Vector3} target - The target vector that is used to store the method's result.
  40475. * @return {Vector3} The delta vector.
  40476. */
  40477. delta( target ) {
  40478. return target.subVectors( this.end, this.start );
  40479. }
  40480. /**
  40481. * Returns the squared Euclidean distance between the line' start and end point.
  40482. *
  40483. * @return {number} The squared Euclidean distance.
  40484. */
  40485. distanceSq() {
  40486. return this.start.distanceToSquared( this.end );
  40487. }
  40488. /**
  40489. * Returns the Euclidean distance between the line' start and end point.
  40490. *
  40491. * @return {number} The Euclidean distance.
  40492. */
  40493. distance() {
  40494. return this.start.distanceTo( this.end );
  40495. }
  40496. /**
  40497. * Returns a vector at a certain position along the line segment.
  40498. *
  40499. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40500. * @param {Vector3} target - The target vector that is used to store the method's result.
  40501. * @return {Vector3} The delta vector.
  40502. */
  40503. at( t, target ) {
  40504. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40505. }
  40506. /**
  40507. * Returns a point parameter based on the closest point as projected on the line segment.
  40508. *
  40509. * @param {Vector3} point - The point for which to return a point parameter.
  40510. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40511. * @return {number} The point parameter.
  40512. */
  40513. closestPointToPointParameter( point, clampToLine ) {
  40514. _startP.subVectors( point, this.start );
  40515. _startEnd.subVectors( this.end, this.start );
  40516. const startEnd2 = _startEnd.dot( _startEnd );
  40517. const startEnd_startP = _startEnd.dot( _startP );
  40518. let t = startEnd_startP / startEnd2;
  40519. if ( clampToLine ) {
  40520. t = clamp( t, 0, 1 );
  40521. }
  40522. return t;
  40523. }
  40524. /**
  40525. * Returns the closest point on the line for a given point.
  40526. *
  40527. * @param {Vector3} point - The point to compute the closest point on the line for.
  40528. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40529. * @param {Vector3} target - The target vector that is used to store the method's result.
  40530. * @return {Vector3} The closest point on the line.
  40531. */
  40532. closestPointToPoint( point, clampToLine, target ) {
  40533. const t = this.closestPointToPointParameter( point, clampToLine );
  40534. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40535. }
  40536. /**
  40537. * Returns the closest squared distance between this line segment and the given one.
  40538. *
  40539. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40540. * @param {Vector3} [c1] - The closest point on this line segment.
  40541. * @param {Vector3} [c2] - The closest point on the given line segment.
  40542. * @return {number} The squared distance between this line segment and the given one.
  40543. */
  40544. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40545. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40546. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40547. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40548. // distance between between S1(s) and S2(t)
  40549. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40550. let s, t;
  40551. const p1 = this.start;
  40552. const p2 = line.start;
  40553. const q1 = this.end;
  40554. const q2 = line.end;
  40555. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40556. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40557. _r.subVectors( p1, p2 );
  40558. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40559. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40560. const f = _d2.dot( _r );
  40561. // Check if either or both segments degenerate into points
  40562. if ( a <= EPSILON && e <= EPSILON ) {
  40563. // Both segments degenerate into points
  40564. c1.copy( p1 );
  40565. c2.copy( p2 );
  40566. c1.sub( c2 );
  40567. return c1.dot( c1 );
  40568. }
  40569. if ( a <= EPSILON ) {
  40570. // First segment degenerates into a point
  40571. s = 0;
  40572. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40573. t = clamp( t, 0, 1 );
  40574. } else {
  40575. const c = _d1.dot( _r );
  40576. if ( e <= EPSILON ) {
  40577. // Second segment degenerates into a point
  40578. t = 0;
  40579. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40580. } else {
  40581. // The general nondegenerate case starts here
  40582. const b = _d1.dot( _d2 );
  40583. const denom = a * e - b * b; // Always nonnegative
  40584. // If segments not parallel, compute closest point on L1 to L2 and
  40585. // clamp to segment S1. Else pick arbitrary s (here 0)
  40586. if ( denom !== 0 ) {
  40587. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40588. } else {
  40589. s = 0;
  40590. }
  40591. // Compute point on L2 closest to S1(s) using
  40592. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40593. t = ( b * s + f ) / e;
  40594. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40595. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40596. // and clamp s to [0, 1]
  40597. if ( t < 0 ) {
  40598. t = 0.;
  40599. s = clamp( - c / a, 0, 1 );
  40600. } else if ( t > 1 ) {
  40601. t = 1;
  40602. s = clamp( ( b - c ) / a, 0, 1 );
  40603. }
  40604. }
  40605. }
  40606. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40607. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40608. c1.sub( c2 );
  40609. return c1.dot( c1 );
  40610. }
  40611. /**
  40612. * Applies a 4x4 transformation matrix to this line segment.
  40613. *
  40614. * @param {Matrix4} matrix - The transformation matrix.
  40615. * @return {Line3} A reference to this line segment.
  40616. */
  40617. applyMatrix4( matrix ) {
  40618. this.start.applyMatrix4( matrix );
  40619. this.end.applyMatrix4( matrix );
  40620. return this;
  40621. }
  40622. /**
  40623. * Returns `true` if this line segment is equal with the given one.
  40624. *
  40625. * @param {Line3} line - The line segment to test for equality.
  40626. * @return {boolean} Whether this line segment is equal with the given one.
  40627. */
  40628. equals( line ) {
  40629. return line.start.equals( this.start ) && line.end.equals( this.end );
  40630. }
  40631. /**
  40632. * Returns a new line segment with copied values from this instance.
  40633. *
  40634. * @return {Line3} A clone of this instance.
  40635. */
  40636. clone() {
  40637. return new this.constructor().copy( this );
  40638. }
  40639. }
  40640. const _vector$3 = /*@__PURE__*/ new Vector3();
  40641. /**
  40642. * This displays a cone shaped helper object for a {@link SpotLight}.
  40643. *
  40644. * ```js
  40645. * const spotLight = new THREE.SpotLight( 0xffffff );
  40646. * spotLight.position.set( 10, 10, 10 );
  40647. * scene.add( spotLight );
  40648. *
  40649. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40650. * scene.add( spotLightHelper );
  40651. * ```
  40652. *
  40653. * @augments Object3D
  40654. */
  40655. class SpotLightHelper extends Object3D {
  40656. /**
  40657. * Constructs a new spot light helper.
  40658. *
  40659. * @param {HemisphereLight} light - The light to be visualized.
  40660. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40661. * the color of the light.
  40662. */
  40663. constructor( light, color ) {
  40664. super();
  40665. /**
  40666. * The light being visualized.
  40667. *
  40668. * @type {SpotLight}
  40669. */
  40670. this.light = light;
  40671. this.matrixAutoUpdate = false;
  40672. /**
  40673. * The color parameter passed in the constructor.
  40674. * If not set, the helper will take the color of the light.
  40675. *
  40676. * @type {number|Color|string}
  40677. */
  40678. this.color = color;
  40679. this.type = 'SpotLightHelper';
  40680. const geometry = new BufferGeometry();
  40681. const positions = [
  40682. 0, 0, 0, 0, 0, 1,
  40683. 0, 0, 0, 1, 0, 1,
  40684. 0, 0, 0, -1, 0, 1,
  40685. 0, 0, 0, 0, 1, 1,
  40686. 0, 0, 0, 0, -1, 1
  40687. ];
  40688. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40689. const p1 = ( i / l ) * Math.PI * 2;
  40690. const p2 = ( j / l ) * Math.PI * 2;
  40691. positions.push(
  40692. Math.cos( p1 ), Math.sin( p1 ), 1,
  40693. Math.cos( p2 ), Math.sin( p2 ), 1
  40694. );
  40695. }
  40696. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40697. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40698. this.cone = new LineSegments( geometry, material );
  40699. this.add( this.cone );
  40700. this.update();
  40701. }
  40702. /**
  40703. * Frees the GPU-related resources allocated by this instance. Call this
  40704. * method whenever this instance is no longer used in your app.
  40705. */
  40706. dispose() {
  40707. this.cone.geometry.dispose();
  40708. this.cone.material.dispose();
  40709. }
  40710. /**
  40711. * Updates the helper to match the position and direction of the
  40712. * light being visualized.
  40713. */
  40714. update() {
  40715. this.light.updateWorldMatrix( true, false );
  40716. this.light.target.updateWorldMatrix( true, false );
  40717. // update the local matrix based on the parent and light target transforms
  40718. if ( this.parent ) {
  40719. this.parent.updateWorldMatrix( true );
  40720. this.matrix
  40721. .copy( this.parent.matrixWorld )
  40722. .invert()
  40723. .multiply( this.light.matrixWorld );
  40724. } else {
  40725. this.matrix.copy( this.light.matrixWorld );
  40726. }
  40727. this.matrixWorld.copy( this.light.matrixWorld );
  40728. const coneLength = this.light.distance ? this.light.distance : 1000;
  40729. const coneWidth = coneLength * Math.tan( this.light.angle );
  40730. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40731. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40732. this.cone.lookAt( _vector$3 );
  40733. if ( this.color !== undefined ) {
  40734. this.cone.material.color.set( this.color );
  40735. } else {
  40736. this.cone.material.color.copy( this.light.color );
  40737. }
  40738. }
  40739. }
  40740. const _vector$2 = /*@__PURE__*/ new Vector3();
  40741. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40742. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40743. /**
  40744. * A helper object to assist with visualizing a {@link Skeleton}.
  40745. *
  40746. * ```js
  40747. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40748. * scene.add( helper );
  40749. * ```
  40750. *
  40751. * @augments LineSegments
  40752. */
  40753. class SkeletonHelper extends LineSegments {
  40754. /**
  40755. * Constructs a new skeleton helper.
  40756. *
  40757. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40758. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40759. */
  40760. constructor( object ) {
  40761. const bones = getBoneList( object );
  40762. const geometry = new BufferGeometry();
  40763. const vertices = [];
  40764. const colors = [];
  40765. for ( let i = 0; i < bones.length; i ++ ) {
  40766. const bone = bones[ i ];
  40767. if ( bone.parent && bone.parent.isBone ) {
  40768. vertices.push( 0, 0, 0 );
  40769. vertices.push( 0, 0, 0 );
  40770. colors.push( 0, 0, 0 );
  40771. colors.push( 0, 0, 0 );
  40772. }
  40773. }
  40774. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40775. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40776. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40777. super( geometry, material );
  40778. /**
  40779. * This flag can be used for type testing.
  40780. *
  40781. * @type {boolean}
  40782. * @readonly
  40783. * @default true
  40784. */
  40785. this.isSkeletonHelper = true;
  40786. this.type = 'SkeletonHelper';
  40787. /**
  40788. * The object being visualized.
  40789. *
  40790. * @type {Object3D}
  40791. */
  40792. this.root = object;
  40793. /**
  40794. * The list of bones that the helper visualizes.
  40795. *
  40796. * @type {Array<Bone>}
  40797. */
  40798. this.bones = bones;
  40799. this.matrix = object.matrixWorld;
  40800. this.matrixAutoUpdate = false;
  40801. // colors
  40802. const color1 = new Color( 0x0000ff );
  40803. const color2 = new Color( 0x00ff00 );
  40804. this.setColors( color1, color2 );
  40805. }
  40806. updateMatrixWorld( force ) {
  40807. const bones = this.bones;
  40808. const geometry = this.geometry;
  40809. const position = geometry.getAttribute( 'position' );
  40810. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40811. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40812. const bone = bones[ i ];
  40813. if ( bone.parent && bone.parent.isBone ) {
  40814. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40815. _vector$2.setFromMatrixPosition( _boneMatrix );
  40816. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40817. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40818. _vector$2.setFromMatrixPosition( _boneMatrix );
  40819. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40820. j += 2;
  40821. }
  40822. }
  40823. geometry.getAttribute( 'position' ).needsUpdate = true;
  40824. super.updateMatrixWorld( force );
  40825. }
  40826. /**
  40827. * Defines the colors of the helper.
  40828. *
  40829. * @param {Color} color1 - The first line color for each bone.
  40830. * @param {Color} color2 - The second line color for each bone.
  40831. * @return {SkeletonHelper} A reference to this helper.
  40832. */
  40833. setColors( color1, color2 ) {
  40834. const geometry = this.geometry;
  40835. const colorAttribute = geometry.getAttribute( 'color' );
  40836. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40837. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40838. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40839. }
  40840. colorAttribute.needsUpdate = true;
  40841. return this;
  40842. }
  40843. /**
  40844. * Frees the GPU-related resources allocated by this instance. Call this
  40845. * method whenever this instance is no longer used in your app.
  40846. */
  40847. dispose() {
  40848. this.geometry.dispose();
  40849. this.material.dispose();
  40850. }
  40851. }
  40852. function getBoneList( object ) {
  40853. const boneList = [];
  40854. if ( object.isBone === true ) {
  40855. boneList.push( object );
  40856. }
  40857. for ( let i = 0; i < object.children.length; i ++ ) {
  40858. boneList.push( ...getBoneList( object.children[ i ] ) );
  40859. }
  40860. return boneList;
  40861. }
  40862. /**
  40863. * This displays a helper object consisting of a spherical mesh for
  40864. * visualizing an instance of {@link PointLight}.
  40865. *
  40866. * ```js
  40867. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40868. * pointLight.position.set( 10, 10, 10 );
  40869. * scene.add( pointLight );
  40870. *
  40871. * const sphereSize = 1;
  40872. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40873. * scene.add( pointLightHelper );
  40874. * ```
  40875. *
  40876. * @augments Mesh
  40877. */
  40878. class PointLightHelper extends Mesh {
  40879. /**
  40880. * Constructs a new point light helper.
  40881. *
  40882. * @param {PointLight} light - The light to be visualized.
  40883. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40884. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40885. * the color of the light.
  40886. */
  40887. constructor( light, sphereSize, color ) {
  40888. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40889. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40890. super( geometry, material );
  40891. /**
  40892. * The light being visualized.
  40893. *
  40894. * @type {HemisphereLight}
  40895. */
  40896. this.light = light;
  40897. /**
  40898. * The color parameter passed in the constructor.
  40899. * If not set, the helper will take the color of the light.
  40900. *
  40901. * @type {number|Color|string}
  40902. */
  40903. this.color = color;
  40904. this.type = 'PointLightHelper';
  40905. this.matrix = this.light.matrixWorld;
  40906. this.matrixAutoUpdate = false;
  40907. this.update();
  40908. /*
  40909. // TODO: delete this comment?
  40910. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40911. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40912. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40913. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40914. const d = light.distance;
  40915. if ( d === 0.0 ) {
  40916. this.lightDistance.visible = false;
  40917. } else {
  40918. this.lightDistance.scale.set( d, d, d );
  40919. }
  40920. this.add( this.lightDistance );
  40921. */
  40922. }
  40923. /**
  40924. * Frees the GPU-related resources allocated by this instance. Call this
  40925. * method whenever this instance is no longer used in your app.
  40926. */
  40927. dispose() {
  40928. this.geometry.dispose();
  40929. this.material.dispose();
  40930. }
  40931. /**
  40932. * Updates the helper to match the position of the
  40933. * light being visualized.
  40934. */
  40935. update() {
  40936. this.light.updateWorldMatrix( true, false );
  40937. if ( this.color !== undefined ) {
  40938. this.material.color.set( this.color );
  40939. } else {
  40940. this.material.color.copy( this.light.color );
  40941. }
  40942. /*
  40943. const d = this.light.distance;
  40944. if ( d === 0.0 ) {
  40945. this.lightDistance.visible = false;
  40946. } else {
  40947. this.lightDistance.visible = true;
  40948. this.lightDistance.scale.set( d, d, d );
  40949. }
  40950. */
  40951. }
  40952. }
  40953. const _vector$1 = /*@__PURE__*/ new Vector3();
  40954. const _color1 = /*@__PURE__*/ new Color();
  40955. const _color2 = /*@__PURE__*/ new Color();
  40956. /**
  40957. * Creates a visual aid consisting of a spherical mesh for a
  40958. * given {@link HemisphereLight}.
  40959. *
  40960. * ```js
  40961. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40962. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40963. * scene.add( helper );
  40964. * ```
  40965. *
  40966. * @augments Object3D
  40967. */
  40968. class HemisphereLightHelper extends Object3D {
  40969. /**
  40970. * Constructs a new hemisphere light helper.
  40971. *
  40972. * @param {HemisphereLight} light - The light to be visualized.
  40973. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40974. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40975. * the color of the light.
  40976. */
  40977. constructor( light, size, color ) {
  40978. super();
  40979. /**
  40980. * The light being visualized.
  40981. *
  40982. * @type {HemisphereLight}
  40983. */
  40984. this.light = light;
  40985. this.matrix = light.matrixWorld;
  40986. this.matrixAutoUpdate = false;
  40987. /**
  40988. * The color parameter passed in the constructor.
  40989. * If not set, the helper will take the color of the light.
  40990. *
  40991. * @type {number|Color|string}
  40992. */
  40993. this.color = color;
  40994. this.type = 'HemisphereLightHelper';
  40995. const geometry = new OctahedronGeometry( size );
  40996. geometry.rotateY( Math.PI * 0.5 );
  40997. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40998. if ( this.color === undefined ) this.material.vertexColors = true;
  40999. const position = geometry.getAttribute( 'position' );
  41000. const colors = new Float32Array( position.count * 3 );
  41001. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41002. this.add( new Mesh( geometry, this.material ) );
  41003. this.update();
  41004. }
  41005. /**
  41006. * Frees the GPU-related resources allocated by this instance. Call this
  41007. * method whenever this instance is no longer used in your app.
  41008. */
  41009. dispose() {
  41010. this.children[ 0 ].geometry.dispose();
  41011. this.children[ 0 ].material.dispose();
  41012. }
  41013. /**
  41014. * Updates the helper to match the position and direction of the
  41015. * light being visualized.
  41016. */
  41017. update() {
  41018. const mesh = this.children[ 0 ];
  41019. if ( this.color !== undefined ) {
  41020. this.material.color.set( this.color );
  41021. } else {
  41022. const colors = mesh.geometry.getAttribute( 'color' );
  41023. _color1.copy( this.light.color );
  41024. _color2.copy( this.light.groundColor );
  41025. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41026. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41027. colors.setXYZ( i, color.r, color.g, color.b );
  41028. }
  41029. colors.needsUpdate = true;
  41030. }
  41031. this.light.updateWorldMatrix( true, false );
  41032. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41033. }
  41034. }
  41035. /**
  41036. * The helper is an object to define grids. Grids are two-dimensional
  41037. * arrays of lines.
  41038. *
  41039. * ```js
  41040. * const size = 10;
  41041. * const divisions = 10;
  41042. *
  41043. * const gridHelper = new THREE.GridHelper( size, divisions );
  41044. * scene.add( gridHelper );
  41045. * ```
  41046. *
  41047. * @augments LineSegments
  41048. */
  41049. class GridHelper extends LineSegments {
  41050. /**
  41051. * Constructs a new grid helper.
  41052. *
  41053. * @param {number} [size=10] - The size of the grid.
  41054. * @param {number} [divisions=10] - The number of divisions across the grid.
  41055. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41056. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41057. */
  41058. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41059. color1 = new Color( color1 );
  41060. color2 = new Color( color2 );
  41061. const center = divisions / 2;
  41062. const step = size / divisions;
  41063. const halfSize = size / 2;
  41064. const vertices = [], colors = [];
  41065. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41066. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41067. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41068. const color = i === center ? color1 : color2;
  41069. color.toArray( colors, j ); j += 3;
  41070. color.toArray( colors, j ); j += 3;
  41071. color.toArray( colors, j ); j += 3;
  41072. color.toArray( colors, j ); j += 3;
  41073. }
  41074. const geometry = new BufferGeometry();
  41075. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41076. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41077. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41078. super( geometry, material );
  41079. this.type = 'GridHelper';
  41080. }
  41081. /**
  41082. * Frees the GPU-related resources allocated by this instance. Call this
  41083. * method whenever this instance is no longer used in your app.
  41084. */
  41085. dispose() {
  41086. this.geometry.dispose();
  41087. this.material.dispose();
  41088. }
  41089. }
  41090. /**
  41091. * This helper is an object to define polar grids. Grids are
  41092. * two-dimensional arrays of lines.
  41093. *
  41094. * ```js
  41095. * const radius = 10;
  41096. * const sectors = 16;
  41097. * const rings = 8;
  41098. * const divisions = 64;
  41099. *
  41100. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41101. * scene.add( helper );
  41102. * ```
  41103. *
  41104. * @augments LineSegments
  41105. */
  41106. class PolarGridHelper extends LineSegments {
  41107. /**
  41108. * Constructs a new polar grid helper.
  41109. *
  41110. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41111. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41112. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41113. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41114. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41115. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41116. */
  41117. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41118. color1 = new Color( color1 );
  41119. color2 = new Color( color2 );
  41120. const vertices = [];
  41121. const colors = [];
  41122. // create the sectors
  41123. if ( sectors > 1 ) {
  41124. for ( let i = 0; i < sectors; i ++ ) {
  41125. const v = ( i / sectors ) * ( Math.PI * 2 );
  41126. const x = Math.sin( v ) * radius;
  41127. const z = Math.cos( v ) * radius;
  41128. vertices.push( 0, 0, 0 );
  41129. vertices.push( x, 0, z );
  41130. const color = ( i & 1 ) ? color1 : color2;
  41131. colors.push( color.r, color.g, color.b );
  41132. colors.push( color.r, color.g, color.b );
  41133. }
  41134. }
  41135. // create the rings
  41136. for ( let i = 0; i < rings; i ++ ) {
  41137. const color = ( i & 1 ) ? color1 : color2;
  41138. const r = radius - ( radius / rings * i );
  41139. for ( let j = 0; j < divisions; j ++ ) {
  41140. // first vertex
  41141. let v = ( j / divisions ) * ( Math.PI * 2 );
  41142. let x = Math.sin( v ) * r;
  41143. let z = Math.cos( v ) * r;
  41144. vertices.push( x, 0, z );
  41145. colors.push( color.r, color.g, color.b );
  41146. // second vertex
  41147. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41148. x = Math.sin( v ) * r;
  41149. z = Math.cos( v ) * r;
  41150. vertices.push( x, 0, z );
  41151. colors.push( color.r, color.g, color.b );
  41152. }
  41153. }
  41154. const geometry = new BufferGeometry();
  41155. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41156. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41157. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41158. super( geometry, material );
  41159. this.type = 'PolarGridHelper';
  41160. }
  41161. /**
  41162. * Frees the GPU-related resources allocated by this instance. Call this
  41163. * method whenever this instance is no longer used in your app.
  41164. */
  41165. dispose() {
  41166. this.geometry.dispose();
  41167. this.material.dispose();
  41168. }
  41169. }
  41170. const _v1 = /*@__PURE__*/ new Vector3();
  41171. const _v2 = /*@__PURE__*/ new Vector3();
  41172. const _v3 = /*@__PURE__*/ new Vector3();
  41173. /**
  41174. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41175. * effect on the scene. This consists of plane and a line representing the
  41176. * light's position and direction.
  41177. *
  41178. * ```js
  41179. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41180. * scene.add( light );
  41181. *
  41182. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41183. * scene.add( helper );
  41184. * ```
  41185. *
  41186. * @augments Object3D
  41187. */
  41188. class DirectionalLightHelper extends Object3D {
  41189. /**
  41190. * Constructs a new directional light helper.
  41191. *
  41192. * @param {DirectionalLight} light - The light to be visualized.
  41193. * @param {number} [size=1] - The dimensions of the plane.
  41194. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41195. * the color of the light.
  41196. */
  41197. constructor( light, size, color ) {
  41198. super();
  41199. /**
  41200. * The light being visualized.
  41201. *
  41202. * @type {DirectionalLight}
  41203. */
  41204. this.light = light;
  41205. this.matrix = light.matrixWorld;
  41206. this.matrixAutoUpdate = false;
  41207. /**
  41208. * The color parameter passed in the constructor.
  41209. * If not set, the helper will take the color of the light.
  41210. *
  41211. * @type {number|Color|string}
  41212. */
  41213. this.color = color;
  41214. this.type = 'DirectionalLightHelper';
  41215. if ( size === undefined ) size = 1;
  41216. let geometry = new BufferGeometry();
  41217. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41218. - size, size, 0,
  41219. size, size, 0,
  41220. size, - size, 0,
  41221. - size, - size, 0,
  41222. - size, size, 0
  41223. ], 3 ) );
  41224. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41225. /**
  41226. * Contains the line showing the location of the directional light.
  41227. *
  41228. * @type {Line}
  41229. */
  41230. this.lightPlane = new Line( geometry, material );
  41231. this.add( this.lightPlane );
  41232. geometry = new BufferGeometry();
  41233. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41234. /**
  41235. * Represents the target line of the directional light.
  41236. *
  41237. * @type {Line}
  41238. */
  41239. this.targetLine = new Line( geometry, material );
  41240. this.add( this.targetLine );
  41241. this.update();
  41242. }
  41243. /**
  41244. * Frees the GPU-related resources allocated by this instance. Call this
  41245. * method whenever this instance is no longer used in your app.
  41246. */
  41247. dispose() {
  41248. this.lightPlane.geometry.dispose();
  41249. this.lightPlane.material.dispose();
  41250. this.targetLine.geometry.dispose();
  41251. this.targetLine.material.dispose();
  41252. }
  41253. /**
  41254. * Updates the helper to match the position and direction of the
  41255. * light being visualized.
  41256. */
  41257. update() {
  41258. this.light.updateWorldMatrix( true, false );
  41259. this.light.target.updateWorldMatrix( true, false );
  41260. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41261. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41262. _v3.subVectors( _v2, _v1 );
  41263. this.lightPlane.lookAt( _v2 );
  41264. if ( this.color !== undefined ) {
  41265. this.lightPlane.material.color.set( this.color );
  41266. this.targetLine.material.color.set( this.color );
  41267. } else {
  41268. this.lightPlane.material.color.copy( this.light.color );
  41269. this.targetLine.material.color.copy( this.light.color );
  41270. }
  41271. this.targetLine.lookAt( _v2 );
  41272. this.targetLine.scale.z = _v3.length();
  41273. }
  41274. }
  41275. const _vector = /*@__PURE__*/ new Vector3();
  41276. const _camera = /*@__PURE__*/ new Camera();
  41277. /**
  41278. * This helps with visualizing what a camera contains in its frustum. It
  41279. * visualizes the frustum of a camera using a line segments.
  41280. *
  41281. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41282. *
  41283. * `CameraHelper` must be a child of the scene.
  41284. *
  41285. * ```js
  41286. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41287. * const helper = new THREE.CameraHelper( camera );
  41288. * scene.add( helper );
  41289. * ```
  41290. *
  41291. * @augments LineSegments
  41292. */
  41293. class CameraHelper extends LineSegments {
  41294. /**
  41295. * Constructs a new arrow helper.
  41296. *
  41297. * @param {Camera} camera - The camera to visualize.
  41298. */
  41299. constructor( camera ) {
  41300. const geometry = new BufferGeometry();
  41301. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41302. const vertices = [];
  41303. const colors = [];
  41304. const pointMap = {};
  41305. // near
  41306. addLine( 'n1', 'n2' );
  41307. addLine( 'n2', 'n4' );
  41308. addLine( 'n4', 'n3' );
  41309. addLine( 'n3', 'n1' );
  41310. // far
  41311. addLine( 'f1', 'f2' );
  41312. addLine( 'f2', 'f4' );
  41313. addLine( 'f4', 'f3' );
  41314. addLine( 'f3', 'f1' );
  41315. // sides
  41316. addLine( 'n1', 'f1' );
  41317. addLine( 'n2', 'f2' );
  41318. addLine( 'n3', 'f3' );
  41319. addLine( 'n4', 'f4' );
  41320. // cone
  41321. addLine( 'p', 'n1' );
  41322. addLine( 'p', 'n2' );
  41323. addLine( 'p', 'n3' );
  41324. addLine( 'p', 'n4' );
  41325. // up
  41326. addLine( 'u1', 'u2' );
  41327. addLine( 'u2', 'u3' );
  41328. addLine( 'u3', 'u1' );
  41329. // target
  41330. addLine( 'c', 't' );
  41331. addLine( 'p', 'c' );
  41332. // cross
  41333. addLine( 'cn1', 'cn2' );
  41334. addLine( 'cn3', 'cn4' );
  41335. addLine( 'cf1', 'cf2' );
  41336. addLine( 'cf3', 'cf4' );
  41337. function addLine( a, b ) {
  41338. addPoint( a );
  41339. addPoint( b );
  41340. }
  41341. function addPoint( id ) {
  41342. vertices.push( 0, 0, 0 );
  41343. colors.push( 0, 0, 0 );
  41344. if ( pointMap[ id ] === undefined ) {
  41345. pointMap[ id ] = [];
  41346. }
  41347. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41348. }
  41349. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41350. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41351. super( geometry, material );
  41352. this.type = 'CameraHelper';
  41353. /**
  41354. * The camera being visualized.
  41355. *
  41356. * @type {Camera}
  41357. */
  41358. this.camera = camera;
  41359. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41360. this.matrix = camera.matrixWorld;
  41361. this.matrixAutoUpdate = false;
  41362. /**
  41363. * This contains the points used to visualize the camera.
  41364. *
  41365. * @type {Object<string,Array<number>>}
  41366. */
  41367. this.pointMap = pointMap;
  41368. this.update();
  41369. // colors
  41370. const colorFrustum = new Color( 0xffaa00 );
  41371. const colorCone = new Color( 0xff0000 );
  41372. const colorUp = new Color( 0x00aaff );
  41373. const colorTarget = new Color( 0xffffff );
  41374. const colorCross = new Color( 0x333333 );
  41375. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41376. }
  41377. /**
  41378. * Defines the colors of the helper.
  41379. *
  41380. * @param {Color} frustum - The frustum line color.
  41381. * @param {Color} cone - The cone line color.
  41382. * @param {Color} up - The up line color.
  41383. * @param {Color} target - The target line color.
  41384. * @param {Color} cross - The cross line color.
  41385. * @return {CameraHelper} A reference to this helper.
  41386. */
  41387. setColors( frustum, cone, up, target, cross ) {
  41388. const geometry = this.geometry;
  41389. const colorAttribute = geometry.getAttribute( 'color' );
  41390. // near
  41391. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41392. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41393. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41394. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41395. // far
  41396. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41397. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41398. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41399. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41400. // sides
  41401. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41402. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41403. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41404. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41405. // cone
  41406. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41407. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41408. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41409. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41410. // up
  41411. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41412. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41413. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41414. // target
  41415. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41416. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41417. // cross
  41418. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41419. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41420. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41421. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41422. colorAttribute.needsUpdate = true;
  41423. return this;
  41424. }
  41425. /**
  41426. * Updates the helper based on the projection matrix of the camera.
  41427. */
  41428. update() {
  41429. const geometry = this.geometry;
  41430. const pointMap = this.pointMap;
  41431. const w = 1, h = 1;
  41432. let nearZ, farZ;
  41433. // we need just camera projection matrix inverse
  41434. // world matrix must be identity
  41435. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41436. // Adjust z values based on coordinate system
  41437. if ( this.camera.reversedDepth === true ) {
  41438. nearZ = 1;
  41439. farZ = 0;
  41440. } else {
  41441. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41442. nearZ = -1;
  41443. farZ = 1;
  41444. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41445. nearZ = 0;
  41446. farZ = 1;
  41447. } else {
  41448. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41449. }
  41450. }
  41451. // center / target
  41452. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41453. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41454. // near
  41455. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41456. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41457. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41458. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41459. // far
  41460. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41461. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41462. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41463. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41464. // up
  41465. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41466. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41467. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41468. // cross
  41469. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41470. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41471. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41472. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41473. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41474. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41475. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41476. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41477. geometry.getAttribute( 'position' ).needsUpdate = true;
  41478. }
  41479. /**
  41480. * Frees the GPU-related resources allocated by this instance. Call this
  41481. * method whenever this instance is no longer used in your app.
  41482. */
  41483. dispose() {
  41484. this.geometry.dispose();
  41485. this.material.dispose();
  41486. }
  41487. }
  41488. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41489. _vector.set( x, y, z ).unproject( camera );
  41490. const points = pointMap[ point ];
  41491. if ( points !== undefined ) {
  41492. const position = geometry.getAttribute( 'position' );
  41493. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41494. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41495. }
  41496. }
  41497. }
  41498. const _box = /*@__PURE__*/ new Box3();
  41499. /**
  41500. * Helper object to graphically show the world-axis-aligned bounding box
  41501. * around an object. The actual bounding box is handled with {@link Box3},
  41502. * this is just a visual helper for debugging. It can be automatically
  41503. * resized with {@link BoxHelper#update} when the object it's created from
  41504. * is transformed. Note that the object must have a geometry for this to work,
  41505. * so it won't work with sprites.
  41506. *
  41507. * ```js
  41508. * const sphere = new THREE.SphereGeometry();
  41509. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41510. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41511. * scene.add( box );
  41512. * ```
  41513. *
  41514. * @augments LineSegments
  41515. */
  41516. class BoxHelper extends LineSegments {
  41517. /**
  41518. * Constructs a new box helper.
  41519. *
  41520. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41521. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41522. */
  41523. constructor( object, color = 0xffff00 ) {
  41524. 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 ] );
  41525. const positions = new Float32Array( 8 * 3 );
  41526. const geometry = new BufferGeometry();
  41527. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41528. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41529. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41530. /**
  41531. * The 3D object being visualized.
  41532. *
  41533. * @type {Object3D}
  41534. */
  41535. this.object = object;
  41536. this.type = 'BoxHelper';
  41537. this.matrixAutoUpdate = false;
  41538. this.update();
  41539. }
  41540. /**
  41541. * Updates the helper's geometry to match the dimensions of the object,
  41542. * including any children.
  41543. */
  41544. update() {
  41545. if ( this.object !== undefined ) {
  41546. _box.setFromObject( this.object );
  41547. }
  41548. if ( _box.isEmpty() ) return;
  41549. const min = _box.min;
  41550. const max = _box.max;
  41551. /*
  41552. 5____4
  41553. 1/___0/|
  41554. | 6__|_7
  41555. 2/___3/
  41556. 0: max.x, max.y, max.z
  41557. 1: min.x, max.y, max.z
  41558. 2: min.x, min.y, max.z
  41559. 3: max.x, min.y, max.z
  41560. 4: max.x, max.y, min.z
  41561. 5: min.x, max.y, min.z
  41562. 6: min.x, min.y, min.z
  41563. 7: max.x, min.y, min.z
  41564. */
  41565. const position = this.geometry.attributes.position;
  41566. const array = position.array;
  41567. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41568. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41569. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41570. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41571. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41572. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41573. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41574. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41575. position.needsUpdate = true;
  41576. this.geometry.computeBoundingSphere();
  41577. }
  41578. /**
  41579. * Updates the wireframe box for the passed object.
  41580. *
  41581. * @param {Object3D} object - The 3D object to create the helper for.
  41582. * @return {BoxHelper} A reference to this instance.
  41583. */
  41584. setFromObject( object ) {
  41585. this.object = object;
  41586. this.update();
  41587. return this;
  41588. }
  41589. copy( source, recursive ) {
  41590. super.copy( source, recursive );
  41591. this.object = source.object;
  41592. return this;
  41593. }
  41594. /**
  41595. * Frees the GPU-related resources allocated by this instance. Call this
  41596. * method whenever this instance is no longer used in your app.
  41597. */
  41598. dispose() {
  41599. this.geometry.dispose();
  41600. this.material.dispose();
  41601. }
  41602. }
  41603. /**
  41604. * A helper object to visualize an instance of {@link Box3}.
  41605. *
  41606. * ```js
  41607. * const box = new THREE.Box3();
  41608. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41609. *
  41610. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41611. * scene.add( helper )
  41612. * ```
  41613. *
  41614. * @augments LineSegments
  41615. */
  41616. class Box3Helper extends LineSegments {
  41617. /**
  41618. * Constructs a new box3 helper.
  41619. *
  41620. * @param {Box3} box - The box to visualize.
  41621. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41622. */
  41623. constructor( box, color = 0xffff00 ) {
  41624. 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 ] );
  41625. 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 ];
  41626. const geometry = new BufferGeometry();
  41627. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41628. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41629. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41630. /**
  41631. * The box being visualized.
  41632. *
  41633. * @type {Box3}
  41634. */
  41635. this.box = box;
  41636. this.type = 'Box3Helper';
  41637. this.geometry.computeBoundingSphere();
  41638. }
  41639. updateMatrixWorld( force ) {
  41640. const box = this.box;
  41641. if ( box.isEmpty() ) return;
  41642. box.getCenter( this.position );
  41643. box.getSize( this.scale );
  41644. this.scale.multiplyScalar( 0.5 );
  41645. super.updateMatrixWorld( force );
  41646. }
  41647. /**
  41648. * Frees the GPU-related resources allocated by this instance. Call this
  41649. * method whenever this instance is no longer used in your app.
  41650. */
  41651. dispose() {
  41652. this.geometry.dispose();
  41653. this.material.dispose();
  41654. }
  41655. }
  41656. /**
  41657. * A helper object to visualize an instance of {@link Plane}.
  41658. *
  41659. * ```js
  41660. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41661. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41662. * scene.add( helper );
  41663. * ```
  41664. *
  41665. * @augments Line
  41666. */
  41667. class PlaneHelper extends Line {
  41668. /**
  41669. * Constructs a new plane helper.
  41670. *
  41671. * @param {Plane} plane - The plane to be visualized.
  41672. * @param {number} [size=1] - The side length of plane helper.
  41673. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41674. */
  41675. constructor( plane, size = 1, hex = 0xffff00 ) {
  41676. const color = hex;
  41677. 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 ];
  41678. const geometry = new BufferGeometry();
  41679. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41680. geometry.computeBoundingSphere();
  41681. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41682. this.type = 'PlaneHelper';
  41683. /**
  41684. * The plane being visualized.
  41685. *
  41686. * @type {Plane}
  41687. */
  41688. this.plane = plane;
  41689. /**
  41690. * The side length of plane helper.
  41691. *
  41692. * @type {number}
  41693. * @default 1
  41694. */
  41695. this.size = size;
  41696. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41697. const geometry2 = new BufferGeometry();
  41698. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41699. geometry2.computeBoundingSphere();
  41700. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41701. }
  41702. updateMatrixWorld( force ) {
  41703. this.position.set( 0, 0, 0 );
  41704. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41705. this.lookAt( this.plane.normal );
  41706. this.translateZ( - this.plane.constant );
  41707. super.updateMatrixWorld( force );
  41708. }
  41709. /**
  41710. * Updates the helper to match the position and direction of the
  41711. * light being visualized.
  41712. */
  41713. dispose() {
  41714. this.geometry.dispose();
  41715. this.material.dispose();
  41716. this.children[ 0 ].geometry.dispose();
  41717. this.children[ 0 ].material.dispose();
  41718. }
  41719. }
  41720. const _axis = /*@__PURE__*/ new Vector3();
  41721. let _lineGeometry, _coneGeometry;
  41722. /**
  41723. * An 3D arrow object for visualizing directions.
  41724. *
  41725. * ```js
  41726. * const dir = new THREE.Vector3( 1, 2, 0 );
  41727. *
  41728. * //normalize the direction vector (convert to vector of length 1)
  41729. * dir.normalize();
  41730. *
  41731. * const origin = new THREE.Vector3( 0, 0, 0 );
  41732. * const length = 1;
  41733. * const hex = 0xffff00;
  41734. *
  41735. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41736. * scene.add( arrowHelper );
  41737. * ```
  41738. *
  41739. * @augments Object3D
  41740. */
  41741. class ArrowHelper extends Object3D {
  41742. /**
  41743. * Constructs a new arrow helper.
  41744. *
  41745. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41746. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41747. * @param {number} [length=1] - Length of the arrow in world units.
  41748. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41749. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41750. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41751. */
  41752. 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 ) {
  41753. super();
  41754. this.type = 'ArrowHelper';
  41755. if ( _lineGeometry === undefined ) {
  41756. _lineGeometry = new BufferGeometry();
  41757. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41758. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41759. _coneGeometry.translate( 0, -0.5, 0 );
  41760. }
  41761. this.position.copy( origin );
  41762. /**
  41763. * The line part of the arrow helper.
  41764. *
  41765. * @type {Line}
  41766. */
  41767. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41768. this.line.matrixAutoUpdate = false;
  41769. this.add( this.line );
  41770. /**
  41771. * The cone part of the arrow helper.
  41772. *
  41773. * @type {Mesh}
  41774. */
  41775. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41776. this.cone.matrixAutoUpdate = false;
  41777. this.add( this.cone );
  41778. this.setDirection( dir );
  41779. this.setLength( length, headLength, headWidth );
  41780. }
  41781. /**
  41782. * Sets the direction of the helper.
  41783. *
  41784. * @param {Vector3} dir - The normalized direction vector.
  41785. */
  41786. setDirection( dir ) {
  41787. // dir is assumed to be normalized
  41788. if ( dir.y > 0.99999 ) {
  41789. this.quaternion.set( 0, 0, 0, 1 );
  41790. } else if ( dir.y < -0.99999 ) {
  41791. this.quaternion.set( 1, 0, 0, 0 );
  41792. } else {
  41793. _axis.set( dir.z, 0, - dir.x ).normalize();
  41794. const radians = Math.acos( dir.y );
  41795. this.quaternion.setFromAxisAngle( _axis, radians );
  41796. }
  41797. }
  41798. /**
  41799. * Sets the length of the helper.
  41800. *
  41801. * @param {number} length - Length of the arrow in world units.
  41802. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41803. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41804. */
  41805. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41806. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41807. this.line.updateMatrix();
  41808. this.cone.scale.set( headWidth, headLength, headWidth );
  41809. this.cone.position.y = length;
  41810. this.cone.updateMatrix();
  41811. }
  41812. /**
  41813. * Sets the color of the helper.
  41814. *
  41815. * @param {number|Color|string} color - The color to set.
  41816. */
  41817. setColor( color ) {
  41818. this.line.material.color.set( color );
  41819. this.cone.material.color.set( color );
  41820. }
  41821. copy( source ) {
  41822. super.copy( source, false );
  41823. this.line.copy( source.line );
  41824. this.cone.copy( source.cone );
  41825. return this;
  41826. }
  41827. /**
  41828. * Frees the GPU-related resources allocated by this instance. Call this
  41829. * method whenever this instance is no longer used in your app.
  41830. */
  41831. dispose() {
  41832. this.line.geometry.dispose();
  41833. this.line.material.dispose();
  41834. this.cone.geometry.dispose();
  41835. this.cone.material.dispose();
  41836. }
  41837. }
  41838. /**
  41839. * An axis object to visualize the 3 axes in a simple way.
  41840. * The X axis is red. The Y axis is green. The Z axis is blue.
  41841. *
  41842. * ```js
  41843. * const axesHelper = new THREE.AxesHelper( 5 );
  41844. * scene.add( axesHelper );
  41845. * ```
  41846. *
  41847. * @augments LineSegments
  41848. */
  41849. class AxesHelper extends LineSegments {
  41850. /**
  41851. * Constructs a new axes helper.
  41852. *
  41853. * @param {number} [size=1] - Size of the lines representing the axes.
  41854. */
  41855. constructor( size = 1 ) {
  41856. const vertices = [
  41857. 0, 0, 0, size, 0, 0,
  41858. 0, 0, 0, 0, size, 0,
  41859. 0, 0, 0, 0, 0, size
  41860. ];
  41861. const colors = [
  41862. 1, 0, 0, 1, 0.6, 0,
  41863. 0, 1, 0, 0.6, 1, 0,
  41864. 0, 0, 1, 0, 0.6, 1
  41865. ];
  41866. const geometry = new BufferGeometry();
  41867. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41868. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41869. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41870. super( geometry, material );
  41871. this.type = 'AxesHelper';
  41872. }
  41873. /**
  41874. * Defines the colors of the axes helper.
  41875. *
  41876. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41877. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41878. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41879. * @return {AxesHelper} A reference to this axes helper.
  41880. */
  41881. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41882. const color = new Color();
  41883. const array = this.geometry.attributes.color.array;
  41884. color.set( xAxisColor );
  41885. color.toArray( array, 0 );
  41886. color.toArray( array, 3 );
  41887. color.set( yAxisColor );
  41888. color.toArray( array, 6 );
  41889. color.toArray( array, 9 );
  41890. color.set( zAxisColor );
  41891. color.toArray( array, 12 );
  41892. color.toArray( array, 15 );
  41893. this.geometry.attributes.color.needsUpdate = true;
  41894. return this;
  41895. }
  41896. /**
  41897. * Frees the GPU-related resources allocated by this instance. Call this
  41898. * method whenever this instance is no longer used in your app.
  41899. */
  41900. dispose() {
  41901. this.geometry.dispose();
  41902. this.material.dispose();
  41903. }
  41904. }
  41905. /**
  41906. * This class is used to convert a series of paths to an array of
  41907. * shapes. It is specifically used in context of fonts and SVG.
  41908. */
  41909. class ShapePath {
  41910. /**
  41911. * Constructs a new shape path.
  41912. */
  41913. constructor() {
  41914. this.type = 'ShapePath';
  41915. /**
  41916. * The color of the shape.
  41917. *
  41918. * @type {Color}
  41919. */
  41920. this.color = new Color();
  41921. /**
  41922. * The paths that have been generated for this shape.
  41923. *
  41924. * @type {Array<Path>}
  41925. * @default null
  41926. */
  41927. this.subPaths = [];
  41928. /**
  41929. * The current path that is being generated.
  41930. *
  41931. * @type {?Path}
  41932. * @default null
  41933. */
  41934. this.currentPath = null;
  41935. }
  41936. /**
  41937. * Creates a new path and moves it current point to the given one.
  41938. *
  41939. * @param {number} x - The x coordinate.
  41940. * @param {number} y - The y coordinate.
  41941. * @return {ShapePath} A reference to this shape path.
  41942. */
  41943. moveTo( x, y ) {
  41944. this.currentPath = new Path();
  41945. this.subPaths.push( this.currentPath );
  41946. this.currentPath.moveTo( x, y );
  41947. return this;
  41948. }
  41949. /**
  41950. * Adds an instance of {@link LineCurve} to the path by connecting
  41951. * the current point with the given one.
  41952. *
  41953. * @param {number} x - The x coordinate of the end point.
  41954. * @param {number} y - The y coordinate of the end point.
  41955. * @return {ShapePath} A reference to this shape path.
  41956. */
  41957. lineTo( x, y ) {
  41958. this.currentPath.lineTo( x, y );
  41959. return this;
  41960. }
  41961. /**
  41962. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41963. * the current point with the given one.
  41964. *
  41965. * @param {number} aCPx - The x coordinate of the control point.
  41966. * @param {number} aCPy - The y coordinate of the control point.
  41967. * @param {number} aX - The x coordinate of the end point.
  41968. * @param {number} aY - The y coordinate of the end point.
  41969. * @return {ShapePath} A reference to this shape path.
  41970. */
  41971. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41972. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41973. return this;
  41974. }
  41975. /**
  41976. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41977. * the current point with the given one.
  41978. *
  41979. * @param {number} aCP1x - The x coordinate of the first control point.
  41980. * @param {number} aCP1y - The y coordinate of the first control point.
  41981. * @param {number} aCP2x - The x coordinate of the second control point.
  41982. * @param {number} aCP2y - The y coordinate of the second control point.
  41983. * @param {number} aX - The x coordinate of the end point.
  41984. * @param {number} aY - The y coordinate of the end point.
  41985. * @return {ShapePath} A reference to this shape path.
  41986. */
  41987. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  41988. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  41989. return this;
  41990. }
  41991. /**
  41992. * Adds an instance of {@link SplineCurve} to the path by connecting
  41993. * the current point with the given list of points.
  41994. *
  41995. * @param {Array<Vector2>} pts - An array of points in 2D space.
  41996. * @return {ShapePath} A reference to this shape path.
  41997. */
  41998. splineThru( pts ) {
  41999. this.currentPath.splineThru( pts );
  42000. return this;
  42001. }
  42002. /**
  42003. * Converts the paths into an array of shapes.
  42004. *
  42005. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42006. * If this flag is set to `true`, then those are flipped.
  42007. * @return {Array<Shape>} An array of shapes.
  42008. */
  42009. toShapes( isCCW ) {
  42010. function toShapesNoHoles( inSubpaths ) {
  42011. const shapes = [];
  42012. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42013. const tmpPath = inSubpaths[ i ];
  42014. const tmpShape = new Shape();
  42015. tmpShape.curves = tmpPath.curves;
  42016. shapes.push( tmpShape );
  42017. }
  42018. return shapes;
  42019. }
  42020. function isPointInsidePolygon( inPt, inPolygon ) {
  42021. const polyLen = inPolygon.length;
  42022. // inPt on polygon contour => immediate success or
  42023. // toggling of inside/outside at every single! intersection point of an edge
  42024. // with the horizontal line through inPt, left of inPt
  42025. // not counting lowerY endpoints of edges and whole edges on that line
  42026. let inside = false;
  42027. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42028. let edgeLowPt = inPolygon[ p ];
  42029. let edgeHighPt = inPolygon[ q ];
  42030. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42031. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42032. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42033. // not parallel
  42034. if ( edgeDy < 0 ) {
  42035. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42036. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42037. }
  42038. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42039. if ( inPt.y === edgeLowPt.y ) {
  42040. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42041. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42042. } else {
  42043. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42044. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42045. if ( perpEdge < 0 ) continue;
  42046. inside = ! inside; // true intersection left of inPt
  42047. }
  42048. } else {
  42049. // parallel or collinear
  42050. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42051. // edge lies on the same horizontal line as inPt
  42052. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42053. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42054. // continue;
  42055. }
  42056. }
  42057. return inside;
  42058. }
  42059. const isClockWise = ShapeUtils.isClockWise;
  42060. const subPaths = this.subPaths;
  42061. if ( subPaths.length === 0 ) return [];
  42062. let solid, tmpPath, tmpShape;
  42063. const shapes = [];
  42064. if ( subPaths.length === 1 ) {
  42065. tmpPath = subPaths[ 0 ];
  42066. tmpShape = new Shape();
  42067. tmpShape.curves = tmpPath.curves;
  42068. shapes.push( tmpShape );
  42069. return shapes;
  42070. }
  42071. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42072. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42073. // console.log("Holes first", holesFirst);
  42074. const betterShapeHoles = [];
  42075. const newShapes = [];
  42076. let newShapeHoles = [];
  42077. let mainIdx = 0;
  42078. let tmpPoints;
  42079. newShapes[ mainIdx ] = undefined;
  42080. newShapeHoles[ mainIdx ] = [];
  42081. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42082. tmpPath = subPaths[ i ];
  42083. tmpPoints = tmpPath.getPoints();
  42084. solid = isClockWise( tmpPoints );
  42085. solid = isCCW ? ! solid : solid;
  42086. if ( solid ) {
  42087. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42088. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42089. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42090. if ( holesFirst ) mainIdx ++;
  42091. newShapeHoles[ mainIdx ] = [];
  42092. //console.log('cw', i);
  42093. } else {
  42094. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42095. //console.log('ccw', i);
  42096. }
  42097. }
  42098. // only Holes? -> probably all Shapes with wrong orientation
  42099. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42100. if ( newShapes.length > 1 ) {
  42101. let ambiguous = false;
  42102. let toChange = 0;
  42103. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42104. betterShapeHoles[ sIdx ] = [];
  42105. }
  42106. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42107. const sho = newShapeHoles[ sIdx ];
  42108. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42109. const ho = sho[ hIdx ];
  42110. let hole_unassigned = true;
  42111. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42112. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42113. if ( sIdx !== s2Idx ) toChange ++;
  42114. if ( hole_unassigned ) {
  42115. hole_unassigned = false;
  42116. betterShapeHoles[ s2Idx ].push( ho );
  42117. } else {
  42118. ambiguous = true;
  42119. }
  42120. }
  42121. }
  42122. if ( hole_unassigned ) {
  42123. betterShapeHoles[ sIdx ].push( ho );
  42124. }
  42125. }
  42126. }
  42127. if ( toChange > 0 && ambiguous === false ) {
  42128. newShapeHoles = betterShapeHoles;
  42129. }
  42130. }
  42131. let tmpHoles;
  42132. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42133. tmpShape = newShapes[ i ].s;
  42134. shapes.push( tmpShape );
  42135. tmpHoles = newShapeHoles[ i ];
  42136. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42137. tmpShape.holes.push( tmpHoles[ j ].h );
  42138. }
  42139. }
  42140. //console.log("shape", shapes);
  42141. return shapes;
  42142. }
  42143. }
  42144. /**
  42145. * Abstract base class for controls.
  42146. *
  42147. * @abstract
  42148. * @augments EventDispatcher
  42149. */
  42150. class Controls extends EventDispatcher {
  42151. /**
  42152. * Constructs a new controls instance.
  42153. *
  42154. * @param {Object3D} object - The object that is managed by the controls.
  42155. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42156. */
  42157. constructor( object, domElement = null ) {
  42158. super();
  42159. /**
  42160. * The object that is managed by the controls.
  42161. *
  42162. * @type {Object3D}
  42163. */
  42164. this.object = object;
  42165. /**
  42166. * The HTML element used for event listeners.
  42167. *
  42168. * @type {?HTMLDOMElement}
  42169. * @default null
  42170. */
  42171. this.domElement = domElement;
  42172. /**
  42173. * Whether the controls responds to user input or not.
  42174. *
  42175. * @type {boolean}
  42176. * @default true
  42177. */
  42178. this.enabled = true;
  42179. /**
  42180. * The internal state of the controls.
  42181. *
  42182. * @type {number}
  42183. * @default -1
  42184. */
  42185. this.state = -1;
  42186. /**
  42187. * This object defines the keyboard input of the controls.
  42188. *
  42189. * @type {Object}
  42190. */
  42191. this.keys = {};
  42192. /**
  42193. * This object defines what type of actions are assigned to the available mouse buttons.
  42194. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42195. *
  42196. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42197. */
  42198. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42199. /**
  42200. * This object defines what type of actions are assigned to what kind of touch interaction.
  42201. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42202. *
  42203. * @type {{ONE: ?number, TWO: ?number}}
  42204. */
  42205. this.touches = { ONE: null, TWO: null };
  42206. }
  42207. /**
  42208. * Connects the controls to the DOM. This method has so called "side effects" since
  42209. * it adds the module's event listeners to the DOM.
  42210. *
  42211. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42212. */
  42213. connect( element ) {
  42214. if ( element === undefined ) {
  42215. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42216. return;
  42217. }
  42218. if ( this.domElement !== null ) this.disconnect();
  42219. this.domElement = element;
  42220. }
  42221. /**
  42222. * Disconnects the controls from the DOM.
  42223. */
  42224. disconnect() {}
  42225. /**
  42226. * Call this method if you no longer want use to the controls. It frees all internal
  42227. * resources and removes all event listeners.
  42228. */
  42229. dispose() {}
  42230. /**
  42231. * Controls should implement this method if they have to update their internal state
  42232. * per simulation step.
  42233. *
  42234. * @param {number} [delta] - The time delta in seconds.
  42235. */
  42236. update( /* delta */ ) {}
  42237. }
  42238. /**
  42239. * Scales the texture as large as possible within its surface without cropping
  42240. * or stretching the texture. The method preserves the original aspect ratio of
  42241. * the texture. Akin to CSS `object-fit: contain`
  42242. *
  42243. * @param {Texture} texture - The texture.
  42244. * @param {number} aspect - The texture's aspect ratio.
  42245. * @return {Texture} The updated texture.
  42246. */
  42247. function contain( texture, aspect ) {
  42248. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42249. if ( imageAspect > aspect ) {
  42250. texture.repeat.x = 1;
  42251. texture.repeat.y = imageAspect / aspect;
  42252. texture.offset.x = 0;
  42253. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42254. } else {
  42255. texture.repeat.x = aspect / imageAspect;
  42256. texture.repeat.y = 1;
  42257. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42258. texture.offset.y = 0;
  42259. }
  42260. return texture;
  42261. }
  42262. /**
  42263. * Scales the texture to the smallest possible size to fill the surface, leaving
  42264. * no empty space. The method preserves the original aspect ratio of the texture.
  42265. * Akin to CSS `object-fit: cover`.
  42266. *
  42267. * @param {Texture} texture - The texture.
  42268. * @param {number} aspect - The texture's aspect ratio.
  42269. * @return {Texture} The updated texture.
  42270. */
  42271. function cover( texture, aspect ) {
  42272. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42273. if ( imageAspect > aspect ) {
  42274. texture.repeat.x = aspect / imageAspect;
  42275. texture.repeat.y = 1;
  42276. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42277. texture.offset.y = 0;
  42278. } else {
  42279. texture.repeat.x = 1;
  42280. texture.repeat.y = imageAspect / aspect;
  42281. texture.offset.x = 0;
  42282. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42283. }
  42284. return texture;
  42285. }
  42286. /**
  42287. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42288. *
  42289. * @param {Texture} texture - The texture.
  42290. * @return {Texture} The updated texture.
  42291. */
  42292. function fill( texture ) {
  42293. texture.repeat.x = 1;
  42294. texture.repeat.y = 1;
  42295. texture.offset.x = 0;
  42296. texture.offset.y = 0;
  42297. return texture;
  42298. }
  42299. /**
  42300. * Determines how many bytes must be used to represent the texture.
  42301. *
  42302. * @param {number} width - The width of the texture.
  42303. * @param {number} height - The height of the texture.
  42304. * @param {number} format - The texture's format.
  42305. * @param {number} type - The texture's type.
  42306. * @return {number} The byte length.
  42307. */
  42308. function getByteLength( width, height, format, type ) {
  42309. const typeByteLength = getTextureTypeByteLength( type );
  42310. switch ( format ) {
  42311. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42312. case AlphaFormat:
  42313. return width * height;
  42314. case RedFormat:
  42315. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42316. case RedIntegerFormat:
  42317. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42318. case RGFormat:
  42319. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42320. case RGIntegerFormat:
  42321. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42322. case RGBFormat:
  42323. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42324. case RGBAFormat:
  42325. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42326. case RGBAIntegerFormat:
  42327. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42328. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42329. case RGB_S3TC_DXT1_Format:
  42330. case RGBA_S3TC_DXT1_Format:
  42331. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42332. case RGBA_S3TC_DXT3_Format:
  42333. case RGBA_S3TC_DXT5_Format:
  42334. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42335. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42336. case RGB_PVRTC_2BPPV1_Format:
  42337. case RGBA_PVRTC_2BPPV1_Format:
  42338. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42339. case RGB_PVRTC_4BPPV1_Format:
  42340. case RGBA_PVRTC_4BPPV1_Format:
  42341. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42342. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42343. case RGB_ETC1_Format:
  42344. case RGB_ETC2_Format:
  42345. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42346. case RGBA_ETC2_EAC_Format:
  42347. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42348. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42349. case RGBA_ASTC_4x4_Format:
  42350. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42351. case RGBA_ASTC_5x4_Format:
  42352. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42353. case RGBA_ASTC_5x5_Format:
  42354. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42355. case RGBA_ASTC_6x5_Format:
  42356. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42357. case RGBA_ASTC_6x6_Format:
  42358. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42359. case RGBA_ASTC_8x5_Format:
  42360. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42361. case RGBA_ASTC_8x6_Format:
  42362. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42363. case RGBA_ASTC_8x8_Format:
  42364. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42365. case RGBA_ASTC_10x5_Format:
  42366. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42367. case RGBA_ASTC_10x6_Format:
  42368. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42369. case RGBA_ASTC_10x8_Format:
  42370. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42371. case RGBA_ASTC_10x10_Format:
  42372. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42373. case RGBA_ASTC_12x10_Format:
  42374. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42375. case RGBA_ASTC_12x12_Format:
  42376. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42377. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42378. case RGBA_BPTC_Format:
  42379. case RGB_BPTC_SIGNED_Format:
  42380. case RGB_BPTC_UNSIGNED_Format:
  42381. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42382. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42383. case RED_RGTC1_Format:
  42384. case SIGNED_RED_RGTC1_Format:
  42385. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42386. case RED_GREEN_RGTC2_Format:
  42387. case SIGNED_RED_GREEN_RGTC2_Format:
  42388. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42389. }
  42390. throw new Error(
  42391. `Unable to determine texture byte length for ${format} format.`,
  42392. );
  42393. }
  42394. function getTextureTypeByteLength( type ) {
  42395. switch ( type ) {
  42396. case UnsignedByteType:
  42397. case ByteType:
  42398. return { byteLength: 1, components: 1 };
  42399. case UnsignedShortType:
  42400. case ShortType:
  42401. case HalfFloatType:
  42402. return { byteLength: 2, components: 1 };
  42403. case UnsignedShort4444Type:
  42404. case UnsignedShort5551Type:
  42405. return { byteLength: 2, components: 4 };
  42406. case UnsignedIntType:
  42407. case IntType:
  42408. case FloatType:
  42409. return { byteLength: 4, components: 1 };
  42410. case UnsignedInt5999Type:
  42411. return { byteLength: 4, components: 3 };
  42412. }
  42413. throw new Error( `Unknown texture type ${type}.` );
  42414. }
  42415. /**
  42416. * A class containing utility functions for textures.
  42417. *
  42418. * @hideconstructor
  42419. */
  42420. class TextureUtils {
  42421. /**
  42422. * Scales the texture as large as possible within its surface without cropping
  42423. * or stretching the texture. The method preserves the original aspect ratio of
  42424. * the texture. Akin to CSS `object-fit: contain`
  42425. *
  42426. * @param {Texture} texture - The texture.
  42427. * @param {number} aspect - The texture's aspect ratio.
  42428. * @return {Texture} The updated texture.
  42429. */
  42430. static contain( texture, aspect ) {
  42431. return contain( texture, aspect );
  42432. }
  42433. /**
  42434. * Scales the texture to the smallest possible size to fill the surface, leaving
  42435. * no empty space. The method preserves the original aspect ratio of the texture.
  42436. * Akin to CSS `object-fit: cover`.
  42437. *
  42438. * @param {Texture} texture - The texture.
  42439. * @param {number} aspect - The texture's aspect ratio.
  42440. * @return {Texture} The updated texture.
  42441. */
  42442. static cover( texture, aspect ) {
  42443. return cover( texture, aspect );
  42444. }
  42445. /**
  42446. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42447. *
  42448. * @param {Texture} texture - The texture.
  42449. * @return {Texture} The updated texture.
  42450. */
  42451. static fill( texture ) {
  42452. return fill( texture );
  42453. }
  42454. /**
  42455. * Determines how many bytes must be used to represent the texture.
  42456. *
  42457. * @param {number} width - The width of the texture.
  42458. * @param {number} height - The height of the texture.
  42459. * @param {number} format - The texture's format.
  42460. * @param {number} type - The texture's type.
  42461. * @return {number} The byte length.
  42462. */
  42463. static getByteLength( width, height, format, type ) {
  42464. return getByteLength( width, height, format, type );
  42465. }
  42466. }
  42467. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42468. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42469. revision: REVISION,
  42470. } } ) );
  42471. }
  42472. if ( typeof window !== 'undefined' ) {
  42473. if ( window.__THREE__ ) {
  42474. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42475. } else {
  42476. window.__THREE__ = REVISION;
  42477. }
  42478. }
  42479. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, FrustumArray, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, 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, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, Timer, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, getByteLength, getUnlitUniformColorSpace, mergeUniforms, probeAsync, warnOnce };
粤ICP备19079148号