three.core.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608
  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 w = 1.0 / ( right - left );
  9483. const h = 1.0 / ( top - bottom );
  9484. const p = 1.0 / ( far - near );
  9485. const x = ( right + left ) * w;
  9486. const y = ( top + bottom ) * h;
  9487. let z, zInv;
  9488. if ( reversedDepth ) {
  9489. z = - near * p - 1;
  9490. zInv = 1 * p;
  9491. } else {
  9492. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9493. z = ( far + near ) * p;
  9494. zInv = -2 * p;
  9495. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9496. z = near * p;
  9497. zInv = -1 * p;
  9498. } else {
  9499. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9500. }
  9501. }
  9502. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  9503. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  9504. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  9505. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9506. return this;
  9507. }
  9508. /**
  9509. * Returns `true` if this matrix is equal with the given one.
  9510. *
  9511. * @param {Matrix4} matrix - The matrix to test for equality.
  9512. * @return {boolean} Whether this matrix is equal with the given one.
  9513. */
  9514. equals( matrix ) {
  9515. const te = this.elements;
  9516. const me = matrix.elements;
  9517. for ( let i = 0; i < 16; i ++ ) {
  9518. if ( te[ i ] !== me[ i ] ) return false;
  9519. }
  9520. return true;
  9521. }
  9522. /**
  9523. * Sets the elements of the matrix from the given array.
  9524. *
  9525. * @param {Array<number>} array - The matrix elements in column-major order.
  9526. * @param {number} [offset=0] - Index of the first element in the array.
  9527. * @return {Matrix4} A reference to this matrix.
  9528. */
  9529. fromArray( array, offset = 0 ) {
  9530. for ( let i = 0; i < 16; i ++ ) {
  9531. this.elements[ i ] = array[ i + offset ];
  9532. }
  9533. return this;
  9534. }
  9535. /**
  9536. * Writes the elements of this matrix to the given array. If no array is provided,
  9537. * the method returns a new instance.
  9538. *
  9539. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9540. * @param {number} [offset=0] - Index of the first element in the array.
  9541. * @return {Array<number>} The matrix elements in column-major order.
  9542. */
  9543. toArray( array = [], offset = 0 ) {
  9544. const te = this.elements;
  9545. array[ offset ] = te[ 0 ];
  9546. array[ offset + 1 ] = te[ 1 ];
  9547. array[ offset + 2 ] = te[ 2 ];
  9548. array[ offset + 3 ] = te[ 3 ];
  9549. array[ offset + 4 ] = te[ 4 ];
  9550. array[ offset + 5 ] = te[ 5 ];
  9551. array[ offset + 6 ] = te[ 6 ];
  9552. array[ offset + 7 ] = te[ 7 ];
  9553. array[ offset + 8 ] = te[ 8 ];
  9554. array[ offset + 9 ] = te[ 9 ];
  9555. array[ offset + 10 ] = te[ 10 ];
  9556. array[ offset + 11 ] = te[ 11 ];
  9557. array[ offset + 12 ] = te[ 12 ];
  9558. array[ offset + 13 ] = te[ 13 ];
  9559. array[ offset + 14 ] = te[ 14 ];
  9560. array[ offset + 15 ] = te[ 15 ];
  9561. return array;
  9562. }
  9563. }
  9564. const _v1$5 = /*@__PURE__*/ new Vector3();
  9565. const _m1$2 = /*@__PURE__*/ new Matrix4();
  9566. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9567. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9568. const _x = /*@__PURE__*/ new Vector3();
  9569. const _y = /*@__PURE__*/ new Vector3();
  9570. const _z = /*@__PURE__*/ new Vector3();
  9571. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9572. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9573. /**
  9574. * A class representing Euler angles.
  9575. *
  9576. * Euler angles describe a rotational transformation by rotating an object on
  9577. * its various axes in specified amounts per axis, and a specified axis
  9578. * order.
  9579. *
  9580. * Iterating through an instance will yield its components (x, y, z,
  9581. * order) in the corresponding order.
  9582. *
  9583. * ```js
  9584. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9585. * const b = new THREE.Vector3( 1, 0, 1 );
  9586. * b.applyEuler(a);
  9587. * ```
  9588. */
  9589. class Euler {
  9590. /**
  9591. * Constructs a new euler instance.
  9592. *
  9593. * @param {number} [x=0] - The angle of the x axis in radians.
  9594. * @param {number} [y=0] - The angle of the y axis in radians.
  9595. * @param {number} [z=0] - The angle of the z axis in radians.
  9596. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9597. */
  9598. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9599. /**
  9600. * This flag can be used for type testing.
  9601. *
  9602. * @type {boolean}
  9603. * @readonly
  9604. * @default true
  9605. */
  9606. this.isEuler = true;
  9607. this._x = x;
  9608. this._y = y;
  9609. this._z = z;
  9610. this._order = order;
  9611. }
  9612. /**
  9613. * The angle of the x axis in radians.
  9614. *
  9615. * @type {number}
  9616. * @default 0
  9617. */
  9618. get x() {
  9619. return this._x;
  9620. }
  9621. set x( value ) {
  9622. this._x = value;
  9623. this._onChangeCallback();
  9624. }
  9625. /**
  9626. * The angle of the y axis in radians.
  9627. *
  9628. * @type {number}
  9629. * @default 0
  9630. */
  9631. get y() {
  9632. return this._y;
  9633. }
  9634. set y( value ) {
  9635. this._y = value;
  9636. this._onChangeCallback();
  9637. }
  9638. /**
  9639. * The angle of the z axis in radians.
  9640. *
  9641. * @type {number}
  9642. * @default 0
  9643. */
  9644. get z() {
  9645. return this._z;
  9646. }
  9647. set z( value ) {
  9648. this._z = value;
  9649. this._onChangeCallback();
  9650. }
  9651. /**
  9652. * A string representing the order that the rotations are applied.
  9653. *
  9654. * @type {string}
  9655. * @default 'XYZ'
  9656. */
  9657. get order() {
  9658. return this._order;
  9659. }
  9660. set order( value ) {
  9661. this._order = value;
  9662. this._onChangeCallback();
  9663. }
  9664. /**
  9665. * Sets the Euler components.
  9666. *
  9667. * @param {number} x - The angle of the x axis in radians.
  9668. * @param {number} y - The angle of the y axis in radians.
  9669. * @param {number} z - The angle of the z axis in radians.
  9670. * @param {string} [order] - A string representing the order that the rotations are applied.
  9671. * @return {Euler} A reference to this Euler instance.
  9672. */
  9673. set( x, y, z, order = this._order ) {
  9674. this._x = x;
  9675. this._y = y;
  9676. this._z = z;
  9677. this._order = order;
  9678. this._onChangeCallback();
  9679. return this;
  9680. }
  9681. /**
  9682. * Returns a new Euler instance with copied values from this instance.
  9683. *
  9684. * @return {Euler} A clone of this instance.
  9685. */
  9686. clone() {
  9687. return new this.constructor( this._x, this._y, this._z, this._order );
  9688. }
  9689. /**
  9690. * Copies the values of the given Euler instance to this instance.
  9691. *
  9692. * @param {Euler} euler - The Euler instance to copy.
  9693. * @return {Euler} A reference to this Euler instance.
  9694. */
  9695. copy( euler ) {
  9696. this._x = euler._x;
  9697. this._y = euler._y;
  9698. this._z = euler._z;
  9699. this._order = euler._order;
  9700. this._onChangeCallback();
  9701. return this;
  9702. }
  9703. /**
  9704. * Sets the angles of this Euler instance from a pure rotation matrix.
  9705. *
  9706. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9707. * @param {string} [order] - A string representing the order that the rotations are applied.
  9708. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9709. * @return {Euler} A reference to this Euler instance.
  9710. */
  9711. setFromRotationMatrix( m, order = this._order, update = true ) {
  9712. const te = m.elements;
  9713. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9714. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9715. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9716. switch ( order ) {
  9717. case 'XYZ':
  9718. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9719. if ( Math.abs( m13 ) < 0.9999999 ) {
  9720. this._x = Math.atan2( - m23, m33 );
  9721. this._z = Math.atan2( - m12, m11 );
  9722. } else {
  9723. this._x = Math.atan2( m32, m22 );
  9724. this._z = 0;
  9725. }
  9726. break;
  9727. case 'YXZ':
  9728. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9729. if ( Math.abs( m23 ) < 0.9999999 ) {
  9730. this._y = Math.atan2( m13, m33 );
  9731. this._z = Math.atan2( m21, m22 );
  9732. } else {
  9733. this._y = Math.atan2( - m31, m11 );
  9734. this._z = 0;
  9735. }
  9736. break;
  9737. case 'ZXY':
  9738. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9739. if ( Math.abs( m32 ) < 0.9999999 ) {
  9740. this._y = Math.atan2( - m31, m33 );
  9741. this._z = Math.atan2( - m12, m22 );
  9742. } else {
  9743. this._y = 0;
  9744. this._z = Math.atan2( m21, m11 );
  9745. }
  9746. break;
  9747. case 'ZYX':
  9748. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9749. if ( Math.abs( m31 ) < 0.9999999 ) {
  9750. this._x = Math.atan2( m32, m33 );
  9751. this._z = Math.atan2( m21, m11 );
  9752. } else {
  9753. this._x = 0;
  9754. this._z = Math.atan2( - m12, m22 );
  9755. }
  9756. break;
  9757. case 'YZX':
  9758. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9759. if ( Math.abs( m21 ) < 0.9999999 ) {
  9760. this._x = Math.atan2( - m23, m22 );
  9761. this._y = Math.atan2( - m31, m11 );
  9762. } else {
  9763. this._x = 0;
  9764. this._y = Math.atan2( m13, m33 );
  9765. }
  9766. break;
  9767. case 'XZY':
  9768. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9769. if ( Math.abs( m12 ) < 0.9999999 ) {
  9770. this._x = Math.atan2( m32, m22 );
  9771. this._y = Math.atan2( m13, m11 );
  9772. } else {
  9773. this._x = Math.atan2( - m23, m33 );
  9774. this._y = 0;
  9775. }
  9776. break;
  9777. default:
  9778. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9779. }
  9780. this._order = order;
  9781. if ( update === true ) this._onChangeCallback();
  9782. return this;
  9783. }
  9784. /**
  9785. * Sets the angles of this Euler instance from a normalized quaternion.
  9786. *
  9787. * @param {Quaternion} q - A normalized Quaternion.
  9788. * @param {string} [order] - A string representing the order that the rotations are applied.
  9789. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9790. * @return {Euler} A reference to this Euler instance.
  9791. */
  9792. setFromQuaternion( q, order, update ) {
  9793. _matrix$2.makeRotationFromQuaternion( q );
  9794. return this.setFromRotationMatrix( _matrix$2, order, update );
  9795. }
  9796. /**
  9797. * Sets the angles of this Euler instance from the given vector.
  9798. *
  9799. * @param {Vector3} v - The vector.
  9800. * @param {string} [order] - A string representing the order that the rotations are applied.
  9801. * @return {Euler} A reference to this Euler instance.
  9802. */
  9803. setFromVector3( v, order = this._order ) {
  9804. return this.set( v.x, v.y, v.z, order );
  9805. }
  9806. /**
  9807. * Resets the euler angle with a new order by creating a quaternion from this
  9808. * euler angle and then setting this euler angle with the quaternion and the
  9809. * new order.
  9810. *
  9811. * Warning: This discards revolution information.
  9812. *
  9813. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9814. * @return {Euler} A reference to this Euler instance.
  9815. */
  9816. reorder( newOrder ) {
  9817. _quaternion$3.setFromEuler( this );
  9818. return this.setFromQuaternion( _quaternion$3, newOrder );
  9819. }
  9820. /**
  9821. * Returns `true` if this Euler instance is equal with the given one.
  9822. *
  9823. * @param {Euler} euler - The Euler instance to test for equality.
  9824. * @return {boolean} Whether this Euler instance is equal with the given one.
  9825. */
  9826. equals( euler ) {
  9827. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9828. }
  9829. /**
  9830. * Sets this Euler instance's components to values from the given array. The first three
  9831. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9832. * defines the Euler order.
  9833. *
  9834. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9835. * @return {Euler} A reference to this Euler instance.
  9836. */
  9837. fromArray( array ) {
  9838. this._x = array[ 0 ];
  9839. this._y = array[ 1 ];
  9840. this._z = array[ 2 ];
  9841. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9842. this._onChangeCallback();
  9843. return this;
  9844. }
  9845. /**
  9846. * Writes the components of this Euler instance to the given array. If no array is provided,
  9847. * the method returns a new instance.
  9848. *
  9849. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9850. * @param {number} [offset=0] - Index of the first element in the array.
  9851. * @return {Array<number,number,number,string>} The Euler components.
  9852. */
  9853. toArray( array = [], offset = 0 ) {
  9854. array[ offset ] = this._x;
  9855. array[ offset + 1 ] = this._y;
  9856. array[ offset + 2 ] = this._z;
  9857. array[ offset + 3 ] = this._order;
  9858. return array;
  9859. }
  9860. _onChange( callback ) {
  9861. this._onChangeCallback = callback;
  9862. return this;
  9863. }
  9864. _onChangeCallback() {}
  9865. *[ Symbol.iterator ]() {
  9866. yield this._x;
  9867. yield this._y;
  9868. yield this._z;
  9869. yield this._order;
  9870. }
  9871. }
  9872. /**
  9873. * The default Euler angle order.
  9874. *
  9875. * @static
  9876. * @type {string}
  9877. * @default 'XYZ'
  9878. */
  9879. Euler.DEFAULT_ORDER = 'XYZ';
  9880. /**
  9881. * A layers object assigns an 3D object to 1 or more of 32
  9882. * layers numbered `0` to `31` - internally the layers are stored as a
  9883. * bit mask], and by default all 3D objects are a member of layer `0`.
  9884. *
  9885. * This can be used to control visibility - an object must share a layer with
  9886. * a camera to be visible when that camera's view is
  9887. * rendered.
  9888. *
  9889. * All classes that inherit from {@link Object3D} have an `layers` property which
  9890. * is an instance of this class.
  9891. */
  9892. class Layers {
  9893. /**
  9894. * Constructs a new layers instance, with membership
  9895. * initially set to layer `0`.
  9896. */
  9897. constructor() {
  9898. /**
  9899. * A bit mask storing which of the 32 layers this layers object is currently
  9900. * a member of.
  9901. *
  9902. * @type {number}
  9903. */
  9904. this.mask = 1 | 0;
  9905. }
  9906. /**
  9907. * Sets membership to the given layer, and remove membership all other layers.
  9908. *
  9909. * @param {number} layer - The layer to set.
  9910. */
  9911. set( layer ) {
  9912. this.mask = ( 1 << layer | 0 ) >>> 0;
  9913. }
  9914. /**
  9915. * Adds membership of the given layer.
  9916. *
  9917. * @param {number} layer - The layer to enable.
  9918. */
  9919. enable( layer ) {
  9920. this.mask |= 1 << layer | 0;
  9921. }
  9922. /**
  9923. * Adds membership to all layers.
  9924. */
  9925. enableAll() {
  9926. this.mask = 0xffffffff | 0;
  9927. }
  9928. /**
  9929. * Toggles the membership of the given layer.
  9930. *
  9931. * @param {number} layer - The layer to toggle.
  9932. */
  9933. toggle( layer ) {
  9934. this.mask ^= 1 << layer | 0;
  9935. }
  9936. /**
  9937. * Removes membership of the given layer.
  9938. *
  9939. * @param {number} layer - The layer to enable.
  9940. */
  9941. disable( layer ) {
  9942. this.mask &= ~ ( 1 << layer | 0 );
  9943. }
  9944. /**
  9945. * Removes the membership from all layers.
  9946. */
  9947. disableAll() {
  9948. this.mask = 0;
  9949. }
  9950. /**
  9951. * Returns `true` if this and the given layers object have at least one
  9952. * layer in common.
  9953. *
  9954. * @param {Layers} layers - The layers to test.
  9955. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9956. */
  9957. test( layers ) {
  9958. return ( this.mask & layers.mask ) !== 0;
  9959. }
  9960. /**
  9961. * Returns `true` if the given layer is enabled.
  9962. *
  9963. * @param {number} layer - The layer to test.
  9964. * @return {boolean } Whether the given layer is enabled or not.
  9965. */
  9966. isEnabled( layer ) {
  9967. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  9968. }
  9969. }
  9970. let _object3DId = 0;
  9971. const _v1$4 = /*@__PURE__*/ new Vector3();
  9972. const _q1 = /*@__PURE__*/ new Quaternion();
  9973. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9974. const _target = /*@__PURE__*/ new Vector3();
  9975. const _position$3 = /*@__PURE__*/ new Vector3();
  9976. const _scale$2 = /*@__PURE__*/ new Vector3();
  9977. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  9978. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  9979. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  9980. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  9981. /**
  9982. * Fires when the object has been added to its parent object.
  9983. *
  9984. * @event Object3D#added
  9985. * @type {Object}
  9986. */
  9987. const _addedEvent = { type: 'added' };
  9988. /**
  9989. * Fires when the object has been removed from its parent object.
  9990. *
  9991. * @event Object3D#removed
  9992. * @type {Object}
  9993. */
  9994. const _removedEvent = { type: 'removed' };
  9995. /**
  9996. * Fires when a new child object has been added.
  9997. *
  9998. * @event Object3D#childadded
  9999. * @type {Object}
  10000. */
  10001. const _childaddedEvent = { type: 'childadded', child: null };
  10002. /**
  10003. * Fires when a child object has been removed.
  10004. *
  10005. * @event Object3D#childremoved
  10006. * @type {Object}
  10007. */
  10008. const _childremovedEvent = { type: 'childremoved', child: null };
  10009. /**
  10010. * This is the base class for most objects in three.js and provides a set of
  10011. * properties and methods for manipulating objects in 3D space.
  10012. *
  10013. * @augments EventDispatcher
  10014. */
  10015. class Object3D extends EventDispatcher {
  10016. /**
  10017. * Constructs a new 3D object.
  10018. */
  10019. constructor() {
  10020. super();
  10021. /**
  10022. * This flag can be used for type testing.
  10023. *
  10024. * @type {boolean}
  10025. * @readonly
  10026. * @default true
  10027. */
  10028. this.isObject3D = true;
  10029. /**
  10030. * The ID of the 3D object.
  10031. *
  10032. * @name Object3D#id
  10033. * @type {number}
  10034. * @readonly
  10035. */
  10036. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10037. /**
  10038. * The UUID of the 3D object.
  10039. *
  10040. * @type {string}
  10041. * @readonly
  10042. */
  10043. this.uuid = generateUUID();
  10044. /**
  10045. * The name of the 3D object.
  10046. *
  10047. * @type {string}
  10048. */
  10049. this.name = '';
  10050. /**
  10051. * The type property is used for detecting the object type
  10052. * in context of serialization/deserialization.
  10053. *
  10054. * @type {string}
  10055. * @readonly
  10056. */
  10057. this.type = 'Object3D';
  10058. /**
  10059. * A reference to the parent object.
  10060. *
  10061. * @type {?Object3D}
  10062. * @default null
  10063. */
  10064. this.parent = null;
  10065. /**
  10066. * An array holding the child 3D objects of this instance.
  10067. *
  10068. * @type {Array<Object3D>}
  10069. */
  10070. this.children = [];
  10071. /**
  10072. * Defines the `up` direction of the 3D object which influences
  10073. * the orientation via methods like {@link Object3D#lookAt}.
  10074. *
  10075. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10076. *
  10077. * @type {Vector3}
  10078. */
  10079. this.up = Object3D.DEFAULT_UP.clone();
  10080. const position = new Vector3();
  10081. const rotation = new Euler();
  10082. const quaternion = new Quaternion();
  10083. const scale = new Vector3( 1, 1, 1 );
  10084. function onRotationChange() {
  10085. quaternion.setFromEuler( rotation, false );
  10086. }
  10087. function onQuaternionChange() {
  10088. rotation.setFromQuaternion( quaternion, undefined, false );
  10089. }
  10090. rotation._onChange( onRotationChange );
  10091. quaternion._onChange( onQuaternionChange );
  10092. Object.defineProperties( this, {
  10093. /**
  10094. * Represents the object's local position.
  10095. *
  10096. * @name Object3D#position
  10097. * @type {Vector3}
  10098. * @default (0,0,0)
  10099. */
  10100. position: {
  10101. configurable: true,
  10102. enumerable: true,
  10103. value: position
  10104. },
  10105. /**
  10106. * Represents the object's local rotation as Euler angles, in radians.
  10107. *
  10108. * @name Object3D#rotation
  10109. * @type {Euler}
  10110. * @default (0,0,0)
  10111. */
  10112. rotation: {
  10113. configurable: true,
  10114. enumerable: true,
  10115. value: rotation
  10116. },
  10117. /**
  10118. * Represents the object's local rotation as Quaternions.
  10119. *
  10120. * @name Object3D#quaternion
  10121. * @type {Quaternion}
  10122. */
  10123. quaternion: {
  10124. configurable: true,
  10125. enumerable: true,
  10126. value: quaternion
  10127. },
  10128. /**
  10129. * Represents the object's local scale.
  10130. *
  10131. * @name Object3D#scale
  10132. * @type {Vector3}
  10133. * @default (1,1,1)
  10134. */
  10135. scale: {
  10136. configurable: true,
  10137. enumerable: true,
  10138. value: scale
  10139. },
  10140. /**
  10141. * Represents the object's model-view matrix.
  10142. *
  10143. * @name Object3D#modelViewMatrix
  10144. * @type {Matrix4}
  10145. */
  10146. modelViewMatrix: {
  10147. value: new Matrix4()
  10148. },
  10149. /**
  10150. * Represents the object's normal matrix.
  10151. *
  10152. * @name Object3D#normalMatrix
  10153. * @type {Matrix3}
  10154. */
  10155. normalMatrix: {
  10156. value: new Matrix3()
  10157. }
  10158. } );
  10159. /**
  10160. * Represents the object's transformation matrix in local space.
  10161. *
  10162. * @type {Matrix4}
  10163. */
  10164. this.matrix = new Matrix4();
  10165. /**
  10166. * Represents the object's transformation matrix in world space.
  10167. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10168. *
  10169. * @type {Matrix4}
  10170. */
  10171. this.matrixWorld = new Matrix4();
  10172. /**
  10173. * When set to `true`, the engine automatically computes the local matrix from position,
  10174. * rotation and scale every frame.
  10175. *
  10176. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10177. *
  10178. * @type {boolean}
  10179. * @default true
  10180. */
  10181. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10182. /**
  10183. * When set to `true`, the engine automatically computes the world matrix from the current local
  10184. * matrix and the object's transformation hierarchy.
  10185. *
  10186. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10187. *
  10188. * @type {boolean}
  10189. * @default true
  10190. */
  10191. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10192. /**
  10193. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10194. * to `false`.
  10195. *
  10196. * @type {boolean}
  10197. * @default false
  10198. */
  10199. this.matrixWorldNeedsUpdate = false;
  10200. /**
  10201. * The layer membership of the 3D object. The 3D object is only visible if it has
  10202. * at least one layer in common with the camera in use. This property can also be
  10203. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10204. *
  10205. * @type {Layers}
  10206. */
  10207. this.layers = new Layers();
  10208. /**
  10209. * When set to `true`, the 3D object gets rendered.
  10210. *
  10211. * @type {boolean}
  10212. * @default true
  10213. */
  10214. this.visible = true;
  10215. /**
  10216. * When set to `true`, the 3D object gets rendered into shadow maps.
  10217. *
  10218. * @type {boolean}
  10219. * @default false
  10220. */
  10221. this.castShadow = false;
  10222. /**
  10223. * When set to `true`, the 3D object is affected by shadows in the scene.
  10224. *
  10225. * @type {boolean}
  10226. * @default false
  10227. */
  10228. this.receiveShadow = false;
  10229. /**
  10230. * When set to `true`, the 3D object is honored by view frustum culling.
  10231. *
  10232. * @type {boolean}
  10233. * @default true
  10234. */
  10235. this.frustumCulled = true;
  10236. /**
  10237. * This value allows the default rendering order of scene graph objects to be
  10238. * overridden although opaque and transparent objects remain sorted independently.
  10239. * When this property is set for an instance of {@link Group},all descendants
  10240. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10241. * render order.
  10242. *
  10243. * @type {number}
  10244. * @default 0
  10245. */
  10246. this.renderOrder = 0;
  10247. /**
  10248. * An array holding the animation clips of the 3D object.
  10249. *
  10250. * @type {Array<AnimationClip>}
  10251. */
  10252. this.animations = [];
  10253. /**
  10254. * Custom depth material to be used when rendering to the depth map. Can only be used
  10255. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10256. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10257. * material for proper shadows.
  10258. *
  10259. * Only relevant in context of {@link WebGLRenderer}.
  10260. *
  10261. * @type {(Material|undefined)}
  10262. * @default undefined
  10263. */
  10264. this.customDepthMaterial = undefined;
  10265. /**
  10266. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10267. *
  10268. * Only relevant in context of {@link WebGLRenderer}.
  10269. *
  10270. * @type {(Material|undefined)}
  10271. * @default undefined
  10272. */
  10273. this.customDistanceMaterial = undefined;
  10274. /**
  10275. * An object that can be used to store custom data about the 3D object. It
  10276. * should not hold references to functions as these will not be cloned.
  10277. *
  10278. * @type {Object}
  10279. */
  10280. this.userData = {};
  10281. }
  10282. /**
  10283. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10284. *
  10285. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10286. * @param {Object3D} object - The 3D object.
  10287. * @param {Camera} camera - The camera that is used to render the scene.
  10288. * @param {Camera} shadowCamera - The shadow camera.
  10289. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10290. * @param {Material} depthMaterial - The depth material.
  10291. * @param {Object} group - The geometry group data.
  10292. */
  10293. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10294. /**
  10295. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10296. *
  10297. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10298. * @param {Object3D} object - The 3D object.
  10299. * @param {Camera} camera - The camera that is used to render the scene.
  10300. * @param {Camera} shadowCamera - The shadow camera.
  10301. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10302. * @param {Material} depthMaterial - The depth material.
  10303. * @param {Object} group - The geometry group data.
  10304. */
  10305. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10306. /**
  10307. * A callback that is executed immediately before a 3D object is rendered.
  10308. *
  10309. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10310. * @param {Object3D} object - The 3D object.
  10311. * @param {Camera} camera - The camera that is used to render the scene.
  10312. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10313. * @param {Material} material - The 3D object's material.
  10314. * @param {Object} group - The geometry group data.
  10315. */
  10316. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10317. /**
  10318. * A callback that is executed immediately after a 3D object is rendered.
  10319. *
  10320. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10321. * @param {Object3D} object - The 3D object.
  10322. * @param {Camera} camera - The camera that is used to render the scene.
  10323. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10324. * @param {Material} material - The 3D object's material.
  10325. * @param {Object} group - The geometry group data.
  10326. */
  10327. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10328. /**
  10329. * Applies the given transformation matrix to the object and updates the object's position,
  10330. * rotation and scale.
  10331. *
  10332. * @param {Matrix4} matrix - The transformation matrix.
  10333. */
  10334. applyMatrix4( matrix ) {
  10335. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10336. this.matrix.premultiply( matrix );
  10337. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10338. }
  10339. /**
  10340. * Applies a rotation represented by given the quaternion to the 3D object.
  10341. *
  10342. * @param {Quaternion} q - The quaternion.
  10343. * @return {Object3D} A reference to this instance.
  10344. */
  10345. applyQuaternion( q ) {
  10346. this.quaternion.premultiply( q );
  10347. return this;
  10348. }
  10349. /**
  10350. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10351. *
  10352. * @param {Vector3} axis - The (normalized) axis vector.
  10353. * @param {number} angle - The angle in radians.
  10354. */
  10355. setRotationFromAxisAngle( axis, angle ) {
  10356. // assumes axis is normalized
  10357. this.quaternion.setFromAxisAngle( axis, angle );
  10358. }
  10359. /**
  10360. * Sets the given rotation represented as Euler angles to the 3D object.
  10361. *
  10362. * @param {Euler} euler - The Euler angles.
  10363. */
  10364. setRotationFromEuler( euler ) {
  10365. this.quaternion.setFromEuler( euler, true );
  10366. }
  10367. /**
  10368. * Sets the given rotation represented as rotation matrix to the 3D object.
  10369. *
  10370. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10371. * a pure rotation matrix (i.e, unscaled).
  10372. */
  10373. setRotationFromMatrix( m ) {
  10374. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10375. this.quaternion.setFromRotationMatrix( m );
  10376. }
  10377. /**
  10378. * Sets the given rotation represented as a Quaternion to the 3D object.
  10379. *
  10380. * @param {Quaternion} q - The Quaternion
  10381. */
  10382. setRotationFromQuaternion( q ) {
  10383. // assumes q is normalized
  10384. this.quaternion.copy( q );
  10385. }
  10386. /**
  10387. * Rotates the 3D object along an axis in local space.
  10388. *
  10389. * @param {Vector3} axis - The (normalized) axis vector.
  10390. * @param {number} angle - The angle in radians.
  10391. * @return {Object3D} A reference to this instance.
  10392. */
  10393. rotateOnAxis( axis, angle ) {
  10394. // rotate object on axis in object space
  10395. // axis is assumed to be normalized
  10396. _q1.setFromAxisAngle( axis, angle );
  10397. this.quaternion.multiply( _q1 );
  10398. return this;
  10399. }
  10400. /**
  10401. * Rotates the 3D object along an axis in world space.
  10402. *
  10403. * @param {Vector3} axis - The (normalized) axis vector.
  10404. * @param {number} angle - The angle in radians.
  10405. * @return {Object3D} A reference to this instance.
  10406. */
  10407. rotateOnWorldAxis( axis, angle ) {
  10408. // rotate object on axis in world space
  10409. // axis is assumed to be normalized
  10410. // method assumes no rotated parent
  10411. _q1.setFromAxisAngle( axis, angle );
  10412. this.quaternion.premultiply( _q1 );
  10413. return this;
  10414. }
  10415. /**
  10416. * Rotates the 3D object around its X axis in local space.
  10417. *
  10418. * @param {number} angle - The angle in radians.
  10419. * @return {Object3D} A reference to this instance.
  10420. */
  10421. rotateX( angle ) {
  10422. return this.rotateOnAxis( _xAxis, angle );
  10423. }
  10424. /**
  10425. * Rotates the 3D object around its Y axis in local space.
  10426. *
  10427. * @param {number} angle - The angle in radians.
  10428. * @return {Object3D} A reference to this instance.
  10429. */
  10430. rotateY( angle ) {
  10431. return this.rotateOnAxis( _yAxis, angle );
  10432. }
  10433. /**
  10434. * Rotates the 3D object around its Z axis in local space.
  10435. *
  10436. * @param {number} angle - The angle in radians.
  10437. * @return {Object3D} A reference to this instance.
  10438. */
  10439. rotateZ( angle ) {
  10440. return this.rotateOnAxis( _zAxis, angle );
  10441. }
  10442. /**
  10443. * Translate the 3D object by a distance along the given axis in local space.
  10444. *
  10445. * @param {Vector3} axis - The (normalized) axis vector.
  10446. * @param {number} distance - The distance in world units.
  10447. * @return {Object3D} A reference to this instance.
  10448. */
  10449. translateOnAxis( axis, distance ) {
  10450. // translate object by distance along axis in object space
  10451. // axis is assumed to be normalized
  10452. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10453. this.position.add( _v1$4.multiplyScalar( distance ) );
  10454. return this;
  10455. }
  10456. /**
  10457. * Translate the 3D object by a distance along its X-axis in local space.
  10458. *
  10459. * @param {number} distance - The distance in world units.
  10460. * @return {Object3D} A reference to this instance.
  10461. */
  10462. translateX( distance ) {
  10463. return this.translateOnAxis( _xAxis, distance );
  10464. }
  10465. /**
  10466. * Translate the 3D object by a distance along its Y-axis in local space.
  10467. *
  10468. * @param {number} distance - The distance in world units.
  10469. * @return {Object3D} A reference to this instance.
  10470. */
  10471. translateY( distance ) {
  10472. return this.translateOnAxis( _yAxis, distance );
  10473. }
  10474. /**
  10475. * Translate the 3D object by a distance along its Z-axis in local space.
  10476. *
  10477. * @param {number} distance - The distance in world units.
  10478. * @return {Object3D} A reference to this instance.
  10479. */
  10480. translateZ( distance ) {
  10481. return this.translateOnAxis( _zAxis, distance );
  10482. }
  10483. /**
  10484. * Converts the given vector from this 3D object's local space to world space.
  10485. *
  10486. * @param {Vector3} vector - The vector to convert.
  10487. * @return {Vector3} The converted vector.
  10488. */
  10489. localToWorld( vector ) {
  10490. this.updateWorldMatrix( true, false );
  10491. return vector.applyMatrix4( this.matrixWorld );
  10492. }
  10493. /**
  10494. * Converts the given vector from this 3D object's word space to local space.
  10495. *
  10496. * @param {Vector3} vector - The vector to convert.
  10497. * @return {Vector3} The converted vector.
  10498. */
  10499. worldToLocal( vector ) {
  10500. this.updateWorldMatrix( true, false );
  10501. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  10502. }
  10503. /**
  10504. * Rotates the object to face a point in world space.
  10505. *
  10506. * This method does not support objects having non-uniformly-scaled parent(s).
  10507. *
  10508. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10509. * @param {number} [y] - The y coordinate in world space.
  10510. * @param {number} [z] - The z coordinate in world space.
  10511. */
  10512. lookAt( x, y, z ) {
  10513. // This method does not support objects having non-uniformly-scaled parent(s)
  10514. if ( x.isVector3 ) {
  10515. _target.copy( x );
  10516. } else {
  10517. _target.set( x, y, z );
  10518. }
  10519. const parent = this.parent;
  10520. this.updateWorldMatrix( true, false );
  10521. _position$3.setFromMatrixPosition( this.matrixWorld );
  10522. if ( this.isCamera || this.isLight ) {
  10523. _m1$1.lookAt( _position$3, _target, this.up );
  10524. } else {
  10525. _m1$1.lookAt( _target, _position$3, this.up );
  10526. }
  10527. this.quaternion.setFromRotationMatrix( _m1$1 );
  10528. if ( parent ) {
  10529. _m1$1.extractRotation( parent.matrixWorld );
  10530. _q1.setFromRotationMatrix( _m1$1 );
  10531. this.quaternion.premultiply( _q1.invert() );
  10532. }
  10533. }
  10534. /**
  10535. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10536. * objects may be added. Any current parent on an object passed in here will be
  10537. * removed, since an object can have at most one parent.
  10538. *
  10539. * @fires Object3D#added
  10540. * @fires Object3D#childadded
  10541. * @param {Object3D} object - The 3D object to add.
  10542. * @return {Object3D} A reference to this instance.
  10543. */
  10544. add( object ) {
  10545. if ( arguments.length > 1 ) {
  10546. for ( let i = 0; i < arguments.length; i ++ ) {
  10547. this.add( arguments[ i ] );
  10548. }
  10549. return this;
  10550. }
  10551. if ( object === this ) {
  10552. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  10553. return this;
  10554. }
  10555. if ( object && object.isObject3D ) {
  10556. object.removeFromParent();
  10557. object.parent = this;
  10558. this.children.push( object );
  10559. object.dispatchEvent( _addedEvent );
  10560. _childaddedEvent.child = object;
  10561. this.dispatchEvent( _childaddedEvent );
  10562. _childaddedEvent.child = null;
  10563. } else {
  10564. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  10565. }
  10566. return this;
  10567. }
  10568. /**
  10569. * Removes the given 3D object as child from this 3D object.
  10570. * An arbitrary number of objects may be removed.
  10571. *
  10572. * @fires Object3D#removed
  10573. * @fires Object3D#childremoved
  10574. * @param {Object3D} object - The 3D object to remove.
  10575. * @return {Object3D} A reference to this instance.
  10576. */
  10577. remove( object ) {
  10578. if ( arguments.length > 1 ) {
  10579. for ( let i = 0; i < arguments.length; i ++ ) {
  10580. this.remove( arguments[ i ] );
  10581. }
  10582. return this;
  10583. }
  10584. const index = this.children.indexOf( object );
  10585. if ( index !== -1 ) {
  10586. object.parent = null;
  10587. this.children.splice( index, 1 );
  10588. object.dispatchEvent( _removedEvent );
  10589. _childremovedEvent.child = object;
  10590. this.dispatchEvent( _childremovedEvent );
  10591. _childremovedEvent.child = null;
  10592. }
  10593. return this;
  10594. }
  10595. /**
  10596. * Removes this 3D object from its current parent.
  10597. *
  10598. * @fires Object3D#removed
  10599. * @fires Object3D#childremoved
  10600. * @return {Object3D} A reference to this instance.
  10601. */
  10602. removeFromParent() {
  10603. const parent = this.parent;
  10604. if ( parent !== null ) {
  10605. parent.remove( this );
  10606. }
  10607. return this;
  10608. }
  10609. /**
  10610. * Removes all child objects.
  10611. *
  10612. * @fires Object3D#removed
  10613. * @fires Object3D#childremoved
  10614. * @return {Object3D} A reference to this instance.
  10615. */
  10616. clear() {
  10617. return this.remove( ... this.children );
  10618. }
  10619. /**
  10620. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10621. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10622. *
  10623. * @fires Object3D#added
  10624. * @fires Object3D#childadded
  10625. * @param {Object3D} object - The 3D object to attach.
  10626. * @return {Object3D} A reference to this instance.
  10627. */
  10628. attach( object ) {
  10629. // adds object as a child of this, while maintaining the object's world transform
  10630. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10631. this.updateWorldMatrix( true, false );
  10632. _m1$1.copy( this.matrixWorld ).invert();
  10633. if ( object.parent !== null ) {
  10634. object.parent.updateWorldMatrix( true, false );
  10635. _m1$1.multiply( object.parent.matrixWorld );
  10636. }
  10637. object.applyMatrix4( _m1$1 );
  10638. object.removeFromParent();
  10639. object.parent = this;
  10640. this.children.push( object );
  10641. object.updateWorldMatrix( false, true );
  10642. object.dispatchEvent( _addedEvent );
  10643. _childaddedEvent.child = object;
  10644. this.dispatchEvent( _childaddedEvent );
  10645. _childaddedEvent.child = null;
  10646. return this;
  10647. }
  10648. /**
  10649. * Searches through the 3D object and its children, starting with the 3D object
  10650. * itself, and returns the first with a matching ID.
  10651. *
  10652. * @param {number} id - The id.
  10653. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10654. */
  10655. getObjectById( id ) {
  10656. return this.getObjectByProperty( 'id', id );
  10657. }
  10658. /**
  10659. * Searches through the 3D object and its children, starting with the 3D object
  10660. * itself, and returns the first with a matching name.
  10661. *
  10662. * @param {string} name - The name.
  10663. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10664. */
  10665. getObjectByName( name ) {
  10666. return this.getObjectByProperty( 'name', name );
  10667. }
  10668. /**
  10669. * Searches through the 3D object and its children, starting with the 3D object
  10670. * itself, and returns the first with a matching property value.
  10671. *
  10672. * @param {string} name - The name of the property.
  10673. * @param {any} value - The value.
  10674. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10675. */
  10676. getObjectByProperty( name, value ) {
  10677. if ( this[ name ] === value ) return this;
  10678. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10679. const child = this.children[ i ];
  10680. const object = child.getObjectByProperty( name, value );
  10681. if ( object !== undefined ) {
  10682. return object;
  10683. }
  10684. }
  10685. return undefined;
  10686. }
  10687. /**
  10688. * Searches through the 3D object and its children, starting with the 3D object
  10689. * itself, and returns all 3D objects with a matching property value.
  10690. *
  10691. * @param {string} name - The name of the property.
  10692. * @param {any} value - The value.
  10693. * @param {Array<Object3D>} result - The method stores the result in this array.
  10694. * @return {Array<Object3D>} The found 3D objects.
  10695. */
  10696. getObjectsByProperty( name, value, result = [] ) {
  10697. if ( this[ name ] === value ) result.push( this );
  10698. const children = this.children;
  10699. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10700. children[ i ].getObjectsByProperty( name, value, result );
  10701. }
  10702. return result;
  10703. }
  10704. /**
  10705. * Returns a vector representing the position of the 3D object in world space.
  10706. *
  10707. * @param {Vector3} target - The target vector the result is stored to.
  10708. * @return {Vector3} The 3D object's position in world space.
  10709. */
  10710. getWorldPosition( target ) {
  10711. this.updateWorldMatrix( true, false );
  10712. return target.setFromMatrixPosition( this.matrixWorld );
  10713. }
  10714. /**
  10715. * Returns a Quaternion representing the position of the 3D object in world space.
  10716. *
  10717. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10718. * @return {Quaternion} The 3D object's rotation in world space.
  10719. */
  10720. getWorldQuaternion( target ) {
  10721. this.updateWorldMatrix( true, false );
  10722. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10723. return target;
  10724. }
  10725. /**
  10726. * Returns a vector representing the scale of the 3D object in world space.
  10727. *
  10728. * @param {Vector3} target - The target vector the result is stored to.
  10729. * @return {Vector3} The 3D object's scale in world space.
  10730. */
  10731. getWorldScale( target ) {
  10732. this.updateWorldMatrix( true, false );
  10733. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10734. return target;
  10735. }
  10736. /**
  10737. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10738. *
  10739. * @param {Vector3} target - The target vector the result is stored to.
  10740. * @return {Vector3} The 3D object's direction in world space.
  10741. */
  10742. getWorldDirection( target ) {
  10743. this.updateWorldMatrix( true, false );
  10744. const e = this.matrixWorld.elements;
  10745. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10746. }
  10747. /**
  10748. * Abstract method to get intersections between a casted ray and this
  10749. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10750. * implement this method in order to use raycasting.
  10751. *
  10752. * @abstract
  10753. * @param {Raycaster} raycaster - The raycaster.
  10754. * @param {Array<Object>} intersects - An array holding the result of the method.
  10755. */
  10756. raycast( /* raycaster, intersects */ ) {}
  10757. /**
  10758. * Executes the callback on this 3D object and all descendants.
  10759. *
  10760. * Note: Modifying the scene graph inside the callback is discouraged.
  10761. *
  10762. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10763. */
  10764. traverse( callback ) {
  10765. callback( this );
  10766. const children = this.children;
  10767. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10768. children[ i ].traverse( callback );
  10769. }
  10770. }
  10771. /**
  10772. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10773. * Descendants of invisible 3D objects are not traversed.
  10774. *
  10775. * Note: Modifying the scene graph inside the callback is discouraged.
  10776. *
  10777. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10778. */
  10779. traverseVisible( callback ) {
  10780. if ( this.visible === false ) return;
  10781. callback( this );
  10782. const children = this.children;
  10783. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10784. children[ i ].traverseVisible( callback );
  10785. }
  10786. }
  10787. /**
  10788. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10789. *
  10790. * Note: Modifying the scene graph inside the callback is discouraged.
  10791. *
  10792. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10793. */
  10794. traverseAncestors( callback ) {
  10795. const parent = this.parent;
  10796. if ( parent !== null ) {
  10797. callback( parent );
  10798. parent.traverseAncestors( callback );
  10799. }
  10800. }
  10801. /**
  10802. * Updates the transformation matrix in local space by computing it from the current
  10803. * position, rotation and scale values.
  10804. */
  10805. updateMatrix() {
  10806. this.matrix.compose( this.position, this.quaternion, this.scale );
  10807. this.matrixWorldNeedsUpdate = true;
  10808. }
  10809. /**
  10810. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10811. *
  10812. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10813. * local space. The computation of the local and world matrix can be controlled with the
  10814. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10815. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10816. *
  10817. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10818. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10819. */
  10820. updateMatrixWorld( force ) {
  10821. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10822. if ( this.matrixWorldNeedsUpdate || force ) {
  10823. if ( this.matrixWorldAutoUpdate === true ) {
  10824. if ( this.parent === null ) {
  10825. this.matrixWorld.copy( this.matrix );
  10826. } else {
  10827. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10828. }
  10829. }
  10830. this.matrixWorldNeedsUpdate = false;
  10831. force = true;
  10832. }
  10833. // make sure descendants are updated if required
  10834. const children = this.children;
  10835. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10836. const child = children[ i ];
  10837. child.updateMatrixWorld( force );
  10838. }
  10839. }
  10840. /**
  10841. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10842. * update of ancestor and descendant nodes.
  10843. *
  10844. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10845. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10846. */
  10847. updateWorldMatrix( updateParents, updateChildren ) {
  10848. const parent = this.parent;
  10849. if ( updateParents === true && parent !== null ) {
  10850. parent.updateWorldMatrix( true, false );
  10851. }
  10852. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10853. if ( this.matrixWorldAutoUpdate === true ) {
  10854. if ( this.parent === null ) {
  10855. this.matrixWorld.copy( this.matrix );
  10856. } else {
  10857. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10858. }
  10859. }
  10860. // make sure descendants are updated
  10861. if ( updateChildren === true ) {
  10862. const children = this.children;
  10863. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10864. const child = children[ i ];
  10865. child.updateWorldMatrix( false, true );
  10866. }
  10867. }
  10868. }
  10869. /**
  10870. * Serializes the 3D object into JSON.
  10871. *
  10872. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10873. * @return {Object} A JSON object representing the serialized 3D object.
  10874. * @see {@link ObjectLoader#parse}
  10875. */
  10876. toJSON( meta ) {
  10877. // meta is a string when called from JSON.stringify
  10878. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10879. const output = {};
  10880. // meta is a hash used to collect geometries, materials.
  10881. // not providing it implies that this is the root object
  10882. // being serialized.
  10883. if ( isRootObject ) {
  10884. // initialize meta obj
  10885. meta = {
  10886. geometries: {},
  10887. materials: {},
  10888. textures: {},
  10889. images: {},
  10890. shapes: {},
  10891. skeletons: {},
  10892. animations: {},
  10893. nodes: {}
  10894. };
  10895. output.metadata = {
  10896. version: 4.7,
  10897. type: 'Object',
  10898. generator: 'Object3D.toJSON'
  10899. };
  10900. }
  10901. // standard Object3D serialization
  10902. const object = {};
  10903. object.uuid = this.uuid;
  10904. object.type = this.type;
  10905. if ( this.name !== '' ) object.name = this.name;
  10906. if ( this.castShadow === true ) object.castShadow = true;
  10907. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10908. if ( this.visible === false ) object.visible = false;
  10909. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10910. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10911. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10912. object.layers = this.layers.mask;
  10913. object.matrix = this.matrix.toArray();
  10914. object.up = this.up.toArray();
  10915. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10916. // object specific properties
  10917. if ( this.isInstancedMesh ) {
  10918. object.type = 'InstancedMesh';
  10919. object.count = this.count;
  10920. object.instanceMatrix = this.instanceMatrix.toJSON();
  10921. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10922. }
  10923. if ( this.isBatchedMesh ) {
  10924. object.type = 'BatchedMesh';
  10925. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10926. object.sortObjects = this.sortObjects;
  10927. object.drawRanges = this._drawRanges;
  10928. object.reservedRanges = this._reservedRanges;
  10929. object.geometryInfo = this._geometryInfo.map( info => ( {
  10930. ...info,
  10931. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10932. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10933. } ) );
  10934. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10935. object.availableInstanceIds = this._availableInstanceIds.slice();
  10936. object.availableGeometryIds = this._availableGeometryIds.slice();
  10937. object.nextIndexStart = this._nextIndexStart;
  10938. object.nextVertexStart = this._nextVertexStart;
  10939. object.geometryCount = this._geometryCount;
  10940. object.maxInstanceCount = this._maxInstanceCount;
  10941. object.maxVertexCount = this._maxVertexCount;
  10942. object.maxIndexCount = this._maxIndexCount;
  10943. object.geometryInitialized = this._geometryInitialized;
  10944. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10945. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10946. if ( this._colorsTexture !== null ) {
  10947. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10948. }
  10949. if ( this.boundingSphere !== null ) {
  10950. object.boundingSphere = this.boundingSphere.toJSON();
  10951. }
  10952. if ( this.boundingBox !== null ) {
  10953. object.boundingBox = this.boundingBox.toJSON();
  10954. }
  10955. }
  10956. //
  10957. function serialize( library, element ) {
  10958. if ( library[ element.uuid ] === undefined ) {
  10959. library[ element.uuid ] = element.toJSON( meta );
  10960. }
  10961. return element.uuid;
  10962. }
  10963. if ( this.isScene ) {
  10964. if ( this.background ) {
  10965. if ( this.background.isColor ) {
  10966. object.background = this.background.toJSON();
  10967. } else if ( this.background.isTexture ) {
  10968. object.background = this.background.toJSON( meta ).uuid;
  10969. }
  10970. }
  10971. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  10972. object.environment = this.environment.toJSON( meta ).uuid;
  10973. }
  10974. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  10975. object.geometry = serialize( meta.geometries, this.geometry );
  10976. const parameters = this.geometry.parameters;
  10977. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10978. const shapes = parameters.shapes;
  10979. if ( Array.isArray( shapes ) ) {
  10980. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  10981. const shape = shapes[ i ];
  10982. serialize( meta.shapes, shape );
  10983. }
  10984. } else {
  10985. serialize( meta.shapes, shapes );
  10986. }
  10987. }
  10988. }
  10989. if ( this.isSkinnedMesh ) {
  10990. object.bindMode = this.bindMode;
  10991. object.bindMatrix = this.bindMatrix.toArray();
  10992. if ( this.skeleton !== undefined ) {
  10993. serialize( meta.skeletons, this.skeleton );
  10994. object.skeleton = this.skeleton.uuid;
  10995. }
  10996. }
  10997. if ( this.material !== undefined ) {
  10998. if ( Array.isArray( this.material ) ) {
  10999. const uuids = [];
  11000. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11001. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11002. }
  11003. object.material = uuids;
  11004. } else {
  11005. object.material = serialize( meta.materials, this.material );
  11006. }
  11007. }
  11008. //
  11009. if ( this.children.length > 0 ) {
  11010. object.children = [];
  11011. for ( let i = 0; i < this.children.length; i ++ ) {
  11012. object.children.push( this.children[ i ].toJSON( meta ).object );
  11013. }
  11014. }
  11015. //
  11016. if ( this.animations.length > 0 ) {
  11017. object.animations = [];
  11018. for ( let i = 0; i < this.animations.length; i ++ ) {
  11019. const animation = this.animations[ i ];
  11020. object.animations.push( serialize( meta.animations, animation ) );
  11021. }
  11022. }
  11023. if ( isRootObject ) {
  11024. const geometries = extractFromCache( meta.geometries );
  11025. const materials = extractFromCache( meta.materials );
  11026. const textures = extractFromCache( meta.textures );
  11027. const images = extractFromCache( meta.images );
  11028. const shapes = extractFromCache( meta.shapes );
  11029. const skeletons = extractFromCache( meta.skeletons );
  11030. const animations = extractFromCache( meta.animations );
  11031. const nodes = extractFromCache( meta.nodes );
  11032. if ( geometries.length > 0 ) output.geometries = geometries;
  11033. if ( materials.length > 0 ) output.materials = materials;
  11034. if ( textures.length > 0 ) output.textures = textures;
  11035. if ( images.length > 0 ) output.images = images;
  11036. if ( shapes.length > 0 ) output.shapes = shapes;
  11037. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11038. if ( animations.length > 0 ) output.animations = animations;
  11039. if ( nodes.length > 0 ) output.nodes = nodes;
  11040. }
  11041. output.object = object;
  11042. return output;
  11043. // extract data from the cache hash
  11044. // remove metadata on each item
  11045. // and return as array
  11046. function extractFromCache( cache ) {
  11047. const values = [];
  11048. for ( const key in cache ) {
  11049. const data = cache[ key ];
  11050. delete data.metadata;
  11051. values.push( data );
  11052. }
  11053. return values;
  11054. }
  11055. }
  11056. /**
  11057. * Returns a new 3D object with copied values from this instance.
  11058. *
  11059. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11060. * @return {Object3D} A clone of this instance.
  11061. */
  11062. clone( recursive ) {
  11063. return new this.constructor().copy( this, recursive );
  11064. }
  11065. /**
  11066. * Copies the values of the given 3D object to this instance.
  11067. *
  11068. * @param {Object3D} source - The 3D object to copy.
  11069. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11070. * @return {Object3D} A reference to this instance.
  11071. */
  11072. copy( source, recursive = true ) {
  11073. this.name = source.name;
  11074. this.up.copy( source.up );
  11075. this.position.copy( source.position );
  11076. this.rotation.order = source.rotation.order;
  11077. this.quaternion.copy( source.quaternion );
  11078. this.scale.copy( source.scale );
  11079. this.matrix.copy( source.matrix );
  11080. this.matrixWorld.copy( source.matrixWorld );
  11081. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11082. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11083. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11084. this.layers.mask = source.layers.mask;
  11085. this.visible = source.visible;
  11086. this.castShadow = source.castShadow;
  11087. this.receiveShadow = source.receiveShadow;
  11088. this.frustumCulled = source.frustumCulled;
  11089. this.renderOrder = source.renderOrder;
  11090. this.animations = source.animations.slice();
  11091. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11092. if ( recursive === true ) {
  11093. for ( let i = 0; i < source.children.length; i ++ ) {
  11094. const child = source.children[ i ];
  11095. this.add( child.clone() );
  11096. }
  11097. }
  11098. return this;
  11099. }
  11100. }
  11101. /**
  11102. * The default up direction for objects, also used as the default
  11103. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11104. *
  11105. * @static
  11106. * @type {Vector3}
  11107. * @default (0,1,0)
  11108. */
  11109. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11110. /**
  11111. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11112. * newly created 3D objects.
  11113. *
  11114. * @static
  11115. * @type {boolean}
  11116. * @default true
  11117. */
  11118. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11119. /**
  11120. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11121. * newly created 3D objects.
  11122. *
  11123. * @static
  11124. * @type {boolean}
  11125. * @default true
  11126. */
  11127. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11128. const _v0$1 = /*@__PURE__*/ new Vector3();
  11129. const _v1$3 = /*@__PURE__*/ new Vector3();
  11130. const _v2$2 = /*@__PURE__*/ new Vector3();
  11131. const _v3$2 = /*@__PURE__*/ new Vector3();
  11132. const _vab = /*@__PURE__*/ new Vector3();
  11133. const _vac = /*@__PURE__*/ new Vector3();
  11134. const _vbc = /*@__PURE__*/ new Vector3();
  11135. const _vap = /*@__PURE__*/ new Vector3();
  11136. const _vbp = /*@__PURE__*/ new Vector3();
  11137. const _vcp = /*@__PURE__*/ new Vector3();
  11138. const _v40 = /*@__PURE__*/ new Vector4();
  11139. const _v41 = /*@__PURE__*/ new Vector4();
  11140. const _v42 = /*@__PURE__*/ new Vector4();
  11141. /**
  11142. * A geometric triangle as defined by three vectors representing its three corners.
  11143. */
  11144. class Triangle {
  11145. /**
  11146. * Constructs a new triangle.
  11147. *
  11148. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11149. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11150. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11151. */
  11152. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11153. /**
  11154. * The first corner of the triangle.
  11155. *
  11156. * @type {Vector3}
  11157. */
  11158. this.a = a;
  11159. /**
  11160. * The second corner of the triangle.
  11161. *
  11162. * @type {Vector3}
  11163. */
  11164. this.b = b;
  11165. /**
  11166. * The third corner of the triangle.
  11167. *
  11168. * @type {Vector3}
  11169. */
  11170. this.c = c;
  11171. }
  11172. /**
  11173. * Computes the normal vector of a triangle.
  11174. *
  11175. * @param {Vector3} a - The first corner of the triangle.
  11176. * @param {Vector3} b - The second corner of the triangle.
  11177. * @param {Vector3} c - The third corner of the triangle.
  11178. * @param {Vector3} target - The target vector that is used to store the method's result.
  11179. * @return {Vector3} The triangle's normal.
  11180. */
  11181. static getNormal( a, b, c, target ) {
  11182. target.subVectors( c, b );
  11183. _v0$1.subVectors( a, b );
  11184. target.cross( _v0$1 );
  11185. const targetLengthSq = target.lengthSq();
  11186. if ( targetLengthSq > 0 ) {
  11187. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11188. }
  11189. return target.set( 0, 0, 0 );
  11190. }
  11191. /**
  11192. * Computes a barycentric coordinates from the given vector.
  11193. * Returns `null` if the triangle is degenerate.
  11194. *
  11195. * @param {Vector3} point - A point in 3D space.
  11196. * @param {Vector3} a - The first corner of the triangle.
  11197. * @param {Vector3} b - The second corner of the triangle.
  11198. * @param {Vector3} c - The third corner of the triangle.
  11199. * @param {Vector3} target - The target vector that is used to store the method's result.
  11200. * @return {?Vector3} The barycentric coordinates for the given point
  11201. */
  11202. static getBarycoord( point, a, b, c, target ) {
  11203. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11204. _v0$1.subVectors( c, a );
  11205. _v1$3.subVectors( b, a );
  11206. _v2$2.subVectors( point, a );
  11207. const dot00 = _v0$1.dot( _v0$1 );
  11208. const dot01 = _v0$1.dot( _v1$3 );
  11209. const dot02 = _v0$1.dot( _v2$2 );
  11210. const dot11 = _v1$3.dot( _v1$3 );
  11211. const dot12 = _v1$3.dot( _v2$2 );
  11212. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11213. // collinear or singular triangle
  11214. if ( denom === 0 ) {
  11215. target.set( 0, 0, 0 );
  11216. return null;
  11217. }
  11218. const invDenom = 1 / denom;
  11219. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11220. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11221. // barycentric coordinates must always sum to 1
  11222. return target.set( 1 - u - v, v, u );
  11223. }
  11224. /**
  11225. * Returns `true` if the given point, when projected onto the plane of the
  11226. * triangle, lies within the triangle.
  11227. *
  11228. * @param {Vector3} point - The point in 3D space to test.
  11229. * @param {Vector3} a - The first corner of the triangle.
  11230. * @param {Vector3} b - The second corner of the triangle.
  11231. * @param {Vector3} c - The third corner of the triangle.
  11232. * @return {boolean} Whether the given point, when projected onto the plane of the
  11233. * triangle, lies within the triangle or not.
  11234. */
  11235. static containsPoint( point, a, b, c ) {
  11236. // if the triangle is degenerate then we can't contain a point
  11237. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11238. return false;
  11239. }
  11240. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11241. }
  11242. /**
  11243. * Computes the value barycentrically interpolated for the given point on the
  11244. * triangle. Returns `null` if the triangle is degenerate.
  11245. *
  11246. * @param {Vector3} point - Position of interpolated point.
  11247. * @param {Vector3} p1 - The first corner of the triangle.
  11248. * @param {Vector3} p2 - The second corner of the triangle.
  11249. * @param {Vector3} p3 - The third corner of the triangle.
  11250. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11251. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11252. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11253. * @param {Vector3} target - The target vector that is used to store the method's result.
  11254. * @return {?Vector3} The interpolated value.
  11255. */
  11256. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11257. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11258. target.x = 0;
  11259. target.y = 0;
  11260. if ( 'z' in target ) target.z = 0;
  11261. if ( 'w' in target ) target.w = 0;
  11262. return null;
  11263. }
  11264. target.setScalar( 0 );
  11265. target.addScaledVector( v1, _v3$2.x );
  11266. target.addScaledVector( v2, _v3$2.y );
  11267. target.addScaledVector( v3, _v3$2.z );
  11268. return target;
  11269. }
  11270. /**
  11271. * Computes the value barycentrically interpolated for the given attribute and indices.
  11272. *
  11273. * @param {BufferAttribute} attr - The attribute to interpolate.
  11274. * @param {number} i1 - Index of first vertex.
  11275. * @param {number} i2 - Index of second vertex.
  11276. * @param {number} i3 - Index of third vertex.
  11277. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11278. * @param {Vector3} target - The target vector that is used to store the method's result.
  11279. * @return {Vector3} The interpolated attribute value.
  11280. */
  11281. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11282. _v40.setScalar( 0 );
  11283. _v41.setScalar( 0 );
  11284. _v42.setScalar( 0 );
  11285. _v40.fromBufferAttribute( attr, i1 );
  11286. _v41.fromBufferAttribute( attr, i2 );
  11287. _v42.fromBufferAttribute( attr, i3 );
  11288. target.setScalar( 0 );
  11289. target.addScaledVector( _v40, barycoord.x );
  11290. target.addScaledVector( _v41, barycoord.y );
  11291. target.addScaledVector( _v42, barycoord.z );
  11292. return target;
  11293. }
  11294. /**
  11295. * Returns `true` if the triangle is oriented towards the given direction.
  11296. *
  11297. * @param {Vector3} a - The first corner of the triangle.
  11298. * @param {Vector3} b - The second corner of the triangle.
  11299. * @param {Vector3} c - The third corner of the triangle.
  11300. * @param {Vector3} direction - The (normalized) direction vector.
  11301. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11302. */
  11303. static isFrontFacing( a, b, c, direction ) {
  11304. _v0$1.subVectors( c, b );
  11305. _v1$3.subVectors( a, b );
  11306. // strictly front facing
  11307. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11308. }
  11309. /**
  11310. * Sets the triangle's vertices by copying the given values.
  11311. *
  11312. * @param {Vector3} a - The first corner of the triangle.
  11313. * @param {Vector3} b - The second corner of the triangle.
  11314. * @param {Vector3} c - The third corner of the triangle.
  11315. * @return {Triangle} A reference to this triangle.
  11316. */
  11317. set( a, b, c ) {
  11318. this.a.copy( a );
  11319. this.b.copy( b );
  11320. this.c.copy( c );
  11321. return this;
  11322. }
  11323. /**
  11324. * Sets the triangle's vertices by copying the given array values.
  11325. *
  11326. * @param {Array<Vector3>} points - An array with 3D points.
  11327. * @param {number} i0 - The array index representing the first corner of the triangle.
  11328. * @param {number} i1 - The array index representing the second corner of the triangle.
  11329. * @param {number} i2 - The array index representing the third corner of the triangle.
  11330. * @return {Triangle} A reference to this triangle.
  11331. */
  11332. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11333. this.a.copy( points[ i0 ] );
  11334. this.b.copy( points[ i1 ] );
  11335. this.c.copy( points[ i2 ] );
  11336. return this;
  11337. }
  11338. /**
  11339. * Sets the triangle's vertices by copying the given attribute values.
  11340. *
  11341. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11342. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11343. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11344. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11345. * @return {Triangle} A reference to this triangle.
  11346. */
  11347. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11348. this.a.fromBufferAttribute( attribute, i0 );
  11349. this.b.fromBufferAttribute( attribute, i1 );
  11350. this.c.fromBufferAttribute( attribute, i2 );
  11351. return this;
  11352. }
  11353. /**
  11354. * Returns a new triangle with copied values from this instance.
  11355. *
  11356. * @return {Triangle} A clone of this instance.
  11357. */
  11358. clone() {
  11359. return new this.constructor().copy( this );
  11360. }
  11361. /**
  11362. * Copies the values of the given triangle to this instance.
  11363. *
  11364. * @param {Triangle} triangle - The triangle to copy.
  11365. * @return {Triangle} A reference to this triangle.
  11366. */
  11367. copy( triangle ) {
  11368. this.a.copy( triangle.a );
  11369. this.b.copy( triangle.b );
  11370. this.c.copy( triangle.c );
  11371. return this;
  11372. }
  11373. /**
  11374. * Computes the area of the triangle.
  11375. *
  11376. * @return {number} The triangle's area.
  11377. */
  11378. getArea() {
  11379. _v0$1.subVectors( this.c, this.b );
  11380. _v1$3.subVectors( this.a, this.b );
  11381. return _v0$1.cross( _v1$3 ).length() * 0.5;
  11382. }
  11383. /**
  11384. * Computes the midpoint of the triangle.
  11385. *
  11386. * @param {Vector3} target - The target vector that is used to store the method's result.
  11387. * @return {Vector3} The triangle's midpoint.
  11388. */
  11389. getMidpoint( target ) {
  11390. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11391. }
  11392. /**
  11393. * Computes the normal of the triangle.
  11394. *
  11395. * @param {Vector3} target - The target vector that is used to store the method's result.
  11396. * @return {Vector3} The triangle's normal.
  11397. */
  11398. getNormal( target ) {
  11399. return Triangle.getNormal( this.a, this.b, this.c, target );
  11400. }
  11401. /**
  11402. * Computes a plane the triangle lies within.
  11403. *
  11404. * @param {Plane} target - The target vector that is used to store the method's result.
  11405. * @return {Plane} The plane the triangle lies within.
  11406. */
  11407. getPlane( target ) {
  11408. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11409. }
  11410. /**
  11411. * Computes a barycentric coordinates from the given vector.
  11412. * Returns `null` if the triangle is degenerate.
  11413. *
  11414. * @param {Vector3} point - A point in 3D space.
  11415. * @param {Vector3} target - The target vector that is used to store the method's result.
  11416. * @return {?Vector3} The barycentric coordinates for the given point
  11417. */
  11418. getBarycoord( point, target ) {
  11419. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11420. }
  11421. /**
  11422. * Computes the value barycentrically interpolated for the given point on the
  11423. * triangle. Returns `null` if the triangle is degenerate.
  11424. *
  11425. * @param {Vector3} point - Position of interpolated point.
  11426. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11427. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11428. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11429. * @param {Vector3} target - The target vector that is used to store the method's result.
  11430. * @return {?Vector3} The interpolated value.
  11431. */
  11432. getInterpolation( point, v1, v2, v3, target ) {
  11433. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11434. }
  11435. /**
  11436. * Returns `true` if the given point, when projected onto the plane of the
  11437. * triangle, lies within the triangle.
  11438. *
  11439. * @param {Vector3} point - The point in 3D space to test.
  11440. * @return {boolean} Whether the given point, when projected onto the plane of the
  11441. * triangle, lies within the triangle or not.
  11442. */
  11443. containsPoint( point ) {
  11444. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11445. }
  11446. /**
  11447. * Returns `true` if the triangle is oriented towards the given direction.
  11448. *
  11449. * @param {Vector3} direction - The (normalized) direction vector.
  11450. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11451. */
  11452. isFrontFacing( direction ) {
  11453. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11454. }
  11455. /**
  11456. * Returns `true` if this triangle intersects with the given box.
  11457. *
  11458. * @param {Box3} box - The box to intersect.
  11459. * @return {boolean} Whether this triangle intersects with the given box or not.
  11460. */
  11461. intersectsBox( box ) {
  11462. return box.intersectsTriangle( this );
  11463. }
  11464. /**
  11465. * Returns the closest point on the triangle to the given point.
  11466. *
  11467. * @param {Vector3} p - The point to compute the closest point for.
  11468. * @param {Vector3} target - The target vector that is used to store the method's result.
  11469. * @return {Vector3} The closest point on the triangle.
  11470. */
  11471. closestPointToPoint( p, target ) {
  11472. const a = this.a, b = this.b, c = this.c;
  11473. let v, w;
  11474. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11475. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11476. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11477. // basically, we're distinguishing which of the voronoi regions of the triangle
  11478. // the point lies in with the minimum amount of redundant computation.
  11479. _vab.subVectors( b, a );
  11480. _vac.subVectors( c, a );
  11481. _vap.subVectors( p, a );
  11482. const d1 = _vab.dot( _vap );
  11483. const d2 = _vac.dot( _vap );
  11484. if ( d1 <= 0 && d2 <= 0 ) {
  11485. // vertex region of A; barycentric coords (1, 0, 0)
  11486. return target.copy( a );
  11487. }
  11488. _vbp.subVectors( p, b );
  11489. const d3 = _vab.dot( _vbp );
  11490. const d4 = _vac.dot( _vbp );
  11491. if ( d3 >= 0 && d4 <= d3 ) {
  11492. // vertex region of B; barycentric coords (0, 1, 0)
  11493. return target.copy( b );
  11494. }
  11495. const vc = d1 * d4 - d3 * d2;
  11496. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11497. v = d1 / ( d1 - d3 );
  11498. // edge region of AB; barycentric coords (1-v, v, 0)
  11499. return target.copy( a ).addScaledVector( _vab, v );
  11500. }
  11501. _vcp.subVectors( p, c );
  11502. const d5 = _vab.dot( _vcp );
  11503. const d6 = _vac.dot( _vcp );
  11504. if ( d6 >= 0 && d5 <= d6 ) {
  11505. // vertex region of C; barycentric coords (0, 0, 1)
  11506. return target.copy( c );
  11507. }
  11508. const vb = d5 * d2 - d1 * d6;
  11509. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11510. w = d2 / ( d2 - d6 );
  11511. // edge region of AC; barycentric coords (1-w, 0, w)
  11512. return target.copy( a ).addScaledVector( _vac, w );
  11513. }
  11514. const va = d3 * d6 - d5 * d4;
  11515. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11516. _vbc.subVectors( c, b );
  11517. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11518. // edge region of BC; barycentric coords (0, 1-w, w)
  11519. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11520. }
  11521. // face region
  11522. const denom = 1 / ( va + vb + vc );
  11523. // u = va * denom
  11524. v = vb * denom;
  11525. w = vc * denom;
  11526. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11527. }
  11528. /**
  11529. * Returns `true` if this triangle is equal with the given one.
  11530. *
  11531. * @param {Triangle} triangle - The triangle to test for equality.
  11532. * @return {boolean} Whether this triangle is equal with the given one.
  11533. */
  11534. equals( triangle ) {
  11535. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11536. }
  11537. }
  11538. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11539. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11540. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11541. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11542. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11543. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11544. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11545. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11546. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11547. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11548. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11549. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11550. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11551. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11552. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11553. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11554. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11555. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11556. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11557. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11558. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11559. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11560. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11561. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11562. const _hslA = { h: 0, s: 0, l: 0 };
  11563. const _hslB = { h: 0, s: 0, l: 0 };
  11564. function hue2rgb( p, q, t ) {
  11565. if ( t < 0 ) t += 1;
  11566. if ( t > 1 ) t -= 1;
  11567. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11568. if ( t < 1 / 2 ) return q;
  11569. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11570. return p;
  11571. }
  11572. /**
  11573. * A Color instance is represented by RGB components in the linear <i>working
  11574. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11575. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11576. * strings) are converted to the working color space automatically.
  11577. *
  11578. * ```js
  11579. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11580. * const color = new THREE.Color().setHex( 0x112233 );
  11581. * ```
  11582. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11583. * ```js
  11584. * // assumed already LinearSRGBColorSpace; no conversion
  11585. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11586. *
  11587. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11588. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11589. * ```
  11590. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11591. * see <i>Color management</i>. Iterating through a Color instance will yield
  11592. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11593. * in any of the following ways:
  11594. * ```js
  11595. * //empty constructor - will default white
  11596. * const color1 = new THREE.Color();
  11597. *
  11598. * //Hexadecimal color (recommended)
  11599. * const color2 = new THREE.Color( 0xff0000 );
  11600. *
  11601. * //RGB string
  11602. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11603. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11604. *
  11605. * //X11 color name - all 140 color names are supported.
  11606. * //Note the lack of CamelCase in the name
  11607. * const color5 = new THREE.Color( 'skyblue' );
  11608. * //HSL string
  11609. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11610. *
  11611. * //Separate RGB values between 0 and 1
  11612. * const color7 = new THREE.Color( 1, 0, 0 );
  11613. * ```
  11614. */
  11615. class Color {
  11616. /**
  11617. * Constructs a new color.
  11618. *
  11619. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11620. * and that method is used throughout the rest of the documentation.
  11621. *
  11622. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11623. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11624. * @param {number} [g] - The green component.
  11625. * @param {number} [b] - The blue component.
  11626. */
  11627. constructor( r, g, b ) {
  11628. /**
  11629. * This flag can be used for type testing.
  11630. *
  11631. * @type {boolean}
  11632. * @readonly
  11633. * @default true
  11634. */
  11635. this.isColor = true;
  11636. /**
  11637. * The red component.
  11638. *
  11639. * @type {number}
  11640. * @default 1
  11641. */
  11642. this.r = 1;
  11643. /**
  11644. * The green component.
  11645. *
  11646. * @type {number}
  11647. * @default 1
  11648. */
  11649. this.g = 1;
  11650. /**
  11651. * The blue component.
  11652. *
  11653. * @type {number}
  11654. * @default 1
  11655. */
  11656. this.b = 1;
  11657. return this.set( r, g, b );
  11658. }
  11659. /**
  11660. * Sets the colors's components from the given values.
  11661. *
  11662. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11663. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11664. * @param {number} [g] - The green component.
  11665. * @param {number} [b] - The blue component.
  11666. * @return {Color} A reference to this color.
  11667. */
  11668. set( r, g, b ) {
  11669. if ( g === undefined && b === undefined ) {
  11670. // r is THREE.Color, hex or string
  11671. const value = r;
  11672. if ( value && value.isColor ) {
  11673. this.copy( value );
  11674. } else if ( typeof value === 'number' ) {
  11675. this.setHex( value );
  11676. } else if ( typeof value === 'string' ) {
  11677. this.setStyle( value );
  11678. }
  11679. } else {
  11680. this.setRGB( r, g, b );
  11681. }
  11682. return this;
  11683. }
  11684. /**
  11685. * Sets the colors's components to the given scalar value.
  11686. *
  11687. * @param {number} scalar - The scalar value.
  11688. * @return {Color} A reference to this color.
  11689. */
  11690. setScalar( scalar ) {
  11691. this.r = scalar;
  11692. this.g = scalar;
  11693. this.b = scalar;
  11694. return this;
  11695. }
  11696. /**
  11697. * Sets this color from a hexadecimal value.
  11698. *
  11699. * @param {number} hex - The hexadecimal value.
  11700. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11701. * @return {Color} A reference to this color.
  11702. */
  11703. setHex( hex, colorSpace = SRGBColorSpace ) {
  11704. hex = Math.floor( hex );
  11705. this.r = ( hex >> 16 & 255 ) / 255;
  11706. this.g = ( hex >> 8 & 255 ) / 255;
  11707. this.b = ( hex & 255 ) / 255;
  11708. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11709. return this;
  11710. }
  11711. /**
  11712. * Sets this color from RGB values.
  11713. *
  11714. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11715. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11716. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11717. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11718. * @return {Color} A reference to this color.
  11719. */
  11720. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11721. this.r = r;
  11722. this.g = g;
  11723. this.b = b;
  11724. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11725. return this;
  11726. }
  11727. /**
  11728. * Sets this color from RGB values.
  11729. *
  11730. * @param {number} h - Hue value between `0.0` and `1.0`.
  11731. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11732. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11733. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11734. * @return {Color} A reference to this color.
  11735. */
  11736. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11737. // h,s,l ranges are in 0.0 - 1.0
  11738. h = euclideanModulo( h, 1 );
  11739. s = clamp( s, 0, 1 );
  11740. l = clamp( l, 0, 1 );
  11741. if ( s === 0 ) {
  11742. this.r = this.g = this.b = l;
  11743. } else {
  11744. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11745. const q = ( 2 * l ) - p;
  11746. this.r = hue2rgb( q, p, h + 1 / 3 );
  11747. this.g = hue2rgb( q, p, h );
  11748. this.b = hue2rgb( q, p, h - 1 / 3 );
  11749. }
  11750. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11751. return this;
  11752. }
  11753. /**
  11754. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11755. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11756. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11757. * all 140 color names are supported).
  11758. *
  11759. * @param {string} style - Color as a CSS-style string.
  11760. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11761. * @return {Color} A reference to this color.
  11762. */
  11763. setStyle( style, colorSpace = SRGBColorSpace ) {
  11764. function handleAlpha( string ) {
  11765. if ( string === undefined ) return;
  11766. if ( parseFloat( string ) < 1 ) {
  11767. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  11768. }
  11769. }
  11770. let m;
  11771. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11772. // rgb / hsl
  11773. let color;
  11774. const name = m[ 1 ];
  11775. const components = m[ 2 ];
  11776. switch ( name ) {
  11777. case 'rgb':
  11778. case 'rgba':
  11779. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11780. // rgb(255,0,0) rgba(255,0,0,0.5)
  11781. handleAlpha( color[ 4 ] );
  11782. return this.setRGB(
  11783. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11784. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11785. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11786. colorSpace
  11787. );
  11788. }
  11789. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11790. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11791. handleAlpha( color[ 4 ] );
  11792. return this.setRGB(
  11793. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11794. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11795. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11796. colorSpace
  11797. );
  11798. }
  11799. break;
  11800. case 'hsl':
  11801. case 'hsla':
  11802. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11803. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11804. handleAlpha( color[ 4 ] );
  11805. return this.setHSL(
  11806. parseFloat( color[ 1 ] ) / 360,
  11807. parseFloat( color[ 2 ] ) / 100,
  11808. parseFloat( color[ 3 ] ) / 100,
  11809. colorSpace
  11810. );
  11811. }
  11812. break;
  11813. default:
  11814. console.warn( 'THREE.Color: Unknown color model ' + style );
  11815. }
  11816. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11817. // hex color
  11818. const hex = m[ 1 ];
  11819. const size = hex.length;
  11820. if ( size === 3 ) {
  11821. // #ff0
  11822. return this.setRGB(
  11823. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11824. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11825. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11826. colorSpace
  11827. );
  11828. } else if ( size === 6 ) {
  11829. // #ff0000
  11830. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11831. } else {
  11832. console.warn( 'THREE.Color: Invalid hex color ' + style );
  11833. }
  11834. } else if ( style && style.length > 0 ) {
  11835. return this.setColorName( style, colorSpace );
  11836. }
  11837. return this;
  11838. }
  11839. /**
  11840. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11841. * you don't need the other CSS-style formats.
  11842. *
  11843. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11844. * ```js
  11845. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11846. * ```
  11847. *
  11848. * @param {string} style - The color name.
  11849. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11850. * @return {Color} A reference to this color.
  11851. */
  11852. setColorName( style, colorSpace = SRGBColorSpace ) {
  11853. // color keywords
  11854. const hex = _colorKeywords[ style.toLowerCase() ];
  11855. if ( hex !== undefined ) {
  11856. // red
  11857. this.setHex( hex, colorSpace );
  11858. } else {
  11859. // unknown color
  11860. console.warn( 'THREE.Color: Unknown color ' + style );
  11861. }
  11862. return this;
  11863. }
  11864. /**
  11865. * Returns a new color with copied values from this instance.
  11866. *
  11867. * @return {Color} A clone of this instance.
  11868. */
  11869. clone() {
  11870. return new this.constructor( this.r, this.g, this.b );
  11871. }
  11872. /**
  11873. * Copies the values of the given color to this instance.
  11874. *
  11875. * @param {Color} color - The color to copy.
  11876. * @return {Color} A reference to this color.
  11877. */
  11878. copy( color ) {
  11879. this.r = color.r;
  11880. this.g = color.g;
  11881. this.b = color.b;
  11882. return this;
  11883. }
  11884. /**
  11885. * Copies the given color into this color, and then converts this color from
  11886. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11887. *
  11888. * @param {Color} color - The color to copy/convert.
  11889. * @return {Color} A reference to this color.
  11890. */
  11891. copySRGBToLinear( color ) {
  11892. this.r = SRGBToLinear( color.r );
  11893. this.g = SRGBToLinear( color.g );
  11894. this.b = SRGBToLinear( color.b );
  11895. return this;
  11896. }
  11897. /**
  11898. * Copies the given color into this color, and then converts this color from
  11899. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11900. *
  11901. * @param {Color} color - The color to copy/convert.
  11902. * @return {Color} A reference to this color.
  11903. */
  11904. copyLinearToSRGB( color ) {
  11905. this.r = LinearToSRGB( color.r );
  11906. this.g = LinearToSRGB( color.g );
  11907. this.b = LinearToSRGB( color.b );
  11908. return this;
  11909. }
  11910. /**
  11911. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11912. *
  11913. * @return {Color} A reference to this color.
  11914. */
  11915. convertSRGBToLinear() {
  11916. this.copySRGBToLinear( this );
  11917. return this;
  11918. }
  11919. /**
  11920. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11921. *
  11922. * @return {Color} A reference to this color.
  11923. */
  11924. convertLinearToSRGB() {
  11925. this.copyLinearToSRGB( this );
  11926. return this;
  11927. }
  11928. /**
  11929. * Returns the hexadecimal value of this color.
  11930. *
  11931. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11932. * @return {number} The hexadecimal value.
  11933. */
  11934. getHex( colorSpace = SRGBColorSpace ) {
  11935. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11936. 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 ) );
  11937. }
  11938. /**
  11939. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11940. *
  11941. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11942. * @return {string} The hexadecimal value as a string.
  11943. */
  11944. getHexString( colorSpace = SRGBColorSpace ) {
  11945. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11946. }
  11947. /**
  11948. * Converts the colors RGB values into the HSL format and stores them into the
  11949. * given target object.
  11950. *
  11951. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11952. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11953. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11954. */
  11955. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11956. // h,s,l ranges are in 0.0 - 1.0
  11957. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11958. const r = _color.r, g = _color.g, b = _color.b;
  11959. const max = Math.max( r, g, b );
  11960. const min = Math.min( r, g, b );
  11961. let hue, saturation;
  11962. const lightness = ( min + max ) / 2.0;
  11963. if ( min === max ) {
  11964. hue = 0;
  11965. saturation = 0;
  11966. } else {
  11967. const delta = max - min;
  11968. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  11969. switch ( max ) {
  11970. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  11971. case g: hue = ( b - r ) / delta + 2; break;
  11972. case b: hue = ( r - g ) / delta + 4; break;
  11973. }
  11974. hue /= 6;
  11975. }
  11976. target.h = hue;
  11977. target.s = saturation;
  11978. target.l = lightness;
  11979. return target;
  11980. }
  11981. /**
  11982. * Returns the RGB values of this color and stores them into the given target object.
  11983. *
  11984. * @param {Color} target - The target color that is used to store the method's result.
  11985. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11986. * @return {Color} The RGB representation of this color.
  11987. */
  11988. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  11989. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11990. target.r = _color.r;
  11991. target.g = _color.g;
  11992. target.b = _color.b;
  11993. return target;
  11994. }
  11995. /**
  11996. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  11997. *
  11998. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11999. * @return {string} The CSS representation of this color.
  12000. */
  12001. getStyle( colorSpace = SRGBColorSpace ) {
  12002. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12003. const r = _color.r, g = _color.g, b = _color.b;
  12004. if ( colorSpace !== SRGBColorSpace ) {
  12005. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12006. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12007. }
  12008. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12009. }
  12010. /**
  12011. * Adds the given HSL values to this color's values.
  12012. * Internally, this converts the color's RGB values to HSL, adds HSL
  12013. * and then converts the color back to RGB.
  12014. *
  12015. * @param {number} h - Hue value between `0.0` and `1.0`.
  12016. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12017. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12018. * @return {Color} A reference to this color.
  12019. */
  12020. offsetHSL( h, s, l ) {
  12021. this.getHSL( _hslA );
  12022. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12023. }
  12024. /**
  12025. * Adds the RGB values of the given color to the RGB values of this color.
  12026. *
  12027. * @param {Color} color - The color to add.
  12028. * @return {Color} A reference to this color.
  12029. */
  12030. add( color ) {
  12031. this.r += color.r;
  12032. this.g += color.g;
  12033. this.b += color.b;
  12034. return this;
  12035. }
  12036. /**
  12037. * Adds the RGB values of the given colors and stores the result in this instance.
  12038. *
  12039. * @param {Color} color1 - The first color.
  12040. * @param {Color} color2 - The second color.
  12041. * @return {Color} A reference to this color.
  12042. */
  12043. addColors( color1, color2 ) {
  12044. this.r = color1.r + color2.r;
  12045. this.g = color1.g + color2.g;
  12046. this.b = color1.b + color2.b;
  12047. return this;
  12048. }
  12049. /**
  12050. * Adds the given scalar value to the RGB values of this color.
  12051. *
  12052. * @param {number} s - The scalar to add.
  12053. * @return {Color} A reference to this color.
  12054. */
  12055. addScalar( s ) {
  12056. this.r += s;
  12057. this.g += s;
  12058. this.b += s;
  12059. return this;
  12060. }
  12061. /**
  12062. * Subtracts the RGB values of the given color from the RGB values of this color.
  12063. *
  12064. * @param {Color} color - The color to subtract.
  12065. * @return {Color} A reference to this color.
  12066. */
  12067. sub( color ) {
  12068. this.r = Math.max( 0, this.r - color.r );
  12069. this.g = Math.max( 0, this.g - color.g );
  12070. this.b = Math.max( 0, this.b - color.b );
  12071. return this;
  12072. }
  12073. /**
  12074. * Multiplies the RGB values of the given color with the RGB values of this color.
  12075. *
  12076. * @param {Color} color - The color to multiply.
  12077. * @return {Color} A reference to this color.
  12078. */
  12079. multiply( color ) {
  12080. this.r *= color.r;
  12081. this.g *= color.g;
  12082. this.b *= color.b;
  12083. return this;
  12084. }
  12085. /**
  12086. * Multiplies the given scalar value with the RGB values of this color.
  12087. *
  12088. * @param {number} s - The scalar to multiply.
  12089. * @return {Color} A reference to this color.
  12090. */
  12091. multiplyScalar( s ) {
  12092. this.r *= s;
  12093. this.g *= s;
  12094. this.b *= s;
  12095. return this;
  12096. }
  12097. /**
  12098. * Linearly interpolates this color's RGB values toward the RGB values of the
  12099. * given color. The alpha argument can be thought of as the ratio between
  12100. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12101. *
  12102. * @param {Color} color - The color to converge on.
  12103. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12104. * @return {Color} A reference to this color.
  12105. */
  12106. lerp( color, alpha ) {
  12107. this.r += ( color.r - this.r ) * alpha;
  12108. this.g += ( color.g - this.g ) * alpha;
  12109. this.b += ( color.b - this.b ) * alpha;
  12110. return this;
  12111. }
  12112. /**
  12113. * Linearly interpolates between the given colors and stores the result in this instance.
  12114. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12115. * is the first and `1.0` is the second color.
  12116. *
  12117. * @param {Color} color1 - The first color.
  12118. * @param {Color} color2 - The second color.
  12119. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12120. * @return {Color} A reference to this color.
  12121. */
  12122. lerpColors( color1, color2, alpha ) {
  12123. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12124. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12125. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12126. return this;
  12127. }
  12128. /**
  12129. * Linearly interpolates this color's HSL values toward the HSL values of the
  12130. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12131. * from one color to the other, but instead going through all the hues in between
  12132. * those two colors. The alpha argument can be thought of as the ratio between
  12133. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12134. *
  12135. * @param {Color} color - The color to converge on.
  12136. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12137. * @return {Color} A reference to this color.
  12138. */
  12139. lerpHSL( color, alpha ) {
  12140. this.getHSL( _hslA );
  12141. color.getHSL( _hslB );
  12142. const h = lerp( _hslA.h, _hslB.h, alpha );
  12143. const s = lerp( _hslA.s, _hslB.s, alpha );
  12144. const l = lerp( _hslA.l, _hslB.l, alpha );
  12145. this.setHSL( h, s, l );
  12146. return this;
  12147. }
  12148. /**
  12149. * Sets the color's RGB components from the given 3D vector.
  12150. *
  12151. * @param {Vector3} v - The vector to set.
  12152. * @return {Color} A reference to this color.
  12153. */
  12154. setFromVector3( v ) {
  12155. this.r = v.x;
  12156. this.g = v.y;
  12157. this.b = v.z;
  12158. return this;
  12159. }
  12160. /**
  12161. * Transforms this color with the given 3x3 matrix.
  12162. *
  12163. * @param {Matrix3} m - The matrix.
  12164. * @return {Color} A reference to this color.
  12165. */
  12166. applyMatrix3( m ) {
  12167. const r = this.r, g = this.g, b = this.b;
  12168. const e = m.elements;
  12169. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12170. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12171. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12172. return this;
  12173. }
  12174. /**
  12175. * Returns `true` if this color is equal with the given one.
  12176. *
  12177. * @param {Color} c - The color to test for equality.
  12178. * @return {boolean} Whether this bounding color is equal with the given one.
  12179. */
  12180. equals( c ) {
  12181. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12182. }
  12183. /**
  12184. * Sets this color's RGB components from the given array.
  12185. *
  12186. * @param {Array<number>} array - An array holding the RGB values.
  12187. * @param {number} [offset=0] - The offset into the array.
  12188. * @return {Color} A reference to this color.
  12189. */
  12190. fromArray( array, offset = 0 ) {
  12191. this.r = array[ offset ];
  12192. this.g = array[ offset + 1 ];
  12193. this.b = array[ offset + 2 ];
  12194. return this;
  12195. }
  12196. /**
  12197. * Writes the RGB components of this color to the given array. If no array is provided,
  12198. * the method returns a new instance.
  12199. *
  12200. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12201. * @param {number} [offset=0] - Index of the first element in the array.
  12202. * @return {Array<number>} The color components.
  12203. */
  12204. toArray( array = [], offset = 0 ) {
  12205. array[ offset ] = this.r;
  12206. array[ offset + 1 ] = this.g;
  12207. array[ offset + 2 ] = this.b;
  12208. return array;
  12209. }
  12210. /**
  12211. * Sets the components of this color from the given buffer attribute.
  12212. *
  12213. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12214. * @param {number} index - The index into the attribute.
  12215. * @return {Color} A reference to this color.
  12216. */
  12217. fromBufferAttribute( attribute, index ) {
  12218. this.r = attribute.getX( index );
  12219. this.g = attribute.getY( index );
  12220. this.b = attribute.getZ( index );
  12221. return this;
  12222. }
  12223. /**
  12224. * This methods defines the serialization result of this class. Returns the color
  12225. * as a hexadecimal value.
  12226. *
  12227. * @return {number} The hexadecimal value.
  12228. */
  12229. toJSON() {
  12230. return this.getHex();
  12231. }
  12232. *[ Symbol.iterator ]() {
  12233. yield this.r;
  12234. yield this.g;
  12235. yield this.b;
  12236. }
  12237. }
  12238. const _color = /*@__PURE__*/ new Color();
  12239. /**
  12240. * A dictionary with X11 color names.
  12241. *
  12242. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12243. *
  12244. * @static
  12245. * @type {Object}
  12246. */
  12247. Color.NAMES = _colorKeywords;
  12248. let _materialId = 0;
  12249. /**
  12250. * Abstract base class for materials.
  12251. *
  12252. * Materials define the appearance of renderable 3D objects.
  12253. *
  12254. * @abstract
  12255. * @augments EventDispatcher
  12256. */
  12257. class Material extends EventDispatcher {
  12258. /**
  12259. * Constructs a new material.
  12260. */
  12261. constructor() {
  12262. super();
  12263. /**
  12264. * This flag can be used for type testing.
  12265. *
  12266. * @type {boolean}
  12267. * @readonly
  12268. * @default true
  12269. */
  12270. this.isMaterial = true;
  12271. /**
  12272. * The ID of the material.
  12273. *
  12274. * @name Material#id
  12275. * @type {number}
  12276. * @readonly
  12277. */
  12278. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12279. /**
  12280. * The UUID of the material.
  12281. *
  12282. * @type {string}
  12283. * @readonly
  12284. */
  12285. this.uuid = generateUUID();
  12286. /**
  12287. * The name of the material.
  12288. *
  12289. * @type {string}
  12290. */
  12291. this.name = '';
  12292. /**
  12293. * The type property is used for detecting the object type
  12294. * in context of serialization/deserialization.
  12295. *
  12296. * @type {string}
  12297. * @readonly
  12298. */
  12299. this.type = 'Material';
  12300. /**
  12301. * Defines the blending type of the material.
  12302. *
  12303. * It must be set to `CustomBlending` if custom blending properties like
  12304. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12305. * should have any effect.
  12306. *
  12307. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12308. * @default NormalBlending
  12309. */
  12310. this.blending = NormalBlending;
  12311. /**
  12312. * Defines which side of faces will be rendered - front, back or both.
  12313. *
  12314. * @type {(FrontSide|BackSide|DoubleSide)}
  12315. * @default FrontSide
  12316. */
  12317. this.side = FrontSide;
  12318. /**
  12319. * If set to `true`, vertex colors should be used.
  12320. *
  12321. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12322. * four (RGBA) component color buffer attribute is used.
  12323. *
  12324. * @type {boolean}
  12325. * @default false
  12326. */
  12327. this.vertexColors = false;
  12328. /**
  12329. * Defines how transparent the material is.
  12330. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12331. *
  12332. * If the {@link Material#transparent} is not set to `true`,
  12333. * the material will remain fully opaque and this value will only affect its color.
  12334. *
  12335. * @type {number}
  12336. * @default 1
  12337. */
  12338. this.opacity = 1;
  12339. /**
  12340. * Defines whether this material is transparent. This has an effect on
  12341. * rendering as transparent objects need special treatment and are rendered
  12342. * after non-transparent objects.
  12343. *
  12344. * When set to true, the extent to which the material is transparent is
  12345. * controlled by {@link Material#opacity}.
  12346. *
  12347. * @type {boolean}
  12348. * @default false
  12349. */
  12350. this.transparent = false;
  12351. /**
  12352. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12353. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12354. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12355. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12356. *
  12357. * @type {boolean}
  12358. * @default false
  12359. */
  12360. this.alphaHash = false;
  12361. /**
  12362. * Defines the blending source factor.
  12363. *
  12364. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12365. * @default SrcAlphaFactor
  12366. */
  12367. this.blendSrc = SrcAlphaFactor;
  12368. /**
  12369. * Defines the blending destination factor.
  12370. *
  12371. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12372. * @default OneMinusSrcAlphaFactor
  12373. */
  12374. this.blendDst = OneMinusSrcAlphaFactor;
  12375. /**
  12376. * Defines the blending equation.
  12377. *
  12378. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12379. * @default AddEquation
  12380. */
  12381. this.blendEquation = AddEquation;
  12382. /**
  12383. * Defines the blending source alpha factor.
  12384. *
  12385. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12386. * @default null
  12387. */
  12388. this.blendSrcAlpha = null;
  12389. /**
  12390. * Defines the blending destination alpha factor.
  12391. *
  12392. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12393. * @default null
  12394. */
  12395. this.blendDstAlpha = null;
  12396. /**
  12397. * Defines the blending equation of the alpha channel.
  12398. *
  12399. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12400. * @default null
  12401. */
  12402. this.blendEquationAlpha = null;
  12403. /**
  12404. * Represents the RGB values of the constant blend color.
  12405. *
  12406. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12407. *
  12408. * @type {Color}
  12409. * @default (0,0,0)
  12410. */
  12411. this.blendColor = new Color( 0, 0, 0 );
  12412. /**
  12413. * Represents the alpha value of the constant blend color.
  12414. *
  12415. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12416. *
  12417. * @type {number}
  12418. * @default 0
  12419. */
  12420. this.blendAlpha = 0;
  12421. /**
  12422. * Defines the depth function.
  12423. *
  12424. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12425. * @default LessEqualDepth
  12426. */
  12427. this.depthFunc = LessEqualDepth;
  12428. /**
  12429. * Whether to have depth test enabled when rendering this material.
  12430. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12431. *
  12432. * @type {boolean}
  12433. * @default true
  12434. */
  12435. this.depthTest = true;
  12436. /**
  12437. * Whether rendering this material has any effect on the depth buffer.
  12438. *
  12439. * When drawing 2D overlays it can be useful to disable the depth writing in
  12440. * order to layer several things together without creating z-index artifacts.
  12441. *
  12442. * @type {boolean}
  12443. * @default true
  12444. */
  12445. this.depthWrite = true;
  12446. /**
  12447. * The bit mask to use when writing to the stencil buffer.
  12448. *
  12449. * @type {number}
  12450. * @default 0xff
  12451. */
  12452. this.stencilWriteMask = 0xff;
  12453. /**
  12454. * The stencil comparison function to use.
  12455. *
  12456. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12457. * @default AlwaysStencilFunc
  12458. */
  12459. this.stencilFunc = AlwaysStencilFunc;
  12460. /**
  12461. * The value to use when performing stencil comparisons or stencil operations.
  12462. *
  12463. * @type {number}
  12464. * @default 0
  12465. */
  12466. this.stencilRef = 0;
  12467. /**
  12468. * The bit mask to use when comparing against the stencil buffer.
  12469. *
  12470. * @type {number}
  12471. * @default 0xff
  12472. */
  12473. this.stencilFuncMask = 0xff;
  12474. /**
  12475. * Which stencil operation to perform when the comparison function returns `false`.
  12476. *
  12477. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12478. * @default KeepStencilOp
  12479. */
  12480. this.stencilFail = KeepStencilOp;
  12481. /**
  12482. * Which stencil operation to perform when the comparison function returns
  12483. * `true` but the depth test fails.
  12484. *
  12485. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12486. * @default KeepStencilOp
  12487. */
  12488. this.stencilZFail = KeepStencilOp;
  12489. /**
  12490. * Which stencil operation to perform when the comparison function returns
  12491. * `true` and the depth test passes.
  12492. *
  12493. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12494. * @default KeepStencilOp
  12495. */
  12496. this.stencilZPass = KeepStencilOp;
  12497. /**
  12498. * Whether stencil operations are performed against the stencil buffer. In
  12499. * order to perform writes or comparisons against the stencil buffer this
  12500. * value must be `true`.
  12501. *
  12502. * @type {boolean}
  12503. * @default false
  12504. */
  12505. this.stencilWrite = false;
  12506. /**
  12507. * User-defined clipping planes specified as THREE.Plane objects in world
  12508. * space. These planes apply to the objects this material is attached to.
  12509. * Points in space whose signed distance to the plane is negative are clipped
  12510. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12511. * be `true`.
  12512. *
  12513. * @type {?Array<Plane>}
  12514. * @default null
  12515. */
  12516. this.clippingPlanes = null;
  12517. /**
  12518. * Changes the behavior of clipping planes so that only their intersection is
  12519. * clipped, rather than their union.
  12520. *
  12521. * @type {boolean}
  12522. * @default false
  12523. */
  12524. this.clipIntersection = false;
  12525. /**
  12526. * Defines whether to clip shadows according to the clipping planes specified
  12527. * on this material.
  12528. *
  12529. * @type {boolean}
  12530. * @default false
  12531. */
  12532. this.clipShadows = false;
  12533. /**
  12534. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12535. * is determined as follows:
  12536. *
  12537. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12538. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12539. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12540. *
  12541. * @type {?(FrontSide|BackSide|DoubleSide)}
  12542. * @default null
  12543. */
  12544. this.shadowSide = null;
  12545. /**
  12546. * Whether to render the material's color.
  12547. *
  12548. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12549. * objects that occlude other objects.
  12550. *
  12551. * @type {boolean}
  12552. * @default true
  12553. */
  12554. this.colorWrite = true;
  12555. /**
  12556. * Override the renderer's default precision for this material.
  12557. *
  12558. * @type {?('highp'|'mediump'|'lowp')}
  12559. * @default null
  12560. */
  12561. this.precision = null;
  12562. /**
  12563. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12564. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12565. * The offset is added before the depth test is performed and before the value is written
  12566. * into the depth buffer.
  12567. *
  12568. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12569. * rendering solids with highlighted edges.
  12570. *
  12571. * @type {boolean}
  12572. * @default false
  12573. */
  12574. this.polygonOffset = false;
  12575. /**
  12576. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12577. *
  12578. * @type {number}
  12579. * @default 0
  12580. */
  12581. this.polygonOffsetFactor = 0;
  12582. /**
  12583. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12584. *
  12585. * @type {number}
  12586. * @default 0
  12587. */
  12588. this.polygonOffsetUnits = 0;
  12589. /**
  12590. * Whether to apply dithering to the color to remove the appearance of banding.
  12591. *
  12592. * @type {boolean}
  12593. * @default false
  12594. */
  12595. this.dithering = false;
  12596. /**
  12597. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12598. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12599. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12600. *
  12601. * @type {boolean}
  12602. * @default false
  12603. */
  12604. this.alphaToCoverage = false;
  12605. /**
  12606. * Whether to premultiply the alpha (transparency) value.
  12607. *
  12608. * @type {boolean}
  12609. * @default false
  12610. */
  12611. this.premultipliedAlpha = false;
  12612. /**
  12613. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12614. *
  12615. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12616. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12617. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12618. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12619. * disable the two pass rendering to avoid performance issues.
  12620. *
  12621. * @type {boolean}
  12622. * @default false
  12623. */
  12624. this.forceSinglePass = false;
  12625. /**
  12626. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12627. *
  12628. * @type {boolean}
  12629. * @default true
  12630. */
  12631. this.allowOverride = true;
  12632. /**
  12633. * Defines whether 3D objects using this material are visible.
  12634. *
  12635. * @type {boolean}
  12636. * @default true
  12637. */
  12638. this.visible = true;
  12639. /**
  12640. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12641. *
  12642. * It is ignored when rendering to a render target or using post processing or when using
  12643. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12644. *
  12645. * @type {boolean}
  12646. * @default true
  12647. */
  12648. this.toneMapped = true;
  12649. /**
  12650. * An object that can be used to store custom data about the Material. It
  12651. * should not hold references to functions as these will not be cloned.
  12652. *
  12653. * @type {Object}
  12654. */
  12655. this.userData = {};
  12656. /**
  12657. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12658. *
  12659. * @type {number}
  12660. * @readonly
  12661. * @default 0
  12662. */
  12663. this.version = 0;
  12664. this._alphaTest = 0;
  12665. }
  12666. /**
  12667. * Sets the alpha value to be used when running an alpha test. The material
  12668. * will not be rendered if the opacity is lower than this value.
  12669. *
  12670. * @type {number}
  12671. * @readonly
  12672. * @default 0
  12673. */
  12674. get alphaTest() {
  12675. return this._alphaTest;
  12676. }
  12677. set alphaTest( value ) {
  12678. if ( this._alphaTest > 0 !== value > 0 ) {
  12679. this.version ++;
  12680. }
  12681. this._alphaTest = value;
  12682. }
  12683. /**
  12684. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12685. *
  12686. * This method can only be used when rendering with {@link WebGLRenderer}.
  12687. *
  12688. * @param {WebGLRenderer} renderer - The renderer.
  12689. * @param {Scene} scene - The scene.
  12690. * @param {Camera} camera - The camera that is used to render the scene.
  12691. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12692. * @param {Object3D} object - The 3D object.
  12693. * @param {Object} group - The geometry group data.
  12694. */
  12695. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12696. /**
  12697. * An optional callback that is executed immediately before the shader
  12698. * program is compiled. This function is called with the shader source code
  12699. * as a parameter. Useful for the modification of built-in materials.
  12700. *
  12701. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12702. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12703. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12704. *
  12705. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12706. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12707. */
  12708. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12709. /**
  12710. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12711. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12712. * shader or recompile the shader for this material as needed.
  12713. *
  12714. * This method can only be used when rendering with {@link WebGLRenderer}.
  12715. *
  12716. * @return {string} The custom program cache key.
  12717. */
  12718. customProgramCacheKey() {
  12719. return this.onBeforeCompile.toString();
  12720. }
  12721. /**
  12722. * This method can be used to set default values from parameter objects.
  12723. * It is a generic implementation so it can be used with different types
  12724. * of materials.
  12725. *
  12726. * @param {Object} [values] - The material values to set.
  12727. */
  12728. setValues( values ) {
  12729. if ( values === undefined ) return;
  12730. for ( const key in values ) {
  12731. const newValue = values[ key ];
  12732. if ( newValue === undefined ) {
  12733. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  12734. continue;
  12735. }
  12736. const currentValue = this[ key ];
  12737. if ( currentValue === undefined ) {
  12738. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12739. continue;
  12740. }
  12741. if ( currentValue && currentValue.isColor ) {
  12742. currentValue.set( newValue );
  12743. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12744. currentValue.copy( newValue );
  12745. } else {
  12746. this[ key ] = newValue;
  12747. }
  12748. }
  12749. }
  12750. /**
  12751. * Serializes the material into JSON.
  12752. *
  12753. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12754. * @return {Object} A JSON object representing the serialized material.
  12755. * @see {@link ObjectLoader#parse}
  12756. */
  12757. toJSON( meta ) {
  12758. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12759. if ( isRootObject ) {
  12760. meta = {
  12761. textures: {},
  12762. images: {}
  12763. };
  12764. }
  12765. const data = {
  12766. metadata: {
  12767. version: 4.7,
  12768. type: 'Material',
  12769. generator: 'Material.toJSON'
  12770. }
  12771. };
  12772. // standard Material serialization
  12773. data.uuid = this.uuid;
  12774. data.type = this.type;
  12775. if ( this.name !== '' ) data.name = this.name;
  12776. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12777. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12778. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12779. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12780. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12781. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12782. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12783. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12784. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12785. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12786. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12787. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12788. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12789. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12790. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12791. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12792. }
  12793. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12794. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12795. }
  12796. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12797. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12798. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12799. }
  12800. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12801. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12802. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12803. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12804. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12805. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12806. }
  12807. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12808. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12809. }
  12810. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12811. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12812. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12813. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12814. }
  12815. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12816. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12817. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12818. if ( this.lightMap && this.lightMap.isTexture ) {
  12819. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12820. data.lightMapIntensity = this.lightMapIntensity;
  12821. }
  12822. if ( this.aoMap && this.aoMap.isTexture ) {
  12823. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12824. data.aoMapIntensity = this.aoMapIntensity;
  12825. }
  12826. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12827. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12828. data.bumpScale = this.bumpScale;
  12829. }
  12830. if ( this.normalMap && this.normalMap.isTexture ) {
  12831. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12832. data.normalMapType = this.normalMapType;
  12833. data.normalScale = this.normalScale.toArray();
  12834. }
  12835. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12836. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12837. data.displacementScale = this.displacementScale;
  12838. data.displacementBias = this.displacementBias;
  12839. }
  12840. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12841. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12842. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12843. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12844. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12845. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12846. if ( this.envMap && this.envMap.isTexture ) {
  12847. data.envMap = this.envMap.toJSON( meta ).uuid;
  12848. if ( this.combine !== undefined ) data.combine = this.combine;
  12849. }
  12850. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12851. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12852. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12853. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12854. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12855. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12856. }
  12857. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12858. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12859. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12860. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12861. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12862. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12863. if ( this.size !== undefined ) data.size = this.size;
  12864. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12865. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12866. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12867. if ( this.side !== FrontSide ) data.side = this.side;
  12868. if ( this.vertexColors === true ) data.vertexColors = true;
  12869. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12870. if ( this.transparent === true ) data.transparent = true;
  12871. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12872. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12873. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12874. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12875. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12876. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12877. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12878. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12879. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12880. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12881. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12882. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12883. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12884. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12885. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12886. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12887. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12888. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12889. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12890. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12891. // rotation (SpriteMaterial)
  12892. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12893. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12894. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12895. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12896. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12897. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12898. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12899. if ( this.scale !== undefined ) data.scale = this.scale;
  12900. if ( this.dithering === true ) data.dithering = true;
  12901. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12902. if ( this.alphaHash === true ) data.alphaHash = true;
  12903. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12904. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12905. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12906. if ( this.wireframe === true ) data.wireframe = true;
  12907. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12908. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12909. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12910. if ( this.flatShading === true ) data.flatShading = true;
  12911. if ( this.visible === false ) data.visible = false;
  12912. if ( this.toneMapped === false ) data.toneMapped = false;
  12913. if ( this.fog === false ) data.fog = false;
  12914. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12915. // TODO: Copied from Object3D.toJSON
  12916. function extractFromCache( cache ) {
  12917. const values = [];
  12918. for ( const key in cache ) {
  12919. const data = cache[ key ];
  12920. delete data.metadata;
  12921. values.push( data );
  12922. }
  12923. return values;
  12924. }
  12925. if ( isRootObject ) {
  12926. const textures = extractFromCache( meta.textures );
  12927. const images = extractFromCache( meta.images );
  12928. if ( textures.length > 0 ) data.textures = textures;
  12929. if ( images.length > 0 ) data.images = images;
  12930. }
  12931. return data;
  12932. }
  12933. /**
  12934. * Returns a new material with copied values from this instance.
  12935. *
  12936. * @return {Material} A clone of this instance.
  12937. */
  12938. clone() {
  12939. return new this.constructor().copy( this );
  12940. }
  12941. /**
  12942. * Copies the values of the given material to this instance.
  12943. *
  12944. * @param {Material} source - The material to copy.
  12945. * @return {Material} A reference to this instance.
  12946. */
  12947. copy( source ) {
  12948. this.name = source.name;
  12949. this.blending = source.blending;
  12950. this.side = source.side;
  12951. this.vertexColors = source.vertexColors;
  12952. this.opacity = source.opacity;
  12953. this.transparent = source.transparent;
  12954. this.blendSrc = source.blendSrc;
  12955. this.blendDst = source.blendDst;
  12956. this.blendEquation = source.blendEquation;
  12957. this.blendSrcAlpha = source.blendSrcAlpha;
  12958. this.blendDstAlpha = source.blendDstAlpha;
  12959. this.blendEquationAlpha = source.blendEquationAlpha;
  12960. this.blendColor.copy( source.blendColor );
  12961. this.blendAlpha = source.blendAlpha;
  12962. this.depthFunc = source.depthFunc;
  12963. this.depthTest = source.depthTest;
  12964. this.depthWrite = source.depthWrite;
  12965. this.stencilWriteMask = source.stencilWriteMask;
  12966. this.stencilFunc = source.stencilFunc;
  12967. this.stencilRef = source.stencilRef;
  12968. this.stencilFuncMask = source.stencilFuncMask;
  12969. this.stencilFail = source.stencilFail;
  12970. this.stencilZFail = source.stencilZFail;
  12971. this.stencilZPass = source.stencilZPass;
  12972. this.stencilWrite = source.stencilWrite;
  12973. const srcPlanes = source.clippingPlanes;
  12974. let dstPlanes = null;
  12975. if ( srcPlanes !== null ) {
  12976. const n = srcPlanes.length;
  12977. dstPlanes = new Array( n );
  12978. for ( let i = 0; i !== n; ++ i ) {
  12979. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12980. }
  12981. }
  12982. this.clippingPlanes = dstPlanes;
  12983. this.clipIntersection = source.clipIntersection;
  12984. this.clipShadows = source.clipShadows;
  12985. this.shadowSide = source.shadowSide;
  12986. this.colorWrite = source.colorWrite;
  12987. this.precision = source.precision;
  12988. this.polygonOffset = source.polygonOffset;
  12989. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12990. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12991. this.dithering = source.dithering;
  12992. this.alphaTest = source.alphaTest;
  12993. this.alphaHash = source.alphaHash;
  12994. this.alphaToCoverage = source.alphaToCoverage;
  12995. this.premultipliedAlpha = source.premultipliedAlpha;
  12996. this.forceSinglePass = source.forceSinglePass;
  12997. this.visible = source.visible;
  12998. this.toneMapped = source.toneMapped;
  12999. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13000. return this;
  13001. }
  13002. /**
  13003. * Frees the GPU-related resources allocated by this instance. Call this
  13004. * method whenever this instance is no longer used in your app.
  13005. *
  13006. * @fires Material#dispose
  13007. */
  13008. dispose() {
  13009. /**
  13010. * Fires when the material has been disposed of.
  13011. *
  13012. * @event Material#dispose
  13013. * @type {Object}
  13014. */
  13015. this.dispatchEvent( { type: 'dispose' } );
  13016. }
  13017. /**
  13018. * Setting this property to `true` indicates the engine the material
  13019. * needs to be recompiled.
  13020. *
  13021. * @type {boolean}
  13022. * @default false
  13023. * @param {boolean} value
  13024. */
  13025. set needsUpdate( value ) {
  13026. if ( value === true ) this.version ++;
  13027. }
  13028. }
  13029. /**
  13030. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13031. *
  13032. * This material is not affected by lights.
  13033. *
  13034. * @augments Material
  13035. */
  13036. class MeshBasicMaterial extends Material {
  13037. /**
  13038. * Constructs a new mesh basic material.
  13039. *
  13040. * @param {Object} [parameters] - An object with one or more properties
  13041. * defining the material's appearance. Any property of the material
  13042. * (including any property from inherited materials) can be passed
  13043. * in here. Color values can be passed any type of value accepted
  13044. * by {@link Color#set}.
  13045. */
  13046. constructor( parameters ) {
  13047. super();
  13048. /**
  13049. * This flag can be used for type testing.
  13050. *
  13051. * @type {boolean}
  13052. * @readonly
  13053. * @default true
  13054. */
  13055. this.isMeshBasicMaterial = true;
  13056. this.type = 'MeshBasicMaterial';
  13057. /**
  13058. * Color of the material.
  13059. *
  13060. * @type {Color}
  13061. * @default (1,1,1)
  13062. */
  13063. this.color = new Color( 0xffffff ); // diffuse
  13064. /**
  13065. * The color map. May optionally include an alpha channel, typically combined
  13066. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13067. * color is modulated by the diffuse `color`.
  13068. *
  13069. * @type {?Texture}
  13070. * @default null
  13071. */
  13072. this.map = null;
  13073. /**
  13074. * The light map. Requires a second set of UVs.
  13075. *
  13076. * @type {?Texture}
  13077. * @default null
  13078. */
  13079. this.lightMap = null;
  13080. /**
  13081. * Intensity of the baked light.
  13082. *
  13083. * @type {number}
  13084. * @default 1
  13085. */
  13086. this.lightMapIntensity = 1.0;
  13087. /**
  13088. * The red channel of this texture is used as the ambient occlusion map.
  13089. * Requires a second set of UVs.
  13090. *
  13091. * @type {?Texture}
  13092. * @default null
  13093. */
  13094. this.aoMap = null;
  13095. /**
  13096. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13097. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13098. * red channel is also `1`, ambient light is fully occluded on a surface.
  13099. *
  13100. * @type {number}
  13101. * @default 1
  13102. */
  13103. this.aoMapIntensity = 1.0;
  13104. /**
  13105. * Specular map used by the material.
  13106. *
  13107. * @type {?Texture}
  13108. * @default null
  13109. */
  13110. this.specularMap = null;
  13111. /**
  13112. * The alpha map is a grayscale texture that controls the opacity across the
  13113. * surface (black: fully transparent; white: fully opaque).
  13114. *
  13115. * Only the color of the texture is used, ignoring the alpha channel if one
  13116. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13117. * when sampling this texture due to the extra bit of precision provided for
  13118. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13119. * luminance/alpha textures will also still work as expected.
  13120. *
  13121. * @type {?Texture}
  13122. * @default null
  13123. */
  13124. this.alphaMap = null;
  13125. /**
  13126. * The environment map.
  13127. *
  13128. * @type {?Texture}
  13129. * @default null
  13130. */
  13131. this.envMap = null;
  13132. /**
  13133. * The rotation of the environment map in radians.
  13134. *
  13135. * @type {Euler}
  13136. * @default (0,0,0)
  13137. */
  13138. this.envMapRotation = new Euler();
  13139. /**
  13140. * How to combine the result of the surface's color with the environment map, if any.
  13141. *
  13142. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13143. * blend between the two colors.
  13144. *
  13145. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13146. * @default MultiplyOperation
  13147. */
  13148. this.combine = MultiplyOperation;
  13149. /**
  13150. * How much the environment map affects the surface.
  13151. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13152. *
  13153. * @type {number}
  13154. * @default 1
  13155. */
  13156. this.reflectivity = 1;
  13157. /**
  13158. * The index of refraction (IOR) of air (approximately 1) divided by the
  13159. * index of refraction of the material. It is used with environment mapping
  13160. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13161. * The refraction ratio should not exceed `1`.
  13162. *
  13163. * @type {number}
  13164. * @default 0.98
  13165. */
  13166. this.refractionRatio = 0.98;
  13167. /**
  13168. * Renders the geometry as a wireframe.
  13169. *
  13170. * @type {boolean}
  13171. * @default false
  13172. */
  13173. this.wireframe = false;
  13174. /**
  13175. * Controls the thickness of the wireframe.
  13176. *
  13177. * Can only be used with {@link SVGRenderer}.
  13178. *
  13179. * @type {number}
  13180. * @default 1
  13181. */
  13182. this.wireframeLinewidth = 1;
  13183. /**
  13184. * Defines appearance of wireframe ends.
  13185. *
  13186. * Can only be used with {@link SVGRenderer}.
  13187. *
  13188. * @type {('round'|'bevel'|'miter')}
  13189. * @default 'round'
  13190. */
  13191. this.wireframeLinecap = 'round';
  13192. /**
  13193. * Defines appearance of wireframe joints.
  13194. *
  13195. * Can only be used with {@link SVGRenderer}.
  13196. *
  13197. * @type {('round'|'bevel'|'miter')}
  13198. * @default 'round'
  13199. */
  13200. this.wireframeLinejoin = 'round';
  13201. /**
  13202. * Whether the material is affected by fog or not.
  13203. *
  13204. * @type {boolean}
  13205. * @default true
  13206. */
  13207. this.fog = true;
  13208. this.setValues( parameters );
  13209. }
  13210. copy( source ) {
  13211. super.copy( source );
  13212. this.color.copy( source.color );
  13213. this.map = source.map;
  13214. this.lightMap = source.lightMap;
  13215. this.lightMapIntensity = source.lightMapIntensity;
  13216. this.aoMap = source.aoMap;
  13217. this.aoMapIntensity = source.aoMapIntensity;
  13218. this.specularMap = source.specularMap;
  13219. this.alphaMap = source.alphaMap;
  13220. this.envMap = source.envMap;
  13221. this.envMapRotation.copy( source.envMapRotation );
  13222. this.combine = source.combine;
  13223. this.reflectivity = source.reflectivity;
  13224. this.refractionRatio = source.refractionRatio;
  13225. this.wireframe = source.wireframe;
  13226. this.wireframeLinewidth = source.wireframeLinewidth;
  13227. this.wireframeLinecap = source.wireframeLinecap;
  13228. this.wireframeLinejoin = source.wireframeLinejoin;
  13229. this.fog = source.fog;
  13230. return this;
  13231. }
  13232. }
  13233. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13234. const _tables = /*@__PURE__*/ _generateTables();
  13235. function _generateTables() {
  13236. // float32 to float16 helpers
  13237. const buffer = new ArrayBuffer( 4 );
  13238. const floatView = new Float32Array( buffer );
  13239. const uint32View = new Uint32Array( buffer );
  13240. const baseTable = new Uint32Array( 512 );
  13241. const shiftTable = new Uint32Array( 512 );
  13242. for ( let i = 0; i < 256; ++ i ) {
  13243. const e = i - 127;
  13244. // very small number (0, -0)
  13245. if ( e < -27 ) {
  13246. baseTable[ i ] = 0x0000;
  13247. baseTable[ i | 0x100 ] = 0x8000;
  13248. shiftTable[ i ] = 24;
  13249. shiftTable[ i | 0x100 ] = 24;
  13250. // small number (denorm)
  13251. } else if ( e < -14 ) {
  13252. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13253. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13254. shiftTable[ i ] = - e - 1;
  13255. shiftTable[ i | 0x100 ] = - e - 1;
  13256. // normal number
  13257. } else if ( e <= 15 ) {
  13258. baseTable[ i ] = ( e + 15 ) << 10;
  13259. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13260. shiftTable[ i ] = 13;
  13261. shiftTable[ i | 0x100 ] = 13;
  13262. // large number (Infinity, -Infinity)
  13263. } else if ( e < 128 ) {
  13264. baseTable[ i ] = 0x7c00;
  13265. baseTable[ i | 0x100 ] = 0xfc00;
  13266. shiftTable[ i ] = 24;
  13267. shiftTable[ i | 0x100 ] = 24;
  13268. // stay (NaN, Infinity, -Infinity)
  13269. } else {
  13270. baseTable[ i ] = 0x7c00;
  13271. baseTable[ i | 0x100 ] = 0xfc00;
  13272. shiftTable[ i ] = 13;
  13273. shiftTable[ i | 0x100 ] = 13;
  13274. }
  13275. }
  13276. // float16 to float32 helpers
  13277. const mantissaTable = new Uint32Array( 2048 );
  13278. const exponentTable = new Uint32Array( 64 );
  13279. const offsetTable = new Uint32Array( 64 );
  13280. for ( let i = 1; i < 1024; ++ i ) {
  13281. let m = i << 13; // zero pad mantissa bits
  13282. let e = 0; // zero exponent
  13283. // normalized
  13284. while ( ( m & 0x00800000 ) === 0 ) {
  13285. m <<= 1;
  13286. e -= 0x00800000; // decrement exponent
  13287. }
  13288. m &= -8388609; // clear leading 1 bit
  13289. e += 0x38800000; // adjust bias
  13290. mantissaTable[ i ] = m | e;
  13291. }
  13292. for ( let i = 1024; i < 2048; ++ i ) {
  13293. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13294. }
  13295. for ( let i = 1; i < 31; ++ i ) {
  13296. exponentTable[ i ] = i << 23;
  13297. }
  13298. exponentTable[ 31 ] = 0x47800000;
  13299. exponentTable[ 32 ] = 0x80000000;
  13300. for ( let i = 33; i < 63; ++ i ) {
  13301. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13302. }
  13303. exponentTable[ 63 ] = 0xc7800000;
  13304. for ( let i = 1; i < 64; ++ i ) {
  13305. if ( i !== 32 ) {
  13306. offsetTable[ i ] = 1024;
  13307. }
  13308. }
  13309. return {
  13310. floatView: floatView,
  13311. uint32View: uint32View,
  13312. baseTable: baseTable,
  13313. shiftTable: shiftTable,
  13314. mantissaTable: mantissaTable,
  13315. exponentTable: exponentTable,
  13316. offsetTable: offsetTable
  13317. };
  13318. }
  13319. /**
  13320. * Returns a half precision floating point value (FP16) from the given single
  13321. * precision floating point value (FP32).
  13322. *
  13323. * @param {number} val - A single precision floating point value.
  13324. * @return {number} The FP16 value.
  13325. */
  13326. function toHalfFloat( val ) {
  13327. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  13328. val = clamp( val, -65504, 65504 );
  13329. _tables.floatView[ 0 ] = val;
  13330. const f = _tables.uint32View[ 0 ];
  13331. const e = ( f >> 23 ) & 0x1ff;
  13332. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13333. }
  13334. /**
  13335. * Returns a single precision floating point value (FP32) from the given half
  13336. * precision floating point value (FP16).
  13337. *
  13338. * @param {number} val - A half precision floating point value.
  13339. * @return {number} The FP32 value.
  13340. */
  13341. function fromHalfFloat( val ) {
  13342. const m = val >> 10;
  13343. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13344. return _tables.floatView[ 0 ];
  13345. }
  13346. /**
  13347. * A class containing utility functions for data.
  13348. *
  13349. * @hideconstructor
  13350. */
  13351. class DataUtils {
  13352. /**
  13353. * Returns a half precision floating point value (FP16) from the given single
  13354. * precision floating point value (FP32).
  13355. *
  13356. * @param {number} val - A single precision floating point value.
  13357. * @return {number} The FP16 value.
  13358. */
  13359. static toHalfFloat( val ) {
  13360. return toHalfFloat( val );
  13361. }
  13362. /**
  13363. * Returns a single precision floating point value (FP32) from the given half
  13364. * precision floating point value (FP16).
  13365. *
  13366. * @param {number} val - A half precision floating point value.
  13367. * @return {number} The FP32 value.
  13368. */
  13369. static fromHalfFloat( val ) {
  13370. return fromHalfFloat( val );
  13371. }
  13372. }
  13373. const _vector$9 = /*@__PURE__*/ new Vector3();
  13374. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13375. let _id$2 = 0;
  13376. /**
  13377. * This class stores data for an attribute (such as vertex positions, face
  13378. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13379. * a geometry, which allows for more efficient passing of data to the GPU.
  13380. *
  13381. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13382. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13383. */
  13384. class BufferAttribute {
  13385. /**
  13386. * Constructs a new buffer attribute.
  13387. *
  13388. * @param {TypedArray} array - The array holding the attribute data.
  13389. * @param {number} itemSize - The item size.
  13390. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13391. */
  13392. constructor( array, itemSize, normalized = false ) {
  13393. if ( Array.isArray( array ) ) {
  13394. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13395. }
  13396. /**
  13397. * This flag can be used for type testing.
  13398. *
  13399. * @type {boolean}
  13400. * @readonly
  13401. * @default true
  13402. */
  13403. this.isBufferAttribute = true;
  13404. /**
  13405. * The ID of the buffer attribute.
  13406. *
  13407. * @name BufferAttribute#id
  13408. * @type {number}
  13409. * @readonly
  13410. */
  13411. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  13412. /**
  13413. * The name of the buffer attribute.
  13414. *
  13415. * @type {string}
  13416. */
  13417. this.name = '';
  13418. /**
  13419. * The array holding the attribute data. It should have `itemSize * numVertices`
  13420. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13421. *
  13422. * @type {TypedArray}
  13423. */
  13424. this.array = array;
  13425. /**
  13426. * The number of values of the array that should be associated with a particular vertex.
  13427. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13428. * normal, or color), then the value should be `3`.
  13429. *
  13430. * @type {number}
  13431. */
  13432. this.itemSize = itemSize;
  13433. /**
  13434. * Represents the number of items this buffer attribute stores. It is internally computed
  13435. * by dividing the `array` length by the `itemSize`.
  13436. *
  13437. * @type {number}
  13438. * @readonly
  13439. */
  13440. this.count = array !== undefined ? array.length / itemSize : 0;
  13441. /**
  13442. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13443. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13444. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13445. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13446. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13447. *
  13448. * @type {boolean}
  13449. */
  13450. this.normalized = normalized;
  13451. /**
  13452. * Defines the intended usage pattern of the data store for optimization purposes.
  13453. *
  13454. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13455. * instantiate a new one and set the desired usage before the next render.
  13456. *
  13457. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13458. * @default StaticDrawUsage
  13459. */
  13460. this.usage = StaticDrawUsage;
  13461. /**
  13462. * This can be used to only update some components of stored vectors (for example, just the
  13463. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13464. *
  13465. * @type {Array<Object>}
  13466. */
  13467. this.updateRanges = [];
  13468. /**
  13469. * Configures the bound GPU type for use in shaders.
  13470. *
  13471. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13472. * For lower precision float types, use `Float16BufferAttribute`.
  13473. *
  13474. * @type {(FloatType|IntType)}
  13475. * @default FloatType
  13476. */
  13477. this.gpuType = FloatType;
  13478. /**
  13479. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13480. *
  13481. * @type {number}
  13482. */
  13483. this.version = 0;
  13484. }
  13485. /**
  13486. * A callback function that is executed after the renderer has transferred the attribute
  13487. * array data to the GPU.
  13488. */
  13489. onUploadCallback() {}
  13490. /**
  13491. * Flag to indicate that this attribute has changed and should be re-sent to
  13492. * the GPU. Set this to `true` when you modify the value of the array.
  13493. *
  13494. * @type {number}
  13495. * @default false
  13496. * @param {boolean} value
  13497. */
  13498. set needsUpdate( value ) {
  13499. if ( value === true ) this.version ++;
  13500. }
  13501. /**
  13502. * Sets the usage of this buffer attribute.
  13503. *
  13504. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13505. * @return {BufferAttribute} A reference to this buffer attribute.
  13506. */
  13507. setUsage( value ) {
  13508. this.usage = value;
  13509. return this;
  13510. }
  13511. /**
  13512. * Adds a range of data in the data array to be updated on the GPU.
  13513. *
  13514. * @param {number} start - Position at which to start update.
  13515. * @param {number} count - The number of components to update.
  13516. */
  13517. addUpdateRange( start, count ) {
  13518. this.updateRanges.push( { start, count } );
  13519. }
  13520. /**
  13521. * Clears the update ranges.
  13522. */
  13523. clearUpdateRanges() {
  13524. this.updateRanges.length = 0;
  13525. }
  13526. /**
  13527. * Copies the values of the given buffer attribute to this instance.
  13528. *
  13529. * @param {BufferAttribute} source - The buffer attribute to copy.
  13530. * @return {BufferAttribute} A reference to this instance.
  13531. */
  13532. copy( source ) {
  13533. this.name = source.name;
  13534. this.array = new source.array.constructor( source.array );
  13535. this.itemSize = source.itemSize;
  13536. this.count = source.count;
  13537. this.normalized = source.normalized;
  13538. this.usage = source.usage;
  13539. this.gpuType = source.gpuType;
  13540. return this;
  13541. }
  13542. /**
  13543. * Copies a vector from the given buffer attribute to this one. The start
  13544. * and destination position in the attribute buffers are represented by the
  13545. * given indices.
  13546. *
  13547. * @param {number} index1 - The destination index into this buffer attribute.
  13548. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13549. * @param {number} index2 - The source index into the given buffer attribute.
  13550. * @return {BufferAttribute} A reference to this instance.
  13551. */
  13552. copyAt( index1, attribute, index2 ) {
  13553. index1 *= this.itemSize;
  13554. index2 *= attribute.itemSize;
  13555. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13556. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13557. }
  13558. return this;
  13559. }
  13560. /**
  13561. * Copies the given array data into this buffer attribute.
  13562. *
  13563. * @param {(TypedArray|Array)} array - The array to copy.
  13564. * @return {BufferAttribute} A reference to this instance.
  13565. */
  13566. copyArray( array ) {
  13567. this.array.set( array );
  13568. return this;
  13569. }
  13570. /**
  13571. * Applies the given 3x3 matrix to the given attribute. Works with
  13572. * item size `2` and `3`.
  13573. *
  13574. * @param {Matrix3} m - The matrix to apply.
  13575. * @return {BufferAttribute} A reference to this instance.
  13576. */
  13577. applyMatrix3( m ) {
  13578. if ( this.itemSize === 2 ) {
  13579. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13580. _vector2$1.fromBufferAttribute( this, i );
  13581. _vector2$1.applyMatrix3( m );
  13582. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13583. }
  13584. } else if ( this.itemSize === 3 ) {
  13585. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13586. _vector$9.fromBufferAttribute( this, i );
  13587. _vector$9.applyMatrix3( m );
  13588. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13589. }
  13590. }
  13591. return this;
  13592. }
  13593. /**
  13594. * Applies the given 4x4 matrix to the given attribute. Only works with
  13595. * item size `3`.
  13596. *
  13597. * @param {Matrix4} m - The matrix to apply.
  13598. * @return {BufferAttribute} A reference to this instance.
  13599. */
  13600. applyMatrix4( m ) {
  13601. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13602. _vector$9.fromBufferAttribute( this, i );
  13603. _vector$9.applyMatrix4( m );
  13604. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13605. }
  13606. return this;
  13607. }
  13608. /**
  13609. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13610. * item size `3`.
  13611. *
  13612. * @param {Matrix3} m - The normal matrix to apply.
  13613. * @return {BufferAttribute} A reference to this instance.
  13614. */
  13615. applyNormalMatrix( m ) {
  13616. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13617. _vector$9.fromBufferAttribute( this, i );
  13618. _vector$9.applyNormalMatrix( m );
  13619. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13620. }
  13621. return this;
  13622. }
  13623. /**
  13624. * Applies the given 4x4 matrix to the given attribute. Only works with
  13625. * item size `3` and with direction vectors.
  13626. *
  13627. * @param {Matrix4} m - The matrix to apply.
  13628. * @return {BufferAttribute} A reference to this instance.
  13629. */
  13630. transformDirection( m ) {
  13631. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13632. _vector$9.fromBufferAttribute( this, i );
  13633. _vector$9.transformDirection( m );
  13634. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13635. }
  13636. return this;
  13637. }
  13638. /**
  13639. * Sets the given array data in the buffer attribute.
  13640. *
  13641. * @param {(TypedArray|Array)} value - The array data to set.
  13642. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13643. * @return {BufferAttribute} A reference to this instance.
  13644. */
  13645. set( value, offset = 0 ) {
  13646. // Matching BufferAttribute constructor, do not normalize the array.
  13647. this.array.set( value, offset );
  13648. return this;
  13649. }
  13650. /**
  13651. * Returns the given component of the vector at the given index.
  13652. *
  13653. * @param {number} index - The index into the buffer attribute.
  13654. * @param {number} component - The component index.
  13655. * @return {number} The returned value.
  13656. */
  13657. getComponent( index, component ) {
  13658. let value = this.array[ index * this.itemSize + component ];
  13659. if ( this.normalized ) value = denormalize( value, this.array );
  13660. return value;
  13661. }
  13662. /**
  13663. * Sets the given value to the given component of the vector at the given index.
  13664. *
  13665. * @param {number} index - The index into the buffer attribute.
  13666. * @param {number} component - The component index.
  13667. * @param {number} value - The value to set.
  13668. * @return {BufferAttribute} A reference to this instance.
  13669. */
  13670. setComponent( index, component, value ) {
  13671. if ( this.normalized ) value = normalize( value, this.array );
  13672. this.array[ index * this.itemSize + component ] = value;
  13673. return this;
  13674. }
  13675. /**
  13676. * Returns the x component of the vector at the given index.
  13677. *
  13678. * @param {number} index - The index into the buffer attribute.
  13679. * @return {number} The x component.
  13680. */
  13681. getX( index ) {
  13682. let x = this.array[ index * this.itemSize ];
  13683. if ( this.normalized ) x = denormalize( x, this.array );
  13684. return x;
  13685. }
  13686. /**
  13687. * Sets the x component of the vector at the given index.
  13688. *
  13689. * @param {number} index - The index into the buffer attribute.
  13690. * @param {number} x - The value to set.
  13691. * @return {BufferAttribute} A reference to this instance.
  13692. */
  13693. setX( index, x ) {
  13694. if ( this.normalized ) x = normalize( x, this.array );
  13695. this.array[ index * this.itemSize ] = x;
  13696. return this;
  13697. }
  13698. /**
  13699. * Returns the y component of the vector at the given index.
  13700. *
  13701. * @param {number} index - The index into the buffer attribute.
  13702. * @return {number} The y component.
  13703. */
  13704. getY( index ) {
  13705. let y = this.array[ index * this.itemSize + 1 ];
  13706. if ( this.normalized ) y = denormalize( y, this.array );
  13707. return y;
  13708. }
  13709. /**
  13710. * Sets the y component of the vector at the given index.
  13711. *
  13712. * @param {number} index - The index into the buffer attribute.
  13713. * @param {number} y - The value to set.
  13714. * @return {BufferAttribute} A reference to this instance.
  13715. */
  13716. setY( index, y ) {
  13717. if ( this.normalized ) y = normalize( y, this.array );
  13718. this.array[ index * this.itemSize + 1 ] = y;
  13719. return this;
  13720. }
  13721. /**
  13722. * Returns the z component of the vector at the given index.
  13723. *
  13724. * @param {number} index - The index into the buffer attribute.
  13725. * @return {number} The z component.
  13726. */
  13727. getZ( index ) {
  13728. let z = this.array[ index * this.itemSize + 2 ];
  13729. if ( this.normalized ) z = denormalize( z, this.array );
  13730. return z;
  13731. }
  13732. /**
  13733. * Sets the z component of the vector at the given index.
  13734. *
  13735. * @param {number} index - The index into the buffer attribute.
  13736. * @param {number} z - The value to set.
  13737. * @return {BufferAttribute} A reference to this instance.
  13738. */
  13739. setZ( index, z ) {
  13740. if ( this.normalized ) z = normalize( z, this.array );
  13741. this.array[ index * this.itemSize + 2 ] = z;
  13742. return this;
  13743. }
  13744. /**
  13745. * Returns the w component of the vector at the given index.
  13746. *
  13747. * @param {number} index - The index into the buffer attribute.
  13748. * @return {number} The w component.
  13749. */
  13750. getW( index ) {
  13751. let w = this.array[ index * this.itemSize + 3 ];
  13752. if ( this.normalized ) w = denormalize( w, this.array );
  13753. return w;
  13754. }
  13755. /**
  13756. * Sets the w component of the vector at the given index.
  13757. *
  13758. * @param {number} index - The index into the buffer attribute.
  13759. * @param {number} w - The value to set.
  13760. * @return {BufferAttribute} A reference to this instance.
  13761. */
  13762. setW( index, w ) {
  13763. if ( this.normalized ) w = normalize( w, this.array );
  13764. this.array[ index * this.itemSize + 3 ] = w;
  13765. return this;
  13766. }
  13767. /**
  13768. * Sets the x and y component of the vector at the given index.
  13769. *
  13770. * @param {number} index - The index into the buffer attribute.
  13771. * @param {number} x - The value for the x component to set.
  13772. * @param {number} y - The value for the y component to set.
  13773. * @return {BufferAttribute} A reference to this instance.
  13774. */
  13775. setXY( index, x, y ) {
  13776. index *= this.itemSize;
  13777. if ( this.normalized ) {
  13778. x = normalize( x, this.array );
  13779. y = normalize( y, this.array );
  13780. }
  13781. this.array[ index + 0 ] = x;
  13782. this.array[ index + 1 ] = y;
  13783. return this;
  13784. }
  13785. /**
  13786. * Sets the x, y and z component of the vector at the given index.
  13787. *
  13788. * @param {number} index - The index into the buffer attribute.
  13789. * @param {number} x - The value for the x component to set.
  13790. * @param {number} y - The value for the y component to set.
  13791. * @param {number} z - The value for the z component to set.
  13792. * @return {BufferAttribute} A reference to this instance.
  13793. */
  13794. setXYZ( index, x, y, z ) {
  13795. index *= this.itemSize;
  13796. if ( this.normalized ) {
  13797. x = normalize( x, this.array );
  13798. y = normalize( y, this.array );
  13799. z = normalize( z, this.array );
  13800. }
  13801. this.array[ index + 0 ] = x;
  13802. this.array[ index + 1 ] = y;
  13803. this.array[ index + 2 ] = z;
  13804. return this;
  13805. }
  13806. /**
  13807. * Sets the x, y, z and w component of the vector at the given index.
  13808. *
  13809. * @param {number} index - The index into the buffer attribute.
  13810. * @param {number} x - The value for the x component to set.
  13811. * @param {number} y - The value for the y component to set.
  13812. * @param {number} z - The value for the z component to set.
  13813. * @param {number} w - The value for the w component to set.
  13814. * @return {BufferAttribute} A reference to this instance.
  13815. */
  13816. setXYZW( index, x, y, z, w ) {
  13817. index *= this.itemSize;
  13818. if ( this.normalized ) {
  13819. x = normalize( x, this.array );
  13820. y = normalize( y, this.array );
  13821. z = normalize( z, this.array );
  13822. w = normalize( w, this.array );
  13823. }
  13824. this.array[ index + 0 ] = x;
  13825. this.array[ index + 1 ] = y;
  13826. this.array[ index + 2 ] = z;
  13827. this.array[ index + 3 ] = w;
  13828. return this;
  13829. }
  13830. /**
  13831. * Sets the given callback function that is executed after the Renderer has transferred
  13832. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13833. * the upload when attribute data are not needed anymore on the CPU side.
  13834. *
  13835. * @param {Function} callback - The `onUpload()` callback.
  13836. * @return {BufferAttribute} A reference to this instance.
  13837. */
  13838. onUpload( callback ) {
  13839. this.onUploadCallback = callback;
  13840. return this;
  13841. }
  13842. /**
  13843. * Returns a new buffer attribute with copied values from this instance.
  13844. *
  13845. * @return {BufferAttribute} A clone of this instance.
  13846. */
  13847. clone() {
  13848. return new this.constructor( this.array, this.itemSize ).copy( this );
  13849. }
  13850. /**
  13851. * Serializes the buffer attribute into JSON.
  13852. *
  13853. * @return {Object} A JSON object representing the serialized buffer attribute.
  13854. */
  13855. toJSON() {
  13856. const data = {
  13857. itemSize: this.itemSize,
  13858. type: this.array.constructor.name,
  13859. array: Array.from( this.array ),
  13860. normalized: this.normalized
  13861. };
  13862. if ( this.name !== '' ) data.name = this.name;
  13863. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13864. return data;
  13865. }
  13866. }
  13867. /**
  13868. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13869. * a plain `Array` instance.
  13870. *
  13871. * @augments BufferAttribute
  13872. */
  13873. class Int8BufferAttribute extends BufferAttribute {
  13874. /**
  13875. * Constructs a new buffer attribute.
  13876. *
  13877. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13878. * @param {number} itemSize - The item size.
  13879. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13880. */
  13881. constructor( array, itemSize, normalized ) {
  13882. super( new Int8Array( array ), itemSize, normalized );
  13883. }
  13884. }
  13885. /**
  13886. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13887. * a plain `Array` instance.
  13888. *
  13889. * @augments BufferAttribute
  13890. */
  13891. class Uint8BufferAttribute extends BufferAttribute {
  13892. /**
  13893. * Constructs a new buffer attribute.
  13894. *
  13895. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13896. * @param {number} itemSize - The item size.
  13897. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13898. */
  13899. constructor( array, itemSize, normalized ) {
  13900. super( new Uint8Array( array ), itemSize, normalized );
  13901. }
  13902. }
  13903. /**
  13904. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13905. * a plain `Array` instance.
  13906. *
  13907. * @augments BufferAttribute
  13908. */
  13909. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13910. /**
  13911. * Constructs a new buffer attribute.
  13912. *
  13913. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13914. * @param {number} itemSize - The item size.
  13915. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13916. */
  13917. constructor( array, itemSize, normalized ) {
  13918. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13919. }
  13920. }
  13921. /**
  13922. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13923. * a plain `Array` instance.
  13924. *
  13925. * @augments BufferAttribute
  13926. */
  13927. class Int16BufferAttribute extends BufferAttribute {
  13928. /**
  13929. * Constructs a new buffer attribute.
  13930. *
  13931. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13932. * @param {number} itemSize - The item size.
  13933. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13934. */
  13935. constructor( array, itemSize, normalized ) {
  13936. super( new Int16Array( array ), itemSize, normalized );
  13937. }
  13938. }
  13939. /**
  13940. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13941. * a plain `Array` instance.
  13942. *
  13943. * @augments BufferAttribute
  13944. */
  13945. class Uint16BufferAttribute extends BufferAttribute {
  13946. /**
  13947. * Constructs a new buffer attribute.
  13948. *
  13949. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13950. * @param {number} itemSize - The item size.
  13951. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13952. */
  13953. constructor( array, itemSize, normalized ) {
  13954. super( new Uint16Array( array ), itemSize, normalized );
  13955. }
  13956. }
  13957. /**
  13958. * Convenient class that can be used when creating a `Int32` buffer attribute with
  13959. * a plain `Array` instance.
  13960. *
  13961. * @augments BufferAttribute
  13962. */
  13963. class Int32BufferAttribute extends BufferAttribute {
  13964. /**
  13965. * Constructs a new buffer attribute.
  13966. *
  13967. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  13968. * @param {number} itemSize - The item size.
  13969. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13970. */
  13971. constructor( array, itemSize, normalized ) {
  13972. super( new Int32Array( array ), itemSize, normalized );
  13973. }
  13974. }
  13975. /**
  13976. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  13977. * a plain `Array` instance.
  13978. *
  13979. * @augments BufferAttribute
  13980. */
  13981. class Uint32BufferAttribute extends BufferAttribute {
  13982. /**
  13983. * Constructs a new buffer attribute.
  13984. *
  13985. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  13986. * @param {number} itemSize - The item size.
  13987. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13988. */
  13989. constructor( array, itemSize, normalized ) {
  13990. super( new Uint32Array( array ), itemSize, normalized );
  13991. }
  13992. }
  13993. /**
  13994. * Convenient class that can be used when creating a `Float16` buffer attribute with
  13995. * a plain `Array` instance.
  13996. *
  13997. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  13998. * browser support is still problematic.
  13999. *
  14000. * @augments BufferAttribute
  14001. */
  14002. class Float16BufferAttribute extends BufferAttribute {
  14003. /**
  14004. * Constructs a new buffer attribute.
  14005. *
  14006. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14007. * @param {number} itemSize - The item size.
  14008. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14009. */
  14010. constructor( array, itemSize, normalized ) {
  14011. super( new Uint16Array( array ), itemSize, normalized );
  14012. this.isFloat16BufferAttribute = true;
  14013. }
  14014. getX( index ) {
  14015. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14016. if ( this.normalized ) x = denormalize( x, this.array );
  14017. return x;
  14018. }
  14019. setX( index, x ) {
  14020. if ( this.normalized ) x = normalize( x, this.array );
  14021. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14022. return this;
  14023. }
  14024. getY( index ) {
  14025. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14026. if ( this.normalized ) y = denormalize( y, this.array );
  14027. return y;
  14028. }
  14029. setY( index, y ) {
  14030. if ( this.normalized ) y = normalize( y, this.array );
  14031. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14032. return this;
  14033. }
  14034. getZ( index ) {
  14035. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14036. if ( this.normalized ) z = denormalize( z, this.array );
  14037. return z;
  14038. }
  14039. setZ( index, z ) {
  14040. if ( this.normalized ) z = normalize( z, this.array );
  14041. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14042. return this;
  14043. }
  14044. getW( index ) {
  14045. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14046. if ( this.normalized ) w = denormalize( w, this.array );
  14047. return w;
  14048. }
  14049. setW( index, w ) {
  14050. if ( this.normalized ) w = normalize( w, this.array );
  14051. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14052. return this;
  14053. }
  14054. setXY( index, x, y ) {
  14055. index *= this.itemSize;
  14056. if ( this.normalized ) {
  14057. x = normalize( x, this.array );
  14058. y = normalize( y, this.array );
  14059. }
  14060. this.array[ index + 0 ] = toHalfFloat( x );
  14061. this.array[ index + 1 ] = toHalfFloat( y );
  14062. return this;
  14063. }
  14064. setXYZ( index, x, y, z ) {
  14065. index *= this.itemSize;
  14066. if ( this.normalized ) {
  14067. x = normalize( x, this.array );
  14068. y = normalize( y, this.array );
  14069. z = normalize( z, this.array );
  14070. }
  14071. this.array[ index + 0 ] = toHalfFloat( x );
  14072. this.array[ index + 1 ] = toHalfFloat( y );
  14073. this.array[ index + 2 ] = toHalfFloat( z );
  14074. return this;
  14075. }
  14076. setXYZW( index, x, y, z, w ) {
  14077. index *= this.itemSize;
  14078. if ( this.normalized ) {
  14079. x = normalize( x, this.array );
  14080. y = normalize( y, this.array );
  14081. z = normalize( z, this.array );
  14082. w = normalize( w, this.array );
  14083. }
  14084. this.array[ index + 0 ] = toHalfFloat( x );
  14085. this.array[ index + 1 ] = toHalfFloat( y );
  14086. this.array[ index + 2 ] = toHalfFloat( z );
  14087. this.array[ index + 3 ] = toHalfFloat( w );
  14088. return this;
  14089. }
  14090. }
  14091. /**
  14092. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14093. * a plain `Array` instance.
  14094. *
  14095. * @augments BufferAttribute
  14096. */
  14097. class Float32BufferAttribute extends BufferAttribute {
  14098. /**
  14099. * Constructs a new buffer attribute.
  14100. *
  14101. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14102. * @param {number} itemSize - The item size.
  14103. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14104. */
  14105. constructor( array, itemSize, normalized ) {
  14106. super( new Float32Array( array ), itemSize, normalized );
  14107. }
  14108. }
  14109. let _id$1 = 0;
  14110. const _m1 = /*@__PURE__*/ new Matrix4();
  14111. const _obj = /*@__PURE__*/ new Object3D();
  14112. const _offset = /*@__PURE__*/ new Vector3();
  14113. const _box$2 = /*@__PURE__*/ new Box3();
  14114. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14115. const _vector$8 = /*@__PURE__*/ new Vector3();
  14116. /**
  14117. * A representation of mesh, line, or point geometry. Includes vertex
  14118. * positions, face indices, normals, colors, UVs, and custom attributes
  14119. * within buffers, reducing the cost of passing all this data to the GPU.
  14120. *
  14121. * ```js
  14122. * const geometry = new THREE.BufferGeometry();
  14123. * // create a simple square shape. We duplicate the top left and bottom right
  14124. * // vertices because each vertex needs to appear once per triangle.
  14125. * const vertices = new Float32Array( [
  14126. * -1.0, -1.0, 1.0, // v0
  14127. * 1.0, -1.0, 1.0, // v1
  14128. * 1.0, 1.0, 1.0, // v2
  14129. *
  14130. * 1.0, 1.0, 1.0, // v3
  14131. * -1.0, 1.0, 1.0, // v4
  14132. * -1.0, -1.0, 1.0 // v5
  14133. * ] );
  14134. * // itemSize = 3 because there are 3 values (components) per vertex
  14135. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14136. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14137. * const mesh = new THREE.Mesh( geometry, material );
  14138. * ```
  14139. *
  14140. * @augments EventDispatcher
  14141. */
  14142. class BufferGeometry extends EventDispatcher {
  14143. /**
  14144. * Constructs a new geometry.
  14145. */
  14146. constructor() {
  14147. super();
  14148. /**
  14149. * This flag can be used for type testing.
  14150. *
  14151. * @type {boolean}
  14152. * @readonly
  14153. * @default true
  14154. */
  14155. this.isBufferGeometry = true;
  14156. /**
  14157. * The ID of the geometry.
  14158. *
  14159. * @name BufferGeometry#id
  14160. * @type {number}
  14161. * @readonly
  14162. */
  14163. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  14164. /**
  14165. * The UUID of the geometry.
  14166. *
  14167. * @type {string}
  14168. * @readonly
  14169. */
  14170. this.uuid = generateUUID();
  14171. /**
  14172. * The name of the geometry.
  14173. *
  14174. * @type {string}
  14175. */
  14176. this.name = '';
  14177. this.type = 'BufferGeometry';
  14178. /**
  14179. * Allows for vertices to be re-used across multiple triangles; this is
  14180. * called using "indexed triangles". Each triangle is associated with the
  14181. * indices of three vertices. This attribute therefore stores the index of
  14182. * each vertex for each triangular face. If this attribute is not set, the
  14183. * renderer assumes that each three contiguous positions represent a single triangle.
  14184. *
  14185. * @type {?BufferAttribute}
  14186. * @default null
  14187. */
  14188. this.index = null;
  14189. /**
  14190. * A (storage) buffer attribute which was generated with a compute shader and
  14191. * now defines indirect draw calls.
  14192. *
  14193. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14194. *
  14195. * @type {?BufferAttribute}
  14196. * @default null
  14197. */
  14198. this.indirect = null;
  14199. /**
  14200. * This dictionary has as id the name of the attribute to be set and as value
  14201. * the buffer attribute to set it to. Rather than accessing this property directly,
  14202. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14203. *
  14204. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14205. */
  14206. this.attributes = {};
  14207. /**
  14208. * This dictionary holds the morph targets of the geometry.
  14209. *
  14210. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14211. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14212. *
  14213. * @type {Object}
  14214. */
  14215. this.morphAttributes = {};
  14216. /**
  14217. * Used to control the morph target behavior; when set to `true`, the morph
  14218. * target data is treated as relative offsets, rather than as absolute
  14219. * positions/normals.
  14220. *
  14221. * @type {boolean}
  14222. * @default false
  14223. */
  14224. this.morphTargetsRelative = false;
  14225. /**
  14226. * Split the geometry into groups, each of which will be rendered in a
  14227. * separate draw call. This allows an array of materials to be used with the geometry.
  14228. *
  14229. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14230. *
  14231. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14232. * indices, and must not leave vertices or indices unused.
  14233. *
  14234. * @type {Array<Object>}
  14235. */
  14236. this.groups = [];
  14237. /**
  14238. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14239. *
  14240. * @type {Box3}
  14241. * @default null
  14242. */
  14243. this.boundingBox = null;
  14244. /**
  14245. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14246. *
  14247. * @type {Sphere}
  14248. * @default null
  14249. */
  14250. this.boundingSphere = null;
  14251. /**
  14252. * Determines the part of the geometry to render. This should not be set directly,
  14253. * instead use `setDrawRange()`.
  14254. *
  14255. * @type {{start:number,count:number}}
  14256. */
  14257. this.drawRange = { start: 0, count: Infinity };
  14258. /**
  14259. * An object that can be used to store custom data about the geometry.
  14260. * It should not hold references to functions as these will not be cloned.
  14261. *
  14262. * @type {Object}
  14263. */
  14264. this.userData = {};
  14265. }
  14266. /**
  14267. * Returns the index of this geometry.
  14268. *
  14269. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14270. */
  14271. getIndex() {
  14272. return this.index;
  14273. }
  14274. /**
  14275. * Sets the given index to this geometry.
  14276. *
  14277. * @param {Array<number>|BufferAttribute} index - The index to set.
  14278. * @return {BufferGeometry} A reference to this instance.
  14279. */
  14280. setIndex( index ) {
  14281. if ( Array.isArray( index ) ) {
  14282. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14283. } else {
  14284. this.index = index;
  14285. }
  14286. return this;
  14287. }
  14288. /**
  14289. * Sets the given indirect attribute to this geometry.
  14290. *
  14291. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14292. * @return {BufferGeometry} A reference to this instance.
  14293. */
  14294. setIndirect( indirect ) {
  14295. this.indirect = indirect;
  14296. return this;
  14297. }
  14298. /**
  14299. * Returns the indirect attribute of this geometry.
  14300. *
  14301. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14302. */
  14303. getIndirect() {
  14304. return this.indirect;
  14305. }
  14306. /**
  14307. * Returns the buffer attribute for the given name.
  14308. *
  14309. * @param {string} name - The attribute name.
  14310. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14311. * Returns `undefined` if not attribute has been found.
  14312. */
  14313. getAttribute( name ) {
  14314. return this.attributes[ name ];
  14315. }
  14316. /**
  14317. * Sets the given attribute for the given name.
  14318. *
  14319. * @param {string} name - The attribute name.
  14320. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14321. * @return {BufferGeometry} A reference to this instance.
  14322. */
  14323. setAttribute( name, attribute ) {
  14324. this.attributes[ name ] = attribute;
  14325. return this;
  14326. }
  14327. /**
  14328. * Deletes the attribute for the given name.
  14329. *
  14330. * @param {string} name - The attribute name to delete.
  14331. * @return {BufferGeometry} A reference to this instance.
  14332. */
  14333. deleteAttribute( name ) {
  14334. delete this.attributes[ name ];
  14335. return this;
  14336. }
  14337. /**
  14338. * Returns `true` if this geometry has an attribute for the given name.
  14339. *
  14340. * @param {string} name - The attribute name.
  14341. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14342. */
  14343. hasAttribute( name ) {
  14344. return this.attributes[ name ] !== undefined;
  14345. }
  14346. /**
  14347. * Adds a group to this geometry.
  14348. *
  14349. * @param {number} start - The first element in this draw call. That is the first
  14350. * vertex for non-indexed geometry, otherwise the first triangle index.
  14351. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14352. * @param {number} [materialIndex=0] - The material array index to use.
  14353. */
  14354. addGroup( start, count, materialIndex = 0 ) {
  14355. this.groups.push( {
  14356. start: start,
  14357. count: count,
  14358. materialIndex: materialIndex
  14359. } );
  14360. }
  14361. /**
  14362. * Clears all groups.
  14363. */
  14364. clearGroups() {
  14365. this.groups = [];
  14366. }
  14367. /**
  14368. * Sets the draw range for this geometry.
  14369. *
  14370. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14371. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14372. * For indexed BufferGeometry, `count` is the number of indices to render.
  14373. */
  14374. setDrawRange( start, count ) {
  14375. this.drawRange.start = start;
  14376. this.drawRange.count = count;
  14377. }
  14378. /**
  14379. * Applies the given 4x4 transformation matrix to the geometry.
  14380. *
  14381. * @param {Matrix4} matrix - The matrix to apply.
  14382. * @return {BufferGeometry} A reference to this instance.
  14383. */
  14384. applyMatrix4( matrix ) {
  14385. const position = this.attributes.position;
  14386. if ( position !== undefined ) {
  14387. position.applyMatrix4( matrix );
  14388. position.needsUpdate = true;
  14389. }
  14390. const normal = this.attributes.normal;
  14391. if ( normal !== undefined ) {
  14392. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14393. normal.applyNormalMatrix( normalMatrix );
  14394. normal.needsUpdate = true;
  14395. }
  14396. const tangent = this.attributes.tangent;
  14397. if ( tangent !== undefined ) {
  14398. tangent.transformDirection( matrix );
  14399. tangent.needsUpdate = true;
  14400. }
  14401. if ( this.boundingBox !== null ) {
  14402. this.computeBoundingBox();
  14403. }
  14404. if ( this.boundingSphere !== null ) {
  14405. this.computeBoundingSphere();
  14406. }
  14407. return this;
  14408. }
  14409. /**
  14410. * Applies the rotation represented by the Quaternion to the geometry.
  14411. *
  14412. * @param {Quaternion} q - The Quaternion to apply.
  14413. * @return {BufferGeometry} A reference to this instance.
  14414. */
  14415. applyQuaternion( q ) {
  14416. _m1.makeRotationFromQuaternion( q );
  14417. this.applyMatrix4( _m1 );
  14418. return this;
  14419. }
  14420. /**
  14421. * Rotates the geometry about the X axis. This is typically done as a one time
  14422. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14423. * real-time mesh rotation.
  14424. *
  14425. * @param {number} angle - The angle in radians.
  14426. * @return {BufferGeometry} A reference to this instance.
  14427. */
  14428. rotateX( angle ) {
  14429. // rotate geometry around world x-axis
  14430. _m1.makeRotationX( angle );
  14431. this.applyMatrix4( _m1 );
  14432. return this;
  14433. }
  14434. /**
  14435. * Rotates the geometry about the Y axis. This is typically done as a one time
  14436. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14437. * real-time mesh rotation.
  14438. *
  14439. * @param {number} angle - The angle in radians.
  14440. * @return {BufferGeometry} A reference to this instance.
  14441. */
  14442. rotateY( angle ) {
  14443. // rotate geometry around world y-axis
  14444. _m1.makeRotationY( angle );
  14445. this.applyMatrix4( _m1 );
  14446. return this;
  14447. }
  14448. /**
  14449. * Rotates the geometry about the Z axis. This is typically done as a one time
  14450. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14451. * real-time mesh rotation.
  14452. *
  14453. * @param {number} angle - The angle in radians.
  14454. * @return {BufferGeometry} A reference to this instance.
  14455. */
  14456. rotateZ( angle ) {
  14457. // rotate geometry around world z-axis
  14458. _m1.makeRotationZ( angle );
  14459. this.applyMatrix4( _m1 );
  14460. return this;
  14461. }
  14462. /**
  14463. * Translates the geometry. This is typically done as a one time
  14464. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14465. * real-time mesh rotation.
  14466. *
  14467. * @param {number} x - The x offset.
  14468. * @param {number} y - The y offset.
  14469. * @param {number} z - The z offset.
  14470. * @return {BufferGeometry} A reference to this instance.
  14471. */
  14472. translate( x, y, z ) {
  14473. // translate geometry
  14474. _m1.makeTranslation( x, y, z );
  14475. this.applyMatrix4( _m1 );
  14476. return this;
  14477. }
  14478. /**
  14479. * Scales the geometry. This is typically done as a one time
  14480. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14481. * real-time mesh rotation.
  14482. *
  14483. * @param {number} x - The x scale.
  14484. * @param {number} y - The y scale.
  14485. * @param {number} z - The z scale.
  14486. * @return {BufferGeometry} A reference to this instance.
  14487. */
  14488. scale( x, y, z ) {
  14489. // scale geometry
  14490. _m1.makeScale( x, y, z );
  14491. this.applyMatrix4( _m1 );
  14492. return this;
  14493. }
  14494. /**
  14495. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14496. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14497. * real-time mesh rotation.
  14498. *
  14499. * @param {Vector3} vector - The target point.
  14500. * @return {BufferGeometry} A reference to this instance.
  14501. */
  14502. lookAt( vector ) {
  14503. _obj.lookAt( vector );
  14504. _obj.updateMatrix();
  14505. this.applyMatrix4( _obj.matrix );
  14506. return this;
  14507. }
  14508. /**
  14509. * Center the geometry based on its bounding box.
  14510. *
  14511. * @return {BufferGeometry} A reference to this instance.
  14512. */
  14513. center() {
  14514. this.computeBoundingBox();
  14515. this.boundingBox.getCenter( _offset ).negate();
  14516. this.translate( _offset.x, _offset.y, _offset.z );
  14517. return this;
  14518. }
  14519. /**
  14520. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14521. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14522. * set to `0`.
  14523. *
  14524. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14525. * data from the array. The length of the array must match the vertex count.
  14526. *
  14527. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14528. * @return {BufferGeometry} A reference to this instance.
  14529. */
  14530. setFromPoints( points ) {
  14531. const positionAttribute = this.getAttribute( 'position' );
  14532. if ( positionAttribute === undefined ) {
  14533. const position = [];
  14534. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14535. const point = points[ i ];
  14536. position.push( point.x, point.y, point.z || 0 );
  14537. }
  14538. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14539. } else {
  14540. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14541. for ( let i = 0; i < l; i ++ ) {
  14542. const point = points[ i ];
  14543. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14544. }
  14545. if ( points.length > positionAttribute.count ) {
  14546. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14547. }
  14548. positionAttribute.needsUpdate = true;
  14549. }
  14550. return this;
  14551. }
  14552. /**
  14553. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14554. * The bounding box is not computed by the engine; it must be computed by your app.
  14555. * You may need to recompute the bounding box if the geometry vertices are modified.
  14556. */
  14557. computeBoundingBox() {
  14558. if ( this.boundingBox === null ) {
  14559. this.boundingBox = new Box3();
  14560. }
  14561. const position = this.attributes.position;
  14562. const morphAttributesPosition = this.morphAttributes.position;
  14563. if ( position && position.isGLBufferAttribute ) {
  14564. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14565. this.boundingBox.set(
  14566. new Vector3( - Infinity, - Infinity, - Infinity ),
  14567. new Vector3( + Infinity, + Infinity, + Infinity )
  14568. );
  14569. return;
  14570. }
  14571. if ( position !== undefined ) {
  14572. this.boundingBox.setFromBufferAttribute( position );
  14573. // process morph attributes if present
  14574. if ( morphAttributesPosition ) {
  14575. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14576. const morphAttribute = morphAttributesPosition[ i ];
  14577. _box$2.setFromBufferAttribute( morphAttribute );
  14578. if ( this.morphTargetsRelative ) {
  14579. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14580. this.boundingBox.expandByPoint( _vector$8 );
  14581. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14582. this.boundingBox.expandByPoint( _vector$8 );
  14583. } else {
  14584. this.boundingBox.expandByPoint( _box$2.min );
  14585. this.boundingBox.expandByPoint( _box$2.max );
  14586. }
  14587. }
  14588. }
  14589. } else {
  14590. this.boundingBox.makeEmpty();
  14591. }
  14592. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14593. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14594. }
  14595. }
  14596. /**
  14597. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14598. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14599. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14600. */
  14601. computeBoundingSphere() {
  14602. if ( this.boundingSphere === null ) {
  14603. this.boundingSphere = new Sphere();
  14604. }
  14605. const position = this.attributes.position;
  14606. const morphAttributesPosition = this.morphAttributes.position;
  14607. if ( position && position.isGLBufferAttribute ) {
  14608. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14609. this.boundingSphere.set( new Vector3(), Infinity );
  14610. return;
  14611. }
  14612. if ( position ) {
  14613. // first, find the center of the bounding sphere
  14614. const center = this.boundingSphere.center;
  14615. _box$2.setFromBufferAttribute( position );
  14616. // process morph attributes if present
  14617. if ( morphAttributesPosition ) {
  14618. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14619. const morphAttribute = morphAttributesPosition[ i ];
  14620. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14621. if ( this.morphTargetsRelative ) {
  14622. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14623. _box$2.expandByPoint( _vector$8 );
  14624. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14625. _box$2.expandByPoint( _vector$8 );
  14626. } else {
  14627. _box$2.expandByPoint( _boxMorphTargets.min );
  14628. _box$2.expandByPoint( _boxMorphTargets.max );
  14629. }
  14630. }
  14631. }
  14632. _box$2.getCenter( center );
  14633. // second, try to find a boundingSphere with a radius smaller than the
  14634. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14635. let maxRadiusSq = 0;
  14636. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14637. _vector$8.fromBufferAttribute( position, i );
  14638. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14639. }
  14640. // process morph attributes if present
  14641. if ( morphAttributesPosition ) {
  14642. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14643. const morphAttribute = morphAttributesPosition[ i ];
  14644. const morphTargetsRelative = this.morphTargetsRelative;
  14645. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14646. _vector$8.fromBufferAttribute( morphAttribute, j );
  14647. if ( morphTargetsRelative ) {
  14648. _offset.fromBufferAttribute( position, j );
  14649. _vector$8.add( _offset );
  14650. }
  14651. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14652. }
  14653. }
  14654. }
  14655. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14656. if ( isNaN( this.boundingSphere.radius ) ) {
  14657. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14658. }
  14659. }
  14660. }
  14661. /**
  14662. * Calculates and adds a tangent attribute to this geometry.
  14663. *
  14664. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14665. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14666. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14667. */
  14668. computeTangents() {
  14669. const index = this.index;
  14670. const attributes = this.attributes;
  14671. // based on http://www.terathon.com/code/tangent.html
  14672. // (per vertex tangents)
  14673. if ( index === null ||
  14674. attributes.position === undefined ||
  14675. attributes.normal === undefined ||
  14676. attributes.uv === undefined ) {
  14677. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14678. return;
  14679. }
  14680. const positionAttribute = attributes.position;
  14681. const normalAttribute = attributes.normal;
  14682. const uvAttribute = attributes.uv;
  14683. if ( this.hasAttribute( 'tangent' ) === false ) {
  14684. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14685. }
  14686. const tangentAttribute = this.getAttribute( 'tangent' );
  14687. const tan1 = [], tan2 = [];
  14688. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14689. tan1[ i ] = new Vector3();
  14690. tan2[ i ] = new Vector3();
  14691. }
  14692. const vA = new Vector3(),
  14693. vB = new Vector3(),
  14694. vC = new Vector3(),
  14695. uvA = new Vector2(),
  14696. uvB = new Vector2(),
  14697. uvC = new Vector2(),
  14698. sdir = new Vector3(),
  14699. tdir = new Vector3();
  14700. function handleTriangle( a, b, c ) {
  14701. vA.fromBufferAttribute( positionAttribute, a );
  14702. vB.fromBufferAttribute( positionAttribute, b );
  14703. vC.fromBufferAttribute( positionAttribute, c );
  14704. uvA.fromBufferAttribute( uvAttribute, a );
  14705. uvB.fromBufferAttribute( uvAttribute, b );
  14706. uvC.fromBufferAttribute( uvAttribute, c );
  14707. vB.sub( vA );
  14708. vC.sub( vA );
  14709. uvB.sub( uvA );
  14710. uvC.sub( uvA );
  14711. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14712. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14713. if ( ! isFinite( r ) ) return;
  14714. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14715. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14716. tan1[ a ].add( sdir );
  14717. tan1[ b ].add( sdir );
  14718. tan1[ c ].add( sdir );
  14719. tan2[ a ].add( tdir );
  14720. tan2[ b ].add( tdir );
  14721. tan2[ c ].add( tdir );
  14722. }
  14723. let groups = this.groups;
  14724. if ( groups.length === 0 ) {
  14725. groups = [ {
  14726. start: 0,
  14727. count: index.count
  14728. } ];
  14729. }
  14730. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14731. const group = groups[ i ];
  14732. const start = group.start;
  14733. const count = group.count;
  14734. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14735. handleTriangle(
  14736. index.getX( j + 0 ),
  14737. index.getX( j + 1 ),
  14738. index.getX( j + 2 )
  14739. );
  14740. }
  14741. }
  14742. const tmp = new Vector3(), tmp2 = new Vector3();
  14743. const n = new Vector3(), n2 = new Vector3();
  14744. function handleVertex( v ) {
  14745. n.fromBufferAttribute( normalAttribute, v );
  14746. n2.copy( n );
  14747. const t = tan1[ v ];
  14748. // Gram-Schmidt orthogonalize
  14749. tmp.copy( t );
  14750. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14751. // Calculate handedness
  14752. tmp2.crossVectors( n2, t );
  14753. const test = tmp2.dot( tan2[ v ] );
  14754. const w = ( test < 0.0 ) ? -1 : 1.0;
  14755. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14756. }
  14757. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14758. const group = groups[ i ];
  14759. const start = group.start;
  14760. const count = group.count;
  14761. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14762. handleVertex( index.getX( j + 0 ) );
  14763. handleVertex( index.getX( j + 1 ) );
  14764. handleVertex( index.getX( j + 2 ) );
  14765. }
  14766. }
  14767. }
  14768. /**
  14769. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14770. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14771. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14772. * to be the same as the face normal.
  14773. */
  14774. computeVertexNormals() {
  14775. const index = this.index;
  14776. const positionAttribute = this.getAttribute( 'position' );
  14777. if ( positionAttribute !== undefined ) {
  14778. let normalAttribute = this.getAttribute( 'normal' );
  14779. if ( normalAttribute === undefined ) {
  14780. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14781. this.setAttribute( 'normal', normalAttribute );
  14782. } else {
  14783. // reset existing normals to zero
  14784. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14785. normalAttribute.setXYZ( i, 0, 0, 0 );
  14786. }
  14787. }
  14788. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14789. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14790. const cb = new Vector3(), ab = new Vector3();
  14791. // indexed elements
  14792. if ( index ) {
  14793. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14794. const vA = index.getX( i + 0 );
  14795. const vB = index.getX( i + 1 );
  14796. const vC = index.getX( i + 2 );
  14797. pA.fromBufferAttribute( positionAttribute, vA );
  14798. pB.fromBufferAttribute( positionAttribute, vB );
  14799. pC.fromBufferAttribute( positionAttribute, vC );
  14800. cb.subVectors( pC, pB );
  14801. ab.subVectors( pA, pB );
  14802. cb.cross( ab );
  14803. nA.fromBufferAttribute( normalAttribute, vA );
  14804. nB.fromBufferAttribute( normalAttribute, vB );
  14805. nC.fromBufferAttribute( normalAttribute, vC );
  14806. nA.add( cb );
  14807. nB.add( cb );
  14808. nC.add( cb );
  14809. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14810. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14811. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14812. }
  14813. } else {
  14814. // non-indexed elements (unconnected triangle soup)
  14815. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14816. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14817. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14818. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14819. cb.subVectors( pC, pB );
  14820. ab.subVectors( pA, pB );
  14821. cb.cross( ab );
  14822. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14823. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14824. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14825. }
  14826. }
  14827. this.normalizeNormals();
  14828. normalAttribute.needsUpdate = true;
  14829. }
  14830. }
  14831. /**
  14832. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14833. * correct lighting on the geometry surfaces.
  14834. */
  14835. normalizeNormals() {
  14836. const normals = this.attributes.normal;
  14837. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14838. _vector$8.fromBufferAttribute( normals, i );
  14839. _vector$8.normalize();
  14840. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14841. }
  14842. }
  14843. /**
  14844. * Return a new non-index version of this indexed geometry. If the geometry
  14845. * is already non-indexed, the method is a NOOP.
  14846. *
  14847. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14848. */
  14849. toNonIndexed() {
  14850. function convertBufferAttribute( attribute, indices ) {
  14851. const array = attribute.array;
  14852. const itemSize = attribute.itemSize;
  14853. const normalized = attribute.normalized;
  14854. const array2 = new array.constructor( indices.length * itemSize );
  14855. let index = 0, index2 = 0;
  14856. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14857. if ( attribute.isInterleavedBufferAttribute ) {
  14858. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14859. } else {
  14860. index = indices[ i ] * itemSize;
  14861. }
  14862. for ( let j = 0; j < itemSize; j ++ ) {
  14863. array2[ index2 ++ ] = array[ index ++ ];
  14864. }
  14865. }
  14866. return new BufferAttribute( array2, itemSize, normalized );
  14867. }
  14868. //
  14869. if ( this.index === null ) {
  14870. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14871. return this;
  14872. }
  14873. const geometry2 = new BufferGeometry();
  14874. const indices = this.index.array;
  14875. const attributes = this.attributes;
  14876. // attributes
  14877. for ( const name in attributes ) {
  14878. const attribute = attributes[ name ];
  14879. const newAttribute = convertBufferAttribute( attribute, indices );
  14880. geometry2.setAttribute( name, newAttribute );
  14881. }
  14882. // morph attributes
  14883. const morphAttributes = this.morphAttributes;
  14884. for ( const name in morphAttributes ) {
  14885. const morphArray = [];
  14886. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14887. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14888. const attribute = morphAttribute[ i ];
  14889. const newAttribute = convertBufferAttribute( attribute, indices );
  14890. morphArray.push( newAttribute );
  14891. }
  14892. geometry2.morphAttributes[ name ] = morphArray;
  14893. }
  14894. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14895. // groups
  14896. const groups = this.groups;
  14897. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14898. const group = groups[ i ];
  14899. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14900. }
  14901. return geometry2;
  14902. }
  14903. /**
  14904. * Serializes the geometry into JSON.
  14905. *
  14906. * @return {Object} A JSON object representing the serialized geometry.
  14907. */
  14908. toJSON() {
  14909. const data = {
  14910. metadata: {
  14911. version: 4.7,
  14912. type: 'BufferGeometry',
  14913. generator: 'BufferGeometry.toJSON'
  14914. }
  14915. };
  14916. // standard BufferGeometry serialization
  14917. data.uuid = this.uuid;
  14918. data.type = this.type;
  14919. if ( this.name !== '' ) data.name = this.name;
  14920. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14921. if ( this.parameters !== undefined ) {
  14922. const parameters = this.parameters;
  14923. for ( const key in parameters ) {
  14924. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14925. }
  14926. return data;
  14927. }
  14928. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14929. data.data = { attributes: {} };
  14930. const index = this.index;
  14931. if ( index !== null ) {
  14932. data.data.index = {
  14933. type: index.array.constructor.name,
  14934. array: Array.prototype.slice.call( index.array )
  14935. };
  14936. }
  14937. const attributes = this.attributes;
  14938. for ( const key in attributes ) {
  14939. const attribute = attributes[ key ];
  14940. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14941. }
  14942. const morphAttributes = {};
  14943. let hasMorphAttributes = false;
  14944. for ( const key in this.morphAttributes ) {
  14945. const attributeArray = this.morphAttributes[ key ];
  14946. const array = [];
  14947. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14948. const attribute = attributeArray[ i ];
  14949. array.push( attribute.toJSON( data.data ) );
  14950. }
  14951. if ( array.length > 0 ) {
  14952. morphAttributes[ key ] = array;
  14953. hasMorphAttributes = true;
  14954. }
  14955. }
  14956. if ( hasMorphAttributes ) {
  14957. data.data.morphAttributes = morphAttributes;
  14958. data.data.morphTargetsRelative = this.morphTargetsRelative;
  14959. }
  14960. const groups = this.groups;
  14961. if ( groups.length > 0 ) {
  14962. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  14963. }
  14964. const boundingSphere = this.boundingSphere;
  14965. if ( boundingSphere !== null ) {
  14966. data.data.boundingSphere = boundingSphere.toJSON();
  14967. }
  14968. return data;
  14969. }
  14970. /**
  14971. * Returns a new geometry with copied values from this instance.
  14972. *
  14973. * @return {BufferGeometry} A clone of this instance.
  14974. */
  14975. clone() {
  14976. return new this.constructor().copy( this );
  14977. }
  14978. /**
  14979. * Copies the values of the given geometry to this instance.
  14980. *
  14981. * @param {BufferGeometry} source - The geometry to copy.
  14982. * @return {BufferGeometry} A reference to this instance.
  14983. */
  14984. copy( source ) {
  14985. // reset
  14986. this.index = null;
  14987. this.attributes = {};
  14988. this.morphAttributes = {};
  14989. this.groups = [];
  14990. this.boundingBox = null;
  14991. this.boundingSphere = null;
  14992. // used for storing cloned, shared data
  14993. const data = {};
  14994. // name
  14995. this.name = source.name;
  14996. // index
  14997. const index = source.index;
  14998. if ( index !== null ) {
  14999. this.setIndex( index.clone() );
  15000. }
  15001. // attributes
  15002. const attributes = source.attributes;
  15003. for ( const name in attributes ) {
  15004. const attribute = attributes[ name ];
  15005. this.setAttribute( name, attribute.clone( data ) );
  15006. }
  15007. // morph attributes
  15008. const morphAttributes = source.morphAttributes;
  15009. for ( const name in morphAttributes ) {
  15010. const array = [];
  15011. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15012. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15013. array.push( morphAttribute[ i ].clone( data ) );
  15014. }
  15015. this.morphAttributes[ name ] = array;
  15016. }
  15017. this.morphTargetsRelative = source.morphTargetsRelative;
  15018. // groups
  15019. const groups = source.groups;
  15020. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15021. const group = groups[ i ];
  15022. this.addGroup( group.start, group.count, group.materialIndex );
  15023. }
  15024. // bounding box
  15025. const boundingBox = source.boundingBox;
  15026. if ( boundingBox !== null ) {
  15027. this.boundingBox = boundingBox.clone();
  15028. }
  15029. // bounding sphere
  15030. const boundingSphere = source.boundingSphere;
  15031. if ( boundingSphere !== null ) {
  15032. this.boundingSphere = boundingSphere.clone();
  15033. }
  15034. // draw range
  15035. this.drawRange.start = source.drawRange.start;
  15036. this.drawRange.count = source.drawRange.count;
  15037. // user data
  15038. this.userData = source.userData;
  15039. return this;
  15040. }
  15041. /**
  15042. * Frees the GPU-related resources allocated by this instance. Call this
  15043. * method whenever this instance is no longer used in your app.
  15044. *
  15045. * @fires BufferGeometry#dispose
  15046. */
  15047. dispose() {
  15048. this.dispatchEvent( { type: 'dispose' } );
  15049. }
  15050. }
  15051. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15052. const _ray$3 = /*@__PURE__*/ new Ray();
  15053. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15054. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15055. const _vA$1 = /*@__PURE__*/ new Vector3();
  15056. const _vB$1 = /*@__PURE__*/ new Vector3();
  15057. const _vC$1 = /*@__PURE__*/ new Vector3();
  15058. const _tempA = /*@__PURE__*/ new Vector3();
  15059. const _morphA = /*@__PURE__*/ new Vector3();
  15060. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15061. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15062. /**
  15063. * Class representing triangular polygon mesh based objects.
  15064. *
  15065. * ```js
  15066. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15067. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15068. * const mesh = new THREE.Mesh( geometry, material );
  15069. * scene.add( mesh );
  15070. * ```
  15071. *
  15072. * @augments Object3D
  15073. */
  15074. class Mesh extends Object3D {
  15075. /**
  15076. * Constructs a new mesh.
  15077. *
  15078. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15079. * @param {Material|Array<Material>} [material] - The mesh material.
  15080. */
  15081. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15082. super();
  15083. /**
  15084. * This flag can be used for type testing.
  15085. *
  15086. * @type {boolean}
  15087. * @readonly
  15088. * @default true
  15089. */
  15090. this.isMesh = true;
  15091. this.type = 'Mesh';
  15092. /**
  15093. * The mesh geometry.
  15094. *
  15095. * @type {BufferGeometry}
  15096. */
  15097. this.geometry = geometry;
  15098. /**
  15099. * The mesh material.
  15100. *
  15101. * @type {Material|Array<Material>}
  15102. * @default MeshBasicMaterial
  15103. */
  15104. this.material = material;
  15105. /**
  15106. * A dictionary representing the morph targets in the geometry. The key is the
  15107. * morph targets name, the value its attribute index. This member is `undefined`
  15108. * by default and only set when morph targets are detected in the geometry.
  15109. *
  15110. * @type {Object<String,number>|undefined}
  15111. * @default undefined
  15112. */
  15113. this.morphTargetDictionary = undefined;
  15114. /**
  15115. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15116. * is applied. This member is `undefined` by default and only set when morph targets are
  15117. * detected in the geometry.
  15118. *
  15119. * @type {Array<number>|undefined}
  15120. * @default undefined
  15121. */
  15122. this.morphTargetInfluences = undefined;
  15123. /**
  15124. * The number of instances of this mesh.
  15125. * Can only be used with {@link WebGPURenderer}.
  15126. *
  15127. * @type {number}
  15128. * @default 1
  15129. */
  15130. this.count = 1;
  15131. this.updateMorphTargets();
  15132. }
  15133. copy( source, recursive ) {
  15134. super.copy( source, recursive );
  15135. if ( source.morphTargetInfluences !== undefined ) {
  15136. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15137. }
  15138. if ( source.morphTargetDictionary !== undefined ) {
  15139. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15140. }
  15141. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15142. this.geometry = source.geometry;
  15143. return this;
  15144. }
  15145. /**
  15146. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15147. * to make sure existing morph targets can influence this 3D object.
  15148. */
  15149. updateMorphTargets() {
  15150. const geometry = this.geometry;
  15151. const morphAttributes = geometry.morphAttributes;
  15152. const keys = Object.keys( morphAttributes );
  15153. if ( keys.length > 0 ) {
  15154. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15155. if ( morphAttribute !== undefined ) {
  15156. this.morphTargetInfluences = [];
  15157. this.morphTargetDictionary = {};
  15158. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15159. const name = morphAttribute[ m ].name || String( m );
  15160. this.morphTargetInfluences.push( 0 );
  15161. this.morphTargetDictionary[ name ] = m;
  15162. }
  15163. }
  15164. }
  15165. }
  15166. /**
  15167. * Returns the local-space position of the vertex at the given index, taking into
  15168. * account the current animation state of both morph targets and skinning.
  15169. *
  15170. * @param {number} index - The vertex index.
  15171. * @param {Vector3} target - The target object that is used to store the method's result.
  15172. * @return {Vector3} The vertex position in local space.
  15173. */
  15174. getVertexPosition( index, target ) {
  15175. const geometry = this.geometry;
  15176. const position = geometry.attributes.position;
  15177. const morphPosition = geometry.morphAttributes.position;
  15178. const morphTargetsRelative = geometry.morphTargetsRelative;
  15179. target.fromBufferAttribute( position, index );
  15180. const morphInfluences = this.morphTargetInfluences;
  15181. if ( morphPosition && morphInfluences ) {
  15182. _morphA.set( 0, 0, 0 );
  15183. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15184. const influence = morphInfluences[ i ];
  15185. const morphAttribute = morphPosition[ i ];
  15186. if ( influence === 0 ) continue;
  15187. _tempA.fromBufferAttribute( morphAttribute, index );
  15188. if ( morphTargetsRelative ) {
  15189. _morphA.addScaledVector( _tempA, influence );
  15190. } else {
  15191. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15192. }
  15193. }
  15194. target.add( _morphA );
  15195. }
  15196. return target;
  15197. }
  15198. /**
  15199. * Computes intersection points between a casted ray and this line.
  15200. *
  15201. * @param {Raycaster} raycaster - The raycaster.
  15202. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15203. */
  15204. raycast( raycaster, intersects ) {
  15205. const geometry = this.geometry;
  15206. const material = this.material;
  15207. const matrixWorld = this.matrixWorld;
  15208. if ( material === undefined ) return;
  15209. // test with bounding sphere in world space
  15210. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15211. _sphere$6.copy( geometry.boundingSphere );
  15212. _sphere$6.applyMatrix4( matrixWorld );
  15213. // check distance from ray origin to bounding sphere
  15214. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15215. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15216. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15217. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15218. }
  15219. // convert ray to local space of mesh
  15220. _inverseMatrix$3.copy( matrixWorld ).invert();
  15221. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15222. // test with bounding box in local space
  15223. if ( geometry.boundingBox !== null ) {
  15224. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15225. }
  15226. // test for intersections with geometry
  15227. this._computeIntersections( raycaster, intersects, _ray$3 );
  15228. }
  15229. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15230. let intersection;
  15231. const geometry = this.geometry;
  15232. const material = this.material;
  15233. const index = geometry.index;
  15234. const position = geometry.attributes.position;
  15235. const uv = geometry.attributes.uv;
  15236. const uv1 = geometry.attributes.uv1;
  15237. const normal = geometry.attributes.normal;
  15238. const groups = geometry.groups;
  15239. const drawRange = geometry.drawRange;
  15240. if ( index !== null ) {
  15241. // indexed buffer geometry
  15242. if ( Array.isArray( material ) ) {
  15243. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15244. const group = groups[ i ];
  15245. const groupMaterial = material[ group.materialIndex ];
  15246. const start = Math.max( group.start, drawRange.start );
  15247. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15248. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15249. const a = index.getX( j );
  15250. const b = index.getX( j + 1 );
  15251. const c = index.getX( j + 2 );
  15252. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15253. if ( intersection ) {
  15254. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15255. intersection.face.materialIndex = group.materialIndex;
  15256. intersects.push( intersection );
  15257. }
  15258. }
  15259. }
  15260. } else {
  15261. const start = Math.max( 0, drawRange.start );
  15262. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15263. for ( let i = start, il = end; i < il; i += 3 ) {
  15264. const a = index.getX( i );
  15265. const b = index.getX( i + 1 );
  15266. const c = index.getX( i + 2 );
  15267. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15268. if ( intersection ) {
  15269. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15270. intersects.push( intersection );
  15271. }
  15272. }
  15273. }
  15274. } else if ( position !== undefined ) {
  15275. // non-indexed buffer geometry
  15276. if ( Array.isArray( material ) ) {
  15277. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15278. const group = groups[ i ];
  15279. const groupMaterial = material[ group.materialIndex ];
  15280. const start = Math.max( group.start, drawRange.start );
  15281. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15282. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15283. const a = j;
  15284. const b = j + 1;
  15285. const c = j + 2;
  15286. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15287. if ( intersection ) {
  15288. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15289. intersection.face.materialIndex = group.materialIndex;
  15290. intersects.push( intersection );
  15291. }
  15292. }
  15293. }
  15294. } else {
  15295. const start = Math.max( 0, drawRange.start );
  15296. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15297. for ( let i = start, il = end; i < il; i += 3 ) {
  15298. const a = i;
  15299. const b = i + 1;
  15300. const c = i + 2;
  15301. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15302. if ( intersection ) {
  15303. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15304. intersects.push( intersection );
  15305. }
  15306. }
  15307. }
  15308. }
  15309. }
  15310. }
  15311. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15312. let intersect;
  15313. if ( material.side === BackSide ) {
  15314. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15315. } else {
  15316. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15317. }
  15318. if ( intersect === null ) return null;
  15319. _intersectionPointWorld.copy( point );
  15320. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15321. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15322. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15323. return {
  15324. distance: distance,
  15325. point: _intersectionPointWorld.clone(),
  15326. object: object
  15327. };
  15328. }
  15329. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15330. object.getVertexPosition( a, _vA$1 );
  15331. object.getVertexPosition( b, _vB$1 );
  15332. object.getVertexPosition( c, _vC$1 );
  15333. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15334. if ( intersection ) {
  15335. const barycoord = new Vector3();
  15336. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15337. if ( uv ) {
  15338. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15339. }
  15340. if ( uv1 ) {
  15341. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15342. }
  15343. if ( normal ) {
  15344. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15345. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15346. intersection.normal.multiplyScalar( -1 );
  15347. }
  15348. }
  15349. const face = {
  15350. a: a,
  15351. b: b,
  15352. c: c,
  15353. normal: new Vector3(),
  15354. materialIndex: 0
  15355. };
  15356. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15357. intersection.face = face;
  15358. intersection.barycoord = barycoord;
  15359. }
  15360. return intersection;
  15361. }
  15362. /**
  15363. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15364. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15365. * of the axes.
  15366. *
  15367. * ```js
  15368. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15369. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15370. * const cube = new THREE.Mesh( geometry, material );
  15371. * scene.add( cube );
  15372. * ```
  15373. *
  15374. * @augments BufferGeometry
  15375. */
  15376. class BoxGeometry extends BufferGeometry {
  15377. /**
  15378. * Constructs a new box geometry.
  15379. *
  15380. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15381. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15382. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15383. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15384. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15385. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15386. */
  15387. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15388. super();
  15389. this.type = 'BoxGeometry';
  15390. /**
  15391. * Holds the constructor parameters that have been
  15392. * used to generate the geometry. Any modification
  15393. * after instantiation does not change the geometry.
  15394. *
  15395. * @type {Object}
  15396. */
  15397. this.parameters = {
  15398. width: width,
  15399. height: height,
  15400. depth: depth,
  15401. widthSegments: widthSegments,
  15402. heightSegments: heightSegments,
  15403. depthSegments: depthSegments
  15404. };
  15405. const scope = this;
  15406. // segments
  15407. widthSegments = Math.floor( widthSegments );
  15408. heightSegments = Math.floor( heightSegments );
  15409. depthSegments = Math.floor( depthSegments );
  15410. // buffers
  15411. const indices = [];
  15412. const vertices = [];
  15413. const normals = [];
  15414. const uvs = [];
  15415. // helper variables
  15416. let numberOfVertices = 0;
  15417. let groupStart = 0;
  15418. // build each side of the box geometry
  15419. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15420. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15421. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15422. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15423. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15424. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15425. // build geometry
  15426. this.setIndex( indices );
  15427. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15428. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15429. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15430. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15431. const segmentWidth = width / gridX;
  15432. const segmentHeight = height / gridY;
  15433. const widthHalf = width / 2;
  15434. const heightHalf = height / 2;
  15435. const depthHalf = depth / 2;
  15436. const gridX1 = gridX + 1;
  15437. const gridY1 = gridY + 1;
  15438. let vertexCounter = 0;
  15439. let groupCount = 0;
  15440. const vector = new Vector3();
  15441. // generate vertices, normals and uvs
  15442. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15443. const y = iy * segmentHeight - heightHalf;
  15444. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15445. const x = ix * segmentWidth - widthHalf;
  15446. // set values to correct vector component
  15447. vector[ u ] = x * udir;
  15448. vector[ v ] = y * vdir;
  15449. vector[ w ] = depthHalf;
  15450. // now apply vector to vertex buffer
  15451. vertices.push( vector.x, vector.y, vector.z );
  15452. // set values to correct vector component
  15453. vector[ u ] = 0;
  15454. vector[ v ] = 0;
  15455. vector[ w ] = depth > 0 ? 1 : -1;
  15456. // now apply vector to normal buffer
  15457. normals.push( vector.x, vector.y, vector.z );
  15458. // uvs
  15459. uvs.push( ix / gridX );
  15460. uvs.push( 1 - ( iy / gridY ) );
  15461. // counters
  15462. vertexCounter += 1;
  15463. }
  15464. }
  15465. // indices
  15466. // 1. you need three indices to draw a single face
  15467. // 2. a single segment consists of two faces
  15468. // 3. so we need to generate six (2*3) indices per segment
  15469. for ( let iy = 0; iy < gridY; iy ++ ) {
  15470. for ( let ix = 0; ix < gridX; ix ++ ) {
  15471. const a = numberOfVertices + ix + gridX1 * iy;
  15472. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15473. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15474. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15475. // faces
  15476. indices.push( a, b, d );
  15477. indices.push( b, c, d );
  15478. // increase counter
  15479. groupCount += 6;
  15480. }
  15481. }
  15482. // add a group to the geometry. this will ensure multi material support
  15483. scope.addGroup( groupStart, groupCount, materialIndex );
  15484. // calculate new start value for groups
  15485. groupStart += groupCount;
  15486. // update total number of vertices
  15487. numberOfVertices += vertexCounter;
  15488. }
  15489. }
  15490. copy( source ) {
  15491. super.copy( source );
  15492. this.parameters = Object.assign( {}, source.parameters );
  15493. return this;
  15494. }
  15495. /**
  15496. * Factory method for creating an instance of this class from the given
  15497. * JSON object.
  15498. *
  15499. * @param {Object} data - A JSON object representing the serialized geometry.
  15500. * @return {BoxGeometry} A new instance.
  15501. */
  15502. static fromJSON( data ) {
  15503. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15504. }
  15505. }
  15506. // Uniform Utilities
  15507. function cloneUniforms( src ) {
  15508. const dst = {};
  15509. for ( const u in src ) {
  15510. dst[ u ] = {};
  15511. for ( const p in src[ u ] ) {
  15512. const property = src[ u ][ p ];
  15513. if ( property && ( property.isColor ||
  15514. property.isMatrix3 || property.isMatrix4 ||
  15515. property.isVector2 || property.isVector3 || property.isVector4 ||
  15516. property.isTexture || property.isQuaternion ) ) {
  15517. if ( property.isRenderTargetTexture ) {
  15518. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15519. dst[ u ][ p ] = null;
  15520. } else {
  15521. dst[ u ][ p ] = property.clone();
  15522. }
  15523. } else if ( Array.isArray( property ) ) {
  15524. dst[ u ][ p ] = property.slice();
  15525. } else {
  15526. dst[ u ][ p ] = property;
  15527. }
  15528. }
  15529. }
  15530. return dst;
  15531. }
  15532. function mergeUniforms( uniforms ) {
  15533. const merged = {};
  15534. for ( let u = 0; u < uniforms.length; u ++ ) {
  15535. const tmp = cloneUniforms( uniforms[ u ] );
  15536. for ( const p in tmp ) {
  15537. merged[ p ] = tmp[ p ];
  15538. }
  15539. }
  15540. return merged;
  15541. }
  15542. function cloneUniformsGroups( src ) {
  15543. const dst = [];
  15544. for ( let u = 0; u < src.length; u ++ ) {
  15545. dst.push( src[ u ].clone() );
  15546. }
  15547. return dst;
  15548. }
  15549. function getUnlitUniformColorSpace( renderer ) {
  15550. const currentRenderTarget = renderer.getRenderTarget();
  15551. if ( currentRenderTarget === null ) {
  15552. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15553. return renderer.outputColorSpace;
  15554. }
  15555. // https://github.com/mrdoob/three.js/issues/27868
  15556. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15557. return currentRenderTarget.texture.colorSpace;
  15558. }
  15559. return ColorManagement.workingColorSpace;
  15560. }
  15561. // Legacy
  15562. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15563. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15564. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15565. /**
  15566. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15567. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15568. * effect not included with any of the built-in materials.
  15569. *
  15570. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15571. *
  15572. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15573. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15574. * you don't want that, use {@link RawShaderMaterial} instead.
  15575. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15576. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15577. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15578. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15579. * - The loop variable has to be *i*.
  15580. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15581. * value of *i* for the given iteration and can be used in preprocessor
  15582. * statements.
  15583. *
  15584. * ```js
  15585. * const material = new THREE.ShaderMaterial( {
  15586. * uniforms: {
  15587. * time: { value: 1.0 },
  15588. * resolution: { value: new THREE.Vector2() }
  15589. * },
  15590. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15591. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15592. * } );
  15593. * ```
  15594. *
  15595. * @augments Material
  15596. */
  15597. class ShaderMaterial extends Material {
  15598. /**
  15599. * Constructs a new shader material.
  15600. *
  15601. * @param {Object} [parameters] - An object with one or more properties
  15602. * defining the material's appearance. Any property of the material
  15603. * (including any property from inherited materials) can be passed
  15604. * in here. Color values can be passed any type of value accepted
  15605. * by {@link Color#set}.
  15606. */
  15607. constructor( parameters ) {
  15608. super();
  15609. /**
  15610. * This flag can be used for type testing.
  15611. *
  15612. * @type {boolean}
  15613. * @readonly
  15614. * @default true
  15615. */
  15616. this.isShaderMaterial = true;
  15617. this.type = 'ShaderMaterial';
  15618. /**
  15619. * Defines custom constants using `#define` directives within the GLSL code
  15620. * for both the vertex shader and the fragment shader; each key/value pair
  15621. * yields another directive.
  15622. * ```js
  15623. * defines: {
  15624. * FOO: 15,
  15625. * BAR: true
  15626. * }
  15627. * ```
  15628. * Yields the lines:
  15629. * ```
  15630. * #define FOO 15
  15631. * #define BAR true
  15632. * ```
  15633. *
  15634. * @type {Object}
  15635. */
  15636. this.defines = {};
  15637. /**
  15638. * An object of the form:
  15639. * ```js
  15640. * {
  15641. * "uniform1": { value: 1.0 },
  15642. * "uniform2": { value: 2 }
  15643. * }
  15644. * ```
  15645. * specifying the uniforms to be passed to the shader code; keys are uniform
  15646. * names, values are definitions of the form
  15647. * ```
  15648. * {
  15649. * value: 1.0
  15650. * }
  15651. * ```
  15652. * where `value` is the value of the uniform. Names must match the name of
  15653. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15654. * on every frame, so updating the value of the uniform will immediately
  15655. * update the value available to the GLSL code.
  15656. *
  15657. * @type {Object}
  15658. */
  15659. this.uniforms = {};
  15660. /**
  15661. * An array holding uniforms groups for configuring UBOs.
  15662. *
  15663. * @type {Array<UniformsGroup>}
  15664. */
  15665. this.uniformsGroups = [];
  15666. /**
  15667. * Vertex shader GLSL code. This is the actual code for the shader.
  15668. *
  15669. * @type {string}
  15670. */
  15671. this.vertexShader = default_vertex;
  15672. /**
  15673. * Fragment shader GLSL code. This is the actual code for the shader.
  15674. *
  15675. * @type {string}
  15676. */
  15677. this.fragmentShader = default_fragment;
  15678. /**
  15679. * Controls line thickness or lines.
  15680. *
  15681. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15682. * width of one pixel.
  15683. *
  15684. * @type {number}
  15685. * @default 1
  15686. */
  15687. this.linewidth = 1;
  15688. /**
  15689. * Renders the geometry as a wireframe.
  15690. *
  15691. * @type {boolean}
  15692. * @default false
  15693. */
  15694. this.wireframe = false;
  15695. /**
  15696. * Controls the thickness of the wireframe.
  15697. *
  15698. * WebGL and WebGPU ignore this property and always render
  15699. * 1 pixel wide lines.
  15700. *
  15701. * @type {number}
  15702. * @default 1
  15703. */
  15704. this.wireframeLinewidth = 1;
  15705. /**
  15706. * Define whether the material color is affected by global fog settings; `true`
  15707. * to pass fog uniforms to the shader.
  15708. *
  15709. * @type {boolean}
  15710. * @default false
  15711. */
  15712. this.fog = false;
  15713. /**
  15714. * Defines whether this material uses lighting; `true` to pass uniform data
  15715. * related to lighting to this shader.
  15716. *
  15717. * @type {boolean}
  15718. * @default false
  15719. */
  15720. this.lights = false;
  15721. /**
  15722. * Defines whether this material supports clipping; `true` to let the renderer
  15723. * pass the clippingPlanes uniform.
  15724. *
  15725. * @type {boolean}
  15726. * @default false
  15727. */
  15728. this.clipping = false;
  15729. /**
  15730. * Overwritten and set to `true` by default.
  15731. *
  15732. * @type {boolean}
  15733. * @default true
  15734. */
  15735. this.forceSinglePass = true;
  15736. /**
  15737. * This object allows to enable certain WebGL 2 extensions.
  15738. *
  15739. * - clipCullDistance: set to `true` to use vertex shader clipping
  15740. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15741. *
  15742. * @type {{clipCullDistance:false,multiDraw:false}}
  15743. */
  15744. this.extensions = {
  15745. clipCullDistance: false, // set to use vertex shader clipping
  15746. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15747. };
  15748. /**
  15749. * When the rendered geometry doesn't include these attributes but the
  15750. * material does, these default values will be passed to the shaders. This
  15751. * avoids errors when buffer data is missing.
  15752. *
  15753. * - color: [ 1, 1, 1 ]
  15754. * - uv: [ 0, 0 ]
  15755. * - uv1: [ 0, 0 ]
  15756. *
  15757. * @type {Object}
  15758. */
  15759. this.defaultAttributeValues = {
  15760. 'color': [ 1, 1, 1 ],
  15761. 'uv': [ 0, 0 ],
  15762. 'uv1': [ 0, 0 ]
  15763. };
  15764. /**
  15765. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15766. * to bind a generic vertex index to an attribute variable.
  15767. *
  15768. * @type {string|undefined}
  15769. * @default undefined
  15770. */
  15771. this.index0AttributeName = undefined;
  15772. /**
  15773. * Can be used to force a uniform update while changing uniforms in
  15774. * {@link Object3D#onBeforeRender}.
  15775. *
  15776. * @type {boolean}
  15777. * @default false
  15778. */
  15779. this.uniformsNeedUpdate = false;
  15780. /**
  15781. * Defines the GLSL version of custom shader code.
  15782. *
  15783. * @type {?(GLSL1|GLSL3)}
  15784. * @default null
  15785. */
  15786. this.glslVersion = null;
  15787. if ( parameters !== undefined ) {
  15788. this.setValues( parameters );
  15789. }
  15790. }
  15791. copy( source ) {
  15792. super.copy( source );
  15793. this.fragmentShader = source.fragmentShader;
  15794. this.vertexShader = source.vertexShader;
  15795. this.uniforms = cloneUniforms( source.uniforms );
  15796. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15797. this.defines = Object.assign( {}, source.defines );
  15798. this.wireframe = source.wireframe;
  15799. this.wireframeLinewidth = source.wireframeLinewidth;
  15800. this.fog = source.fog;
  15801. this.lights = source.lights;
  15802. this.clipping = source.clipping;
  15803. this.extensions = Object.assign( {}, source.extensions );
  15804. this.glslVersion = source.glslVersion;
  15805. return this;
  15806. }
  15807. toJSON( meta ) {
  15808. const data = super.toJSON( meta );
  15809. data.glslVersion = this.glslVersion;
  15810. data.uniforms = {};
  15811. for ( const name in this.uniforms ) {
  15812. const uniform = this.uniforms[ name ];
  15813. const value = uniform.value;
  15814. if ( value && value.isTexture ) {
  15815. data.uniforms[ name ] = {
  15816. type: 't',
  15817. value: value.toJSON( meta ).uuid
  15818. };
  15819. } else if ( value && value.isColor ) {
  15820. data.uniforms[ name ] = {
  15821. type: 'c',
  15822. value: value.getHex()
  15823. };
  15824. } else if ( value && value.isVector2 ) {
  15825. data.uniforms[ name ] = {
  15826. type: 'v2',
  15827. value: value.toArray()
  15828. };
  15829. } else if ( value && value.isVector3 ) {
  15830. data.uniforms[ name ] = {
  15831. type: 'v3',
  15832. value: value.toArray()
  15833. };
  15834. } else if ( value && value.isVector4 ) {
  15835. data.uniforms[ name ] = {
  15836. type: 'v4',
  15837. value: value.toArray()
  15838. };
  15839. } else if ( value && value.isMatrix3 ) {
  15840. data.uniforms[ name ] = {
  15841. type: 'm3',
  15842. value: value.toArray()
  15843. };
  15844. } else if ( value && value.isMatrix4 ) {
  15845. data.uniforms[ name ] = {
  15846. type: 'm4',
  15847. value: value.toArray()
  15848. };
  15849. } else {
  15850. data.uniforms[ name ] = {
  15851. value: value
  15852. };
  15853. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15854. }
  15855. }
  15856. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15857. data.vertexShader = this.vertexShader;
  15858. data.fragmentShader = this.fragmentShader;
  15859. data.lights = this.lights;
  15860. data.clipping = this.clipping;
  15861. const extensions = {};
  15862. for ( const key in this.extensions ) {
  15863. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15864. }
  15865. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15866. return data;
  15867. }
  15868. }
  15869. /**
  15870. * Abstract base class for cameras. This class should always be inherited
  15871. * when you build a new camera.
  15872. *
  15873. * @abstract
  15874. * @augments Object3D
  15875. */
  15876. class Camera extends Object3D {
  15877. /**
  15878. * Constructs a new camera.
  15879. */
  15880. constructor() {
  15881. super();
  15882. /**
  15883. * This flag can be used for type testing.
  15884. *
  15885. * @type {boolean}
  15886. * @readonly
  15887. * @default true
  15888. */
  15889. this.isCamera = true;
  15890. this.type = 'Camera';
  15891. /**
  15892. * The flag that indicates whether the camera uses a reversed depth buffer.
  15893. *
  15894. * @type {boolean}
  15895. * @default false
  15896. */
  15897. this.reversedDepth = false;
  15898. /**
  15899. * The inverse of the camera's world matrix.
  15900. *
  15901. * @type {Matrix4}
  15902. */
  15903. this.matrixWorldInverse = new Matrix4();
  15904. /**
  15905. * The camera's projection matrix.
  15906. *
  15907. * @type {Matrix4}
  15908. */
  15909. this.projectionMatrix = new Matrix4();
  15910. /**
  15911. * The inverse of the camera's projection matrix.
  15912. *
  15913. * @type {Matrix4}
  15914. */
  15915. this.projectionMatrixInverse = new Matrix4();
  15916. /**
  15917. * The coordinate system in which the camera is used.
  15918. *
  15919. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15920. */
  15921. this.coordinateSystem = WebGLCoordinateSystem;
  15922. }
  15923. copy( source, recursive ) {
  15924. super.copy( source, recursive );
  15925. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15926. this.projectionMatrix.copy( source.projectionMatrix );
  15927. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15928. this.coordinateSystem = source.coordinateSystem;
  15929. return this;
  15930. }
  15931. /**
  15932. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15933. *
  15934. * This method is overwritten since cameras have a different forward vector compared to other
  15935. * 3D objects. A camera looks down its local, negative z-axis by default.
  15936. *
  15937. * @param {Vector3} target - The target vector the result is stored to.
  15938. * @return {Vector3} The 3D object's direction in world space.
  15939. */
  15940. getWorldDirection( target ) {
  15941. return super.getWorldDirection( target ).negate();
  15942. }
  15943. updateMatrixWorld( force ) {
  15944. super.updateMatrixWorld( force );
  15945. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15946. }
  15947. updateWorldMatrix( updateParents, updateChildren ) {
  15948. super.updateWorldMatrix( updateParents, updateChildren );
  15949. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15950. }
  15951. clone() {
  15952. return new this.constructor().copy( this );
  15953. }
  15954. }
  15955. const _v3$1 = /*@__PURE__*/ new Vector3();
  15956. const _minTarget = /*@__PURE__*/ new Vector2();
  15957. const _maxTarget = /*@__PURE__*/ new Vector2();
  15958. /**
  15959. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  15960. *
  15961. * This projection mode is designed to mimic the way the human eye sees. It
  15962. * is the most common projection mode used for rendering a 3D scene.
  15963. *
  15964. * ```js
  15965. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  15966. * scene.add( camera );
  15967. * ```
  15968. *
  15969. * @augments Camera
  15970. */
  15971. class PerspectiveCamera extends Camera {
  15972. /**
  15973. * Constructs a new perspective camera.
  15974. *
  15975. * @param {number} [fov=50] - The vertical field of view.
  15976. * @param {number} [aspect=1] - The aspect ratio.
  15977. * @param {number} [near=0.1] - The camera's near plane.
  15978. * @param {number} [far=2000] - The camera's far plane.
  15979. */
  15980. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  15981. super();
  15982. /**
  15983. * This flag can be used for type testing.
  15984. *
  15985. * @type {boolean}
  15986. * @readonly
  15987. * @default true
  15988. */
  15989. this.isPerspectiveCamera = true;
  15990. this.type = 'PerspectiveCamera';
  15991. /**
  15992. * The vertical field of view, from bottom to top of view,
  15993. * in degrees.
  15994. *
  15995. * @type {number}
  15996. * @default 50
  15997. */
  15998. this.fov = fov;
  15999. /**
  16000. * The zoom factor of the camera.
  16001. *
  16002. * @type {number}
  16003. * @default 1
  16004. */
  16005. this.zoom = 1;
  16006. /**
  16007. * The camera's near plane. The valid range is greater than `0`
  16008. * and less than the current value of {@link PerspectiveCamera#far}.
  16009. *
  16010. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16011. * valid value for a perspective camera's near plane.
  16012. *
  16013. * @type {number}
  16014. * @default 0.1
  16015. */
  16016. this.near = near;
  16017. /**
  16018. * The camera's far plane. Must be greater than the
  16019. * current value of {@link PerspectiveCamera#near}.
  16020. *
  16021. * @type {number}
  16022. * @default 2000
  16023. */
  16024. this.far = far;
  16025. /**
  16026. * Object distance used for stereoscopy and depth-of-field effects. This
  16027. * parameter does not influence the projection matrix unless a
  16028. * {@link StereoCamera} is being used.
  16029. *
  16030. * @type {number}
  16031. * @default 10
  16032. */
  16033. this.focus = 10;
  16034. /**
  16035. * The aspect ratio, usually the canvas width / canvas height.
  16036. *
  16037. * @type {number}
  16038. * @default 1
  16039. */
  16040. this.aspect = aspect;
  16041. /**
  16042. * Represents the frustum window specification. This property should not be edited
  16043. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16044. *
  16045. * @type {?Object}
  16046. * @default null
  16047. */
  16048. this.view = null;
  16049. /**
  16050. * Film size used for the larger axis. Default is `35` (millimeters). This
  16051. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16052. * is set to a nonzero value.
  16053. *
  16054. * @type {number}
  16055. * @default 35
  16056. */
  16057. this.filmGauge = 35;
  16058. /**
  16059. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16060. *
  16061. * @type {number}
  16062. * @default 0
  16063. */
  16064. this.filmOffset = 0;
  16065. this.updateProjectionMatrix();
  16066. }
  16067. copy( source, recursive ) {
  16068. super.copy( source, recursive );
  16069. this.fov = source.fov;
  16070. this.zoom = source.zoom;
  16071. this.near = source.near;
  16072. this.far = source.far;
  16073. this.focus = source.focus;
  16074. this.aspect = source.aspect;
  16075. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16076. this.filmGauge = source.filmGauge;
  16077. this.filmOffset = source.filmOffset;
  16078. return this;
  16079. }
  16080. /**
  16081. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16082. *
  16083. * The default film gauge is 35, so that the focal length can be specified for
  16084. * a 35mm (full frame) camera.
  16085. *
  16086. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16087. */
  16088. setFocalLength( focalLength ) {
  16089. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16090. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16091. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16092. this.updateProjectionMatrix();
  16093. }
  16094. /**
  16095. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16096. * {@link PerspectiveCamera#filmGauge}.
  16097. *
  16098. * @return {number} The computed focal length.
  16099. */
  16100. getFocalLength() {
  16101. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16102. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16103. }
  16104. /**
  16105. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16106. *
  16107. * @return {number} The effective FOV.
  16108. */
  16109. getEffectiveFOV() {
  16110. return RAD2DEG * 2 * Math.atan(
  16111. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16112. }
  16113. /**
  16114. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16115. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16116. *
  16117. * @return {number} The film width.
  16118. */
  16119. getFilmWidth() {
  16120. // film not completely covered in portrait format (aspect < 1)
  16121. return this.filmGauge * Math.min( this.aspect, 1 );
  16122. }
  16123. /**
  16124. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16125. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16126. *
  16127. * @return {number} The film width.
  16128. */
  16129. getFilmHeight() {
  16130. // film not completely covered in landscape format (aspect > 1)
  16131. return this.filmGauge / Math.max( this.aspect, 1 );
  16132. }
  16133. /**
  16134. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16135. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16136. *
  16137. * @param {number} distance - The viewing distance.
  16138. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16139. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16140. */
  16141. getViewBounds( distance, minTarget, maxTarget ) {
  16142. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16143. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16144. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16145. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16146. }
  16147. /**
  16148. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16149. *
  16150. * @param {number} distance - The viewing distance.
  16151. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16152. * @returns {Vector2} The view size.
  16153. */
  16154. getViewSize( distance, target ) {
  16155. this.getViewBounds( distance, _minTarget, _maxTarget );
  16156. return target.subVectors( _maxTarget, _minTarget );
  16157. }
  16158. /**
  16159. * Sets an offset in a larger frustum. This is useful for multi-window or
  16160. * multi-monitor/multi-machine setups.
  16161. *
  16162. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16163. * the monitors are in grid like this
  16164. *```
  16165. * +---+---+---+
  16166. * | A | B | C |
  16167. * +---+---+---+
  16168. * | D | E | F |
  16169. * +---+---+---+
  16170. *```
  16171. * then for each monitor you would call it like this:
  16172. *```js
  16173. * const w = 1920;
  16174. * const h = 1080;
  16175. * const fullWidth = w * 3;
  16176. * const fullHeight = h * 2;
  16177. *
  16178. * // --A--
  16179. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16180. * // --B--
  16181. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16182. * // --C--
  16183. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16184. * // --D--
  16185. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16186. * // --E--
  16187. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16188. * // --F--
  16189. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16190. * ```
  16191. *
  16192. * Note there is no reason monitors have to be the same size or in a grid.
  16193. *
  16194. * @param {number} fullWidth - The full width of multiview setup.
  16195. * @param {number} fullHeight - The full height of multiview setup.
  16196. * @param {number} x - The horizontal offset of the subcamera.
  16197. * @param {number} y - The vertical offset of the subcamera.
  16198. * @param {number} width - The width of subcamera.
  16199. * @param {number} height - The height of subcamera.
  16200. */
  16201. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16202. this.aspect = fullWidth / fullHeight;
  16203. if ( this.view === null ) {
  16204. this.view = {
  16205. enabled: true,
  16206. fullWidth: 1,
  16207. fullHeight: 1,
  16208. offsetX: 0,
  16209. offsetY: 0,
  16210. width: 1,
  16211. height: 1
  16212. };
  16213. }
  16214. this.view.enabled = true;
  16215. this.view.fullWidth = fullWidth;
  16216. this.view.fullHeight = fullHeight;
  16217. this.view.offsetX = x;
  16218. this.view.offsetY = y;
  16219. this.view.width = width;
  16220. this.view.height = height;
  16221. this.updateProjectionMatrix();
  16222. }
  16223. /**
  16224. * Removes the view offset from the projection matrix.
  16225. */
  16226. clearViewOffset() {
  16227. if ( this.view !== null ) {
  16228. this.view.enabled = false;
  16229. }
  16230. this.updateProjectionMatrix();
  16231. }
  16232. /**
  16233. * Updates the camera's projection matrix. Must be called after any change of
  16234. * camera properties.
  16235. */
  16236. updateProjectionMatrix() {
  16237. const near = this.near;
  16238. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16239. let height = 2 * top;
  16240. let width = this.aspect * height;
  16241. let left = -0.5 * width;
  16242. const view = this.view;
  16243. if ( this.view !== null && this.view.enabled ) {
  16244. const fullWidth = view.fullWidth,
  16245. fullHeight = view.fullHeight;
  16246. left += view.offsetX * width / fullWidth;
  16247. top -= view.offsetY * height / fullHeight;
  16248. width *= view.width / fullWidth;
  16249. height *= view.height / fullHeight;
  16250. }
  16251. const skew = this.filmOffset;
  16252. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16253. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16254. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16255. }
  16256. toJSON( meta ) {
  16257. const data = super.toJSON( meta );
  16258. data.object.fov = this.fov;
  16259. data.object.zoom = this.zoom;
  16260. data.object.near = this.near;
  16261. data.object.far = this.far;
  16262. data.object.focus = this.focus;
  16263. data.object.aspect = this.aspect;
  16264. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16265. data.object.filmGauge = this.filmGauge;
  16266. data.object.filmOffset = this.filmOffset;
  16267. return data;
  16268. }
  16269. }
  16270. const fov = -90; // negative fov is not an error
  16271. const aspect = 1;
  16272. /**
  16273. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16274. * cube render target. The render target can then be used as an environment map for rendering
  16275. * realtime reflections in your scene.
  16276. *
  16277. * ```js
  16278. * // Create cube render target
  16279. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16280. *
  16281. * // Create cube camera
  16282. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16283. * scene.add( cubeCamera );
  16284. *
  16285. * // Create car
  16286. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16287. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16288. * scene.add( car );
  16289. *
  16290. * // Update the render target cube
  16291. * car.visible = false;
  16292. * cubeCamera.position.copy( car.position );
  16293. * cubeCamera.update( renderer, scene );
  16294. *
  16295. * // Render the scene
  16296. * car.visible = true;
  16297. * renderer.render( scene, camera );
  16298. * ```
  16299. *
  16300. * @augments Object3D
  16301. */
  16302. class CubeCamera extends Object3D {
  16303. /**
  16304. * Constructs a new cube camera.
  16305. *
  16306. * @param {number} near - The camera's near plane.
  16307. * @param {number} far - The camera's far plane.
  16308. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16309. */
  16310. constructor( near, far, renderTarget ) {
  16311. super();
  16312. this.type = 'CubeCamera';
  16313. /**
  16314. * A reference to the cube render target.
  16315. *
  16316. * @type {WebGLCubeRenderTarget}
  16317. */
  16318. this.renderTarget = renderTarget;
  16319. /**
  16320. * The current active coordinate system.
  16321. *
  16322. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16323. * @default null
  16324. */
  16325. this.coordinateSystem = null;
  16326. /**
  16327. * The current active mipmap level
  16328. *
  16329. * @type {number}
  16330. * @default 0
  16331. */
  16332. this.activeMipmapLevel = 0;
  16333. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16334. cameraPX.layers = this.layers;
  16335. this.add( cameraPX );
  16336. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16337. cameraNX.layers = this.layers;
  16338. this.add( cameraNX );
  16339. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16340. cameraPY.layers = this.layers;
  16341. this.add( cameraPY );
  16342. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16343. cameraNY.layers = this.layers;
  16344. this.add( cameraNY );
  16345. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16346. cameraPZ.layers = this.layers;
  16347. this.add( cameraPZ );
  16348. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16349. cameraNZ.layers = this.layers;
  16350. this.add( cameraNZ );
  16351. }
  16352. /**
  16353. * Must be called when the coordinate system of the cube camera is changed.
  16354. */
  16355. updateCoordinateSystem() {
  16356. const coordinateSystem = this.coordinateSystem;
  16357. const cameras = this.children.concat();
  16358. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16359. for ( const camera of cameras ) this.remove( camera );
  16360. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16361. cameraPX.up.set( 0, 1, 0 );
  16362. cameraPX.lookAt( 1, 0, 0 );
  16363. cameraNX.up.set( 0, 1, 0 );
  16364. cameraNX.lookAt( -1, 0, 0 );
  16365. cameraPY.up.set( 0, 0, -1 );
  16366. cameraPY.lookAt( 0, 1, 0 );
  16367. cameraNY.up.set( 0, 0, 1 );
  16368. cameraNY.lookAt( 0, -1, 0 );
  16369. cameraPZ.up.set( 0, 1, 0 );
  16370. cameraPZ.lookAt( 0, 0, 1 );
  16371. cameraNZ.up.set( 0, 1, 0 );
  16372. cameraNZ.lookAt( 0, 0, -1 );
  16373. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16374. cameraPX.up.set( 0, -1, 0 );
  16375. cameraPX.lookAt( -1, 0, 0 );
  16376. cameraNX.up.set( 0, -1, 0 );
  16377. cameraNX.lookAt( 1, 0, 0 );
  16378. cameraPY.up.set( 0, 0, 1 );
  16379. cameraPY.lookAt( 0, 1, 0 );
  16380. cameraNY.up.set( 0, 0, -1 );
  16381. cameraNY.lookAt( 0, -1, 0 );
  16382. cameraPZ.up.set( 0, -1, 0 );
  16383. cameraPZ.lookAt( 0, 0, 1 );
  16384. cameraNZ.up.set( 0, -1, 0 );
  16385. cameraNZ.lookAt( 0, 0, -1 );
  16386. } else {
  16387. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16388. }
  16389. for ( const camera of cameras ) {
  16390. this.add( camera );
  16391. camera.updateMatrixWorld();
  16392. }
  16393. }
  16394. /**
  16395. * Calling this method will render the given scene with the given renderer
  16396. * into the cube render target of the camera.
  16397. *
  16398. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16399. * @param {Scene} scene - The scene to render.
  16400. */
  16401. update( renderer, scene ) {
  16402. if ( this.parent === null ) this.updateMatrixWorld();
  16403. const { renderTarget, activeMipmapLevel } = this;
  16404. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16405. this.coordinateSystem = renderer.coordinateSystem;
  16406. this.updateCoordinateSystem();
  16407. }
  16408. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16409. const currentRenderTarget = renderer.getRenderTarget();
  16410. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16411. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16412. const currentXrEnabled = renderer.xr.enabled;
  16413. renderer.xr.enabled = false;
  16414. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16415. renderTarget.texture.generateMipmaps = false;
  16416. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16417. renderer.render( scene, cameraPX );
  16418. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16419. renderer.render( scene, cameraNX );
  16420. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16421. renderer.render( scene, cameraPY );
  16422. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16423. renderer.render( scene, cameraNY );
  16424. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16425. renderer.render( scene, cameraPZ );
  16426. // mipmaps are generated during the last call of render()
  16427. // at this point, all sides of the cube render target are defined
  16428. renderTarget.texture.generateMipmaps = generateMipmaps;
  16429. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16430. renderer.render( scene, cameraNZ );
  16431. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16432. renderer.xr.enabled = currentXrEnabled;
  16433. renderTarget.texture.needsPMREMUpdate = true;
  16434. }
  16435. }
  16436. /**
  16437. * Creates a cube texture made up of six images.
  16438. *
  16439. * ```js
  16440. * const loader = new THREE.CubeTextureLoader();
  16441. * loader.setPath( 'textures/cube/pisa/' );
  16442. *
  16443. * const textureCube = loader.load( [
  16444. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16445. * ] );
  16446. *
  16447. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16448. * ```
  16449. *
  16450. * @augments Texture
  16451. */
  16452. class CubeTexture extends Texture {
  16453. /**
  16454. * Constructs a new cube texture.
  16455. *
  16456. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16457. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16458. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16459. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16460. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16461. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16462. * @param {number} [format=RGBAFormat] - The texture format.
  16463. * @param {number} [type=UnsignedByteType] - The texture type.
  16464. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16465. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16466. */
  16467. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16468. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16469. /**
  16470. * This flag can be used for type testing.
  16471. *
  16472. * @type {boolean}
  16473. * @readonly
  16474. * @default true
  16475. */
  16476. this.isCubeTexture = true;
  16477. /**
  16478. * If set to `true`, the texture is flipped along the vertical axis when
  16479. * uploaded to the GPU.
  16480. *
  16481. * Overwritten and set to `false` by default.
  16482. *
  16483. * @type {boolean}
  16484. * @default false
  16485. */
  16486. this.flipY = false;
  16487. }
  16488. /**
  16489. * Alias for {@link CubeTexture#image}.
  16490. *
  16491. * @type {Array<Image>}
  16492. */
  16493. get images() {
  16494. return this.image;
  16495. }
  16496. set images( value ) {
  16497. this.image = value;
  16498. }
  16499. }
  16500. /**
  16501. * A cube render target used in context of {@link WebGLRenderer}.
  16502. *
  16503. * @augments WebGLRenderTarget
  16504. */
  16505. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16506. /**
  16507. * Constructs a new cube render target.
  16508. *
  16509. * @param {number} [size=1] - The size of the render target.
  16510. * @param {RenderTarget~Options} [options] - The configuration object.
  16511. */
  16512. constructor( size = 1, options = {} ) {
  16513. super( size, size, options );
  16514. /**
  16515. * This flag can be used for type testing.
  16516. *
  16517. * @type {boolean}
  16518. * @readonly
  16519. * @default true
  16520. */
  16521. this.isWebGLCubeRenderTarget = true;
  16522. const image = { width: size, height: size, depth: 1 };
  16523. const images = [ image, image, image, image, image, image ];
  16524. /**
  16525. * Overwritten with a different texture type.
  16526. *
  16527. * @type {DataArrayTexture}
  16528. */
  16529. this.texture = new CubeTexture( images );
  16530. this._setTextureOptions( options );
  16531. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16532. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16533. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16534. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16535. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16536. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16537. this.texture.isRenderTargetTexture = true;
  16538. }
  16539. /**
  16540. * Converts the given equirectangular texture to a cube map.
  16541. *
  16542. * @param {WebGLRenderer} renderer - The renderer.
  16543. * @param {Texture} texture - The equirectangular texture.
  16544. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16545. */
  16546. fromEquirectangularTexture( renderer, texture ) {
  16547. this.texture.type = texture.type;
  16548. this.texture.colorSpace = texture.colorSpace;
  16549. this.texture.generateMipmaps = texture.generateMipmaps;
  16550. this.texture.minFilter = texture.minFilter;
  16551. this.texture.magFilter = texture.magFilter;
  16552. const shader = {
  16553. uniforms: {
  16554. tEquirect: { value: null },
  16555. },
  16556. vertexShader: /* glsl */`
  16557. varying vec3 vWorldDirection;
  16558. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16559. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16560. }
  16561. void main() {
  16562. vWorldDirection = transformDirection( position, modelMatrix );
  16563. #include <begin_vertex>
  16564. #include <project_vertex>
  16565. }
  16566. `,
  16567. fragmentShader: /* glsl */`
  16568. uniform sampler2D tEquirect;
  16569. varying vec3 vWorldDirection;
  16570. #include <common>
  16571. void main() {
  16572. vec3 direction = normalize( vWorldDirection );
  16573. vec2 sampleUV = equirectUv( direction );
  16574. gl_FragColor = texture2D( tEquirect, sampleUV );
  16575. }
  16576. `
  16577. };
  16578. const geometry = new BoxGeometry( 5, 5, 5 );
  16579. const material = new ShaderMaterial( {
  16580. name: 'CubemapFromEquirect',
  16581. uniforms: cloneUniforms( shader.uniforms ),
  16582. vertexShader: shader.vertexShader,
  16583. fragmentShader: shader.fragmentShader,
  16584. side: BackSide,
  16585. blending: NoBlending
  16586. } );
  16587. material.uniforms.tEquirect.value = texture;
  16588. const mesh = new Mesh( geometry, material );
  16589. const currentMinFilter = texture.minFilter;
  16590. // Avoid blurred poles
  16591. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16592. const camera = new CubeCamera( 1, 10, this );
  16593. camera.update( renderer, mesh );
  16594. texture.minFilter = currentMinFilter;
  16595. mesh.geometry.dispose();
  16596. mesh.material.dispose();
  16597. return this;
  16598. }
  16599. /**
  16600. * Clears this cube render target.
  16601. *
  16602. * @param {WebGLRenderer} renderer - The renderer.
  16603. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16604. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16605. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16606. */
  16607. clear( renderer, color = true, depth = true, stencil = true ) {
  16608. const currentRenderTarget = renderer.getRenderTarget();
  16609. for ( let i = 0; i < 6; i ++ ) {
  16610. renderer.setRenderTarget( this, i );
  16611. renderer.clear( color, depth, stencil );
  16612. }
  16613. renderer.setRenderTarget( currentRenderTarget );
  16614. }
  16615. }
  16616. /**
  16617. * This is almost identical to an {@link Object3D}. Its purpose is to
  16618. * make working with groups of objects syntactically clearer.
  16619. *
  16620. * ```js
  16621. * // Create a group and add the two cubes.
  16622. * // These cubes can now be rotated / scaled etc as a group.
  16623. * const group = new THREE.Group();
  16624. *
  16625. * group.add( meshA );
  16626. * group.add( meshB );
  16627. *
  16628. * scene.add( group );
  16629. * ```
  16630. *
  16631. * @augments Object3D
  16632. */
  16633. class Group extends Object3D {
  16634. constructor() {
  16635. super();
  16636. /**
  16637. * This flag can be used for type testing.
  16638. *
  16639. * @type {boolean}
  16640. * @readonly
  16641. * @default true
  16642. */
  16643. this.isGroup = true;
  16644. this.type = 'Group';
  16645. }
  16646. }
  16647. const _moveEvent = { type: 'move' };
  16648. /**
  16649. * Class for representing a XR controller with its
  16650. * different coordinate systems.
  16651. *
  16652. * @private
  16653. */
  16654. class WebXRController {
  16655. /**
  16656. * Constructs a new XR controller.
  16657. */
  16658. constructor() {
  16659. /**
  16660. * A group representing the target ray space
  16661. * of the XR controller.
  16662. *
  16663. * @private
  16664. * @type {?Group}
  16665. * @default null
  16666. */
  16667. this._targetRay = null;
  16668. /**
  16669. * A group representing the grip space
  16670. * of the XR controller.
  16671. *
  16672. * @private
  16673. * @type {?Group}
  16674. * @default null
  16675. */
  16676. this._grip = null;
  16677. /**
  16678. * A group representing the hand space
  16679. * of the XR controller.
  16680. *
  16681. * @private
  16682. * @type {?Group}
  16683. * @default null
  16684. */
  16685. this._hand = null;
  16686. }
  16687. /**
  16688. * Returns a group representing the hand space of the XR controller.
  16689. *
  16690. * @return {Group} A group representing the hand space of the XR controller.
  16691. */
  16692. getHandSpace() {
  16693. if ( this._hand === null ) {
  16694. this._hand = new Group();
  16695. this._hand.matrixAutoUpdate = false;
  16696. this._hand.visible = false;
  16697. this._hand.joints = {};
  16698. this._hand.inputState = { pinching: false };
  16699. }
  16700. return this._hand;
  16701. }
  16702. /**
  16703. * Returns a group representing the target ray space of the XR controller.
  16704. *
  16705. * @return {Group} A group representing the target ray space of the XR controller.
  16706. */
  16707. getTargetRaySpace() {
  16708. if ( this._targetRay === null ) {
  16709. this._targetRay = new Group();
  16710. this._targetRay.matrixAutoUpdate = false;
  16711. this._targetRay.visible = false;
  16712. this._targetRay.hasLinearVelocity = false;
  16713. this._targetRay.linearVelocity = new Vector3();
  16714. this._targetRay.hasAngularVelocity = false;
  16715. this._targetRay.angularVelocity = new Vector3();
  16716. }
  16717. return this._targetRay;
  16718. }
  16719. /**
  16720. * Returns a group representing the grip space of the XR controller.
  16721. *
  16722. * @return {Group} A group representing the grip space of the XR controller.
  16723. */
  16724. getGripSpace() {
  16725. if ( this._grip === null ) {
  16726. this._grip = new Group();
  16727. this._grip.matrixAutoUpdate = false;
  16728. this._grip.visible = false;
  16729. this._grip.hasLinearVelocity = false;
  16730. this._grip.linearVelocity = new Vector3();
  16731. this._grip.hasAngularVelocity = false;
  16732. this._grip.angularVelocity = new Vector3();
  16733. }
  16734. return this._grip;
  16735. }
  16736. /**
  16737. * Dispatches the given event to the groups representing
  16738. * the different coordinate spaces of the XR controller.
  16739. *
  16740. * @param {Object} event - The event to dispatch.
  16741. * @return {WebXRController} A reference to this instance.
  16742. */
  16743. dispatchEvent( event ) {
  16744. if ( this._targetRay !== null ) {
  16745. this._targetRay.dispatchEvent( event );
  16746. }
  16747. if ( this._grip !== null ) {
  16748. this._grip.dispatchEvent( event );
  16749. }
  16750. if ( this._hand !== null ) {
  16751. this._hand.dispatchEvent( event );
  16752. }
  16753. return this;
  16754. }
  16755. /**
  16756. * Connects the controller with the given XR input source.
  16757. *
  16758. * @param {XRInputSource} inputSource - The input source.
  16759. * @return {WebXRController} A reference to this instance.
  16760. */
  16761. connect( inputSource ) {
  16762. if ( inputSource && inputSource.hand ) {
  16763. const hand = this._hand;
  16764. if ( hand ) {
  16765. for ( const inputjoint of inputSource.hand.values() ) {
  16766. // Initialize hand with joints when connected
  16767. this._getHandJoint( hand, inputjoint );
  16768. }
  16769. }
  16770. }
  16771. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16772. return this;
  16773. }
  16774. /**
  16775. * Disconnects the controller from the given XR input source.
  16776. *
  16777. * @param {XRInputSource} inputSource - The input source.
  16778. * @return {WebXRController} A reference to this instance.
  16779. */
  16780. disconnect( inputSource ) {
  16781. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16782. if ( this._targetRay !== null ) {
  16783. this._targetRay.visible = false;
  16784. }
  16785. if ( this._grip !== null ) {
  16786. this._grip.visible = false;
  16787. }
  16788. if ( this._hand !== null ) {
  16789. this._hand.visible = false;
  16790. }
  16791. return this;
  16792. }
  16793. /**
  16794. * Updates the controller with the given input source, XR frame and reference space.
  16795. * This updates the transformations of the groups that represent the different
  16796. * coordinate systems of the controller.
  16797. *
  16798. * @param {XRInputSource} inputSource - The input source.
  16799. * @param {XRFrame} frame - The XR frame.
  16800. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16801. * @return {WebXRController} A reference to this instance.
  16802. */
  16803. update( inputSource, frame, referenceSpace ) {
  16804. let inputPose = null;
  16805. let gripPose = null;
  16806. let handPose = null;
  16807. const targetRay = this._targetRay;
  16808. const grip = this._grip;
  16809. const hand = this._hand;
  16810. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16811. if ( hand && inputSource.hand ) {
  16812. handPose = true;
  16813. for ( const inputjoint of inputSource.hand.values() ) {
  16814. // Update the joints groups with the XRJoint poses
  16815. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16816. // The transform of this joint will be updated with the joint pose on each frame
  16817. const joint = this._getHandJoint( hand, inputjoint );
  16818. if ( jointPose !== null ) {
  16819. joint.matrix.fromArray( jointPose.transform.matrix );
  16820. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16821. joint.matrixWorldNeedsUpdate = true;
  16822. joint.jointRadius = jointPose.radius;
  16823. }
  16824. joint.visible = jointPose !== null;
  16825. }
  16826. // Custom events
  16827. // Check pinchz
  16828. const indexTip = hand.joints[ 'index-finger-tip' ];
  16829. const thumbTip = hand.joints[ 'thumb-tip' ];
  16830. const distance = indexTip.position.distanceTo( thumbTip.position );
  16831. const distanceToPinch = 0.02;
  16832. const threshold = 0.005;
  16833. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16834. hand.inputState.pinching = false;
  16835. this.dispatchEvent( {
  16836. type: 'pinchend',
  16837. handedness: inputSource.handedness,
  16838. target: this
  16839. } );
  16840. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16841. hand.inputState.pinching = true;
  16842. this.dispatchEvent( {
  16843. type: 'pinchstart',
  16844. handedness: inputSource.handedness,
  16845. target: this
  16846. } );
  16847. }
  16848. } else {
  16849. if ( grip !== null && inputSource.gripSpace ) {
  16850. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16851. if ( gripPose !== null ) {
  16852. grip.matrix.fromArray( gripPose.transform.matrix );
  16853. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16854. grip.matrixWorldNeedsUpdate = true;
  16855. if ( gripPose.linearVelocity ) {
  16856. grip.hasLinearVelocity = true;
  16857. grip.linearVelocity.copy( gripPose.linearVelocity );
  16858. } else {
  16859. grip.hasLinearVelocity = false;
  16860. }
  16861. if ( gripPose.angularVelocity ) {
  16862. grip.hasAngularVelocity = true;
  16863. grip.angularVelocity.copy( gripPose.angularVelocity );
  16864. } else {
  16865. grip.hasAngularVelocity = false;
  16866. }
  16867. }
  16868. }
  16869. }
  16870. if ( targetRay !== null ) {
  16871. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16872. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16873. if ( inputPose === null && gripPose !== null ) {
  16874. inputPose = gripPose;
  16875. }
  16876. if ( inputPose !== null ) {
  16877. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16878. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16879. targetRay.matrixWorldNeedsUpdate = true;
  16880. if ( inputPose.linearVelocity ) {
  16881. targetRay.hasLinearVelocity = true;
  16882. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16883. } else {
  16884. targetRay.hasLinearVelocity = false;
  16885. }
  16886. if ( inputPose.angularVelocity ) {
  16887. targetRay.hasAngularVelocity = true;
  16888. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16889. } else {
  16890. targetRay.hasAngularVelocity = false;
  16891. }
  16892. this.dispatchEvent( _moveEvent );
  16893. }
  16894. }
  16895. }
  16896. if ( targetRay !== null ) {
  16897. targetRay.visible = ( inputPose !== null );
  16898. }
  16899. if ( grip !== null ) {
  16900. grip.visible = ( gripPose !== null );
  16901. }
  16902. if ( hand !== null ) {
  16903. hand.visible = ( handPose !== null );
  16904. }
  16905. return this;
  16906. }
  16907. /**
  16908. * Returns a group representing the hand joint for the given input joint.
  16909. *
  16910. * @private
  16911. * @param {Group} hand - The group representing the hand space.
  16912. * @param {XRJointSpace} inputjoint - The hand joint data.
  16913. * @return {Group} A group representing the hand joint for the given input joint.
  16914. */
  16915. _getHandJoint( hand, inputjoint ) {
  16916. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16917. const joint = new Group();
  16918. joint.matrixAutoUpdate = false;
  16919. joint.visible = false;
  16920. hand.joints[ inputjoint.jointName ] = joint;
  16921. hand.add( joint );
  16922. }
  16923. return hand.joints[ inputjoint.jointName ];
  16924. }
  16925. }
  16926. /**
  16927. * This class can be used to define an exponential squared fog,
  16928. * which gives a clear view near the camera and a faster than exponentially
  16929. * densening fog farther from the camera.
  16930. *
  16931. * ```js
  16932. * const scene = new THREE.Scene();
  16933. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16934. * ```
  16935. */
  16936. class FogExp2 {
  16937. /**
  16938. * Constructs a new fog.
  16939. *
  16940. * @param {number|Color} color - The fog's color.
  16941. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16942. */
  16943. constructor( color, density = 0.00025 ) {
  16944. /**
  16945. * This flag can be used for type testing.
  16946. *
  16947. * @type {boolean}
  16948. * @readonly
  16949. * @default true
  16950. */
  16951. this.isFogExp2 = true;
  16952. /**
  16953. * The name of the fog.
  16954. *
  16955. * @type {string}
  16956. */
  16957. this.name = '';
  16958. /**
  16959. * The fog's color.
  16960. *
  16961. * @type {Color}
  16962. */
  16963. this.color = new Color( color );
  16964. /**
  16965. * Defines how fast the fog will grow dense.
  16966. *
  16967. * @type {number}
  16968. * @default 0.00025
  16969. */
  16970. this.density = density;
  16971. }
  16972. /**
  16973. * Returns a new fog with copied values from this instance.
  16974. *
  16975. * @return {FogExp2} A clone of this instance.
  16976. */
  16977. clone() {
  16978. return new FogExp2( this.color, this.density );
  16979. }
  16980. /**
  16981. * Serializes the fog into JSON.
  16982. *
  16983. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  16984. * @return {Object} A JSON object representing the serialized fog
  16985. */
  16986. toJSON( /* meta */ ) {
  16987. return {
  16988. type: 'FogExp2',
  16989. name: this.name,
  16990. color: this.color.getHex(),
  16991. density: this.density
  16992. };
  16993. }
  16994. }
  16995. /**
  16996. * This class can be used to define a linear fog that grows linearly denser
  16997. * with the distance.
  16998. *
  16999. * ```js
  17000. * const scene = new THREE.Scene();
  17001. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17002. * ```
  17003. */
  17004. class Fog {
  17005. /**
  17006. * Constructs a new fog.
  17007. *
  17008. * @param {number|Color} color - The fog's color.
  17009. * @param {number} [near=1] - The minimum distance to start applying fog.
  17010. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17011. */
  17012. constructor( color, near = 1, far = 1000 ) {
  17013. /**
  17014. * This flag can be used for type testing.
  17015. *
  17016. * @type {boolean}
  17017. * @readonly
  17018. * @default true
  17019. */
  17020. this.isFog = true;
  17021. /**
  17022. * The name of the fog.
  17023. *
  17024. * @type {string}
  17025. */
  17026. this.name = '';
  17027. /**
  17028. * The fog's color.
  17029. *
  17030. * @type {Color}
  17031. */
  17032. this.color = new Color( color );
  17033. /**
  17034. * The minimum distance to start applying fog. Objects that are less than
  17035. * `near` units from the active camera won't be affected by fog.
  17036. *
  17037. * @type {number}
  17038. * @default 1
  17039. */
  17040. this.near = near;
  17041. /**
  17042. * The maximum distance at which fog stops being calculated and applied.
  17043. * Objects that are more than `far` units away from the active camera won't
  17044. * be affected by fog.
  17045. *
  17046. * @type {number}
  17047. * @default 1000
  17048. */
  17049. this.far = far;
  17050. }
  17051. /**
  17052. * Returns a new fog with copied values from this instance.
  17053. *
  17054. * @return {Fog} A clone of this instance.
  17055. */
  17056. clone() {
  17057. return new Fog( this.color, this.near, this.far );
  17058. }
  17059. /**
  17060. * Serializes the fog into JSON.
  17061. *
  17062. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17063. * @return {Object} A JSON object representing the serialized fog
  17064. */
  17065. toJSON( /* meta */ ) {
  17066. return {
  17067. type: 'Fog',
  17068. name: this.name,
  17069. color: this.color.getHex(),
  17070. near: this.near,
  17071. far: this.far
  17072. };
  17073. }
  17074. }
  17075. /**
  17076. * Scenes allow you to set up what is to be rendered and where by three.js.
  17077. * This is where you place 3D objects like meshes, lines or lights.
  17078. *
  17079. * @augments Object3D
  17080. */
  17081. class Scene extends Object3D {
  17082. /**
  17083. * Constructs a new scene.
  17084. */
  17085. constructor() {
  17086. super();
  17087. /**
  17088. * This flag can be used for type testing.
  17089. *
  17090. * @type {boolean}
  17091. * @readonly
  17092. * @default true
  17093. */
  17094. this.isScene = true;
  17095. this.type = 'Scene';
  17096. /**
  17097. * Defines the background of the scene. Valid inputs are:
  17098. *
  17099. * - A color for defining a uniform colored background.
  17100. * - A texture for defining a (flat) textured background.
  17101. * - Cube textures or equirectangular textures for defining a skybox.
  17102. *
  17103. * @type {?(Color|Texture)}
  17104. * @default null
  17105. */
  17106. this.background = null;
  17107. /**
  17108. * Sets the environment map for all physical materials in the scene. However,
  17109. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17110. * material property.
  17111. *
  17112. * @type {?Texture}
  17113. * @default null
  17114. */
  17115. this.environment = null;
  17116. /**
  17117. * A fog instance defining the type of fog that affects everything
  17118. * rendered in the scene.
  17119. *
  17120. * @type {?(Fog|FogExp2)}
  17121. * @default null
  17122. */
  17123. this.fog = null;
  17124. /**
  17125. * Sets the blurriness of the background. Only influences environment maps
  17126. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17127. * and `1`.
  17128. *
  17129. * @type {number}
  17130. * @default 0
  17131. */
  17132. this.backgroundBlurriness = 0;
  17133. /**
  17134. * Attenuates the color of the background. Only applies to background textures.
  17135. *
  17136. * @type {number}
  17137. * @default 1
  17138. */
  17139. this.backgroundIntensity = 1;
  17140. /**
  17141. * The rotation of the background in radians. Only influences environment maps
  17142. * assigned to {@link Scene#background}.
  17143. *
  17144. * @type {Euler}
  17145. * @default (0,0,0)
  17146. */
  17147. this.backgroundRotation = new Euler();
  17148. /**
  17149. * Attenuates the color of the environment. Only influences environment maps
  17150. * assigned to {@link Scene#environment}.
  17151. *
  17152. * @type {number}
  17153. * @default 1
  17154. */
  17155. this.environmentIntensity = 1;
  17156. /**
  17157. * The rotation of the environment map in radians. Only influences physical materials
  17158. * in the scene when {@link Scene#environment} is used.
  17159. *
  17160. * @type {Euler}
  17161. * @default (0,0,0)
  17162. */
  17163. this.environmentRotation = new Euler();
  17164. /**
  17165. * Forces everything in the scene to be rendered with the defined material. It is possible
  17166. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17167. *
  17168. * @type {?Material}
  17169. * @default null
  17170. */
  17171. this.overrideMaterial = null;
  17172. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17173. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17174. }
  17175. }
  17176. copy( source, recursive ) {
  17177. super.copy( source, recursive );
  17178. if ( source.background !== null ) this.background = source.background.clone();
  17179. if ( source.environment !== null ) this.environment = source.environment.clone();
  17180. if ( source.fog !== null ) this.fog = source.fog.clone();
  17181. this.backgroundBlurriness = source.backgroundBlurriness;
  17182. this.backgroundIntensity = source.backgroundIntensity;
  17183. this.backgroundRotation.copy( source.backgroundRotation );
  17184. this.environmentIntensity = source.environmentIntensity;
  17185. this.environmentRotation.copy( source.environmentRotation );
  17186. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17187. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17188. return this;
  17189. }
  17190. toJSON( meta ) {
  17191. const data = super.toJSON( meta );
  17192. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17193. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17194. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17195. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17196. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17197. data.object.environmentRotation = this.environmentRotation.toArray();
  17198. return data;
  17199. }
  17200. }
  17201. /**
  17202. * "Interleaved" means that multiple attributes, possibly of different types,
  17203. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17204. *
  17205. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17206. */
  17207. class InterleavedBuffer {
  17208. /**
  17209. * Constructs a new interleaved buffer.
  17210. *
  17211. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17212. * @param {number} stride - The number of typed-array elements per vertex.
  17213. */
  17214. constructor( array, stride ) {
  17215. /**
  17216. * This flag can be used for type testing.
  17217. *
  17218. * @type {boolean}
  17219. * @readonly
  17220. * @default true
  17221. */
  17222. this.isInterleavedBuffer = true;
  17223. /**
  17224. * A typed array with a shared buffer storing attribute data.
  17225. *
  17226. * @type {TypedArray}
  17227. */
  17228. this.array = array;
  17229. /**
  17230. * The number of typed-array elements per vertex.
  17231. *
  17232. * @type {number}
  17233. */
  17234. this.stride = stride;
  17235. /**
  17236. * The total number of elements in the array
  17237. *
  17238. * @type {number}
  17239. * @readonly
  17240. */
  17241. this.count = array !== undefined ? array.length / stride : 0;
  17242. /**
  17243. * Defines the intended usage pattern of the data store for optimization purposes.
  17244. *
  17245. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17246. * instantiate a new one and set the desired usage before the next render.
  17247. *
  17248. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17249. * @default StaticDrawUsage
  17250. */
  17251. this.usage = StaticDrawUsage;
  17252. /**
  17253. * This can be used to only update some components of stored vectors (for example, just the
  17254. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17255. *
  17256. * @type {Array<Object>}
  17257. */
  17258. this.updateRanges = [];
  17259. /**
  17260. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17261. *
  17262. * @type {number}
  17263. */
  17264. this.version = 0;
  17265. /**
  17266. * The UUID of the interleaved buffer.
  17267. *
  17268. * @type {string}
  17269. * @readonly
  17270. */
  17271. this.uuid = generateUUID();
  17272. }
  17273. /**
  17274. * A callback function that is executed after the renderer has transferred the attribute array
  17275. * data to the GPU.
  17276. */
  17277. onUploadCallback() {}
  17278. /**
  17279. * Flag to indicate that this attribute has changed and should be re-sent to
  17280. * the GPU. Set this to `true` when you modify the value of the array.
  17281. *
  17282. * @type {number}
  17283. * @default false
  17284. * @param {boolean} value
  17285. */
  17286. set needsUpdate( value ) {
  17287. if ( value === true ) this.version ++;
  17288. }
  17289. /**
  17290. * Sets the usage of this interleaved buffer.
  17291. *
  17292. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17293. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17294. */
  17295. setUsage( value ) {
  17296. this.usage = value;
  17297. return this;
  17298. }
  17299. /**
  17300. * Adds a range of data in the data array to be updated on the GPU.
  17301. *
  17302. * @param {number} start - Position at which to start update.
  17303. * @param {number} count - The number of components to update.
  17304. */
  17305. addUpdateRange( start, count ) {
  17306. this.updateRanges.push( { start, count } );
  17307. }
  17308. /**
  17309. * Clears the update ranges.
  17310. */
  17311. clearUpdateRanges() {
  17312. this.updateRanges.length = 0;
  17313. }
  17314. /**
  17315. * Copies the values of the given interleaved buffer to this instance.
  17316. *
  17317. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17318. * @return {InterleavedBuffer} A reference to this instance.
  17319. */
  17320. copy( source ) {
  17321. this.array = new source.array.constructor( source.array );
  17322. this.count = source.count;
  17323. this.stride = source.stride;
  17324. this.usage = source.usage;
  17325. return this;
  17326. }
  17327. /**
  17328. * Copies a vector from the given interleaved buffer to this one. The start
  17329. * and destination position in the attribute buffers are represented by the
  17330. * given indices.
  17331. *
  17332. * @param {number} index1 - The destination index into this interleaved buffer.
  17333. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17334. * @param {number} index2 - The source index into the given interleaved buffer.
  17335. * @return {InterleavedBuffer} A reference to this instance.
  17336. */
  17337. copyAt( index1, interleavedBuffer, index2 ) {
  17338. index1 *= this.stride;
  17339. index2 *= interleavedBuffer.stride;
  17340. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17341. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17342. }
  17343. return this;
  17344. }
  17345. /**
  17346. * Sets the given array data in the interleaved buffer.
  17347. *
  17348. * @param {(TypedArray|Array)} value - The array data to set.
  17349. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17350. * @return {InterleavedBuffer} A reference to this instance.
  17351. */
  17352. set( value, offset = 0 ) {
  17353. this.array.set( value, offset );
  17354. return this;
  17355. }
  17356. /**
  17357. * Returns a new interleaved buffer with copied values from this instance.
  17358. *
  17359. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17360. * @return {InterleavedBuffer} A clone of this instance.
  17361. */
  17362. clone( data ) {
  17363. if ( data.arrayBuffers === undefined ) {
  17364. data.arrayBuffers = {};
  17365. }
  17366. if ( this.array.buffer._uuid === undefined ) {
  17367. this.array.buffer._uuid = generateUUID();
  17368. }
  17369. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17370. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17371. }
  17372. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17373. const ib = new this.constructor( array, this.stride );
  17374. ib.setUsage( this.usage );
  17375. return ib;
  17376. }
  17377. /**
  17378. * Sets the given callback function that is executed after the Renderer has transferred
  17379. * the array data to the GPU. Can be used to perform clean-up operations after
  17380. * the upload when data are not needed anymore on the CPU side.
  17381. *
  17382. * @param {Function} callback - The `onUpload()` callback.
  17383. * @return {InterleavedBuffer} A reference to this instance.
  17384. */
  17385. onUpload( callback ) {
  17386. this.onUploadCallback = callback;
  17387. return this;
  17388. }
  17389. /**
  17390. * Serializes the interleaved buffer into JSON.
  17391. *
  17392. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17393. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17394. */
  17395. toJSON( data ) {
  17396. if ( data.arrayBuffers === undefined ) {
  17397. data.arrayBuffers = {};
  17398. }
  17399. // generate UUID for array buffer if necessary
  17400. if ( this.array.buffer._uuid === undefined ) {
  17401. this.array.buffer._uuid = generateUUID();
  17402. }
  17403. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17404. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17405. }
  17406. //
  17407. return {
  17408. uuid: this.uuid,
  17409. buffer: this.array.buffer._uuid,
  17410. type: this.array.constructor.name,
  17411. stride: this.stride
  17412. };
  17413. }
  17414. }
  17415. const _vector$7 = /*@__PURE__*/ new Vector3();
  17416. /**
  17417. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17418. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17419. * different offsets into the buffer.
  17420. */
  17421. class InterleavedBufferAttribute {
  17422. /**
  17423. * Constructs a new interleaved buffer attribute.
  17424. *
  17425. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17426. * @param {number} itemSize - The item size.
  17427. * @param {number} offset - The attribute offset into the buffer.
  17428. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17429. */
  17430. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17431. /**
  17432. * This flag can be used for type testing.
  17433. *
  17434. * @type {boolean}
  17435. * @readonly
  17436. * @default true
  17437. */
  17438. this.isInterleavedBufferAttribute = true;
  17439. /**
  17440. * The name of the buffer attribute.
  17441. *
  17442. * @type {string}
  17443. */
  17444. this.name = '';
  17445. /**
  17446. * The buffer holding the interleaved data.
  17447. *
  17448. * @type {InterleavedBuffer}
  17449. */
  17450. this.data = interleavedBuffer;
  17451. /**
  17452. * The item size, see {@link BufferAttribute#itemSize}.
  17453. *
  17454. * @type {number}
  17455. */
  17456. this.itemSize = itemSize;
  17457. /**
  17458. * The attribute offset into the buffer.
  17459. *
  17460. * @type {number}
  17461. */
  17462. this.offset = offset;
  17463. /**
  17464. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17465. *
  17466. * @type {InterleavedBuffer}
  17467. */
  17468. this.normalized = normalized;
  17469. }
  17470. /**
  17471. * The item count of this buffer attribute.
  17472. *
  17473. * @type {number}
  17474. * @readonly
  17475. */
  17476. get count() {
  17477. return this.data.count;
  17478. }
  17479. /**
  17480. * The array holding the interleaved buffer attribute data.
  17481. *
  17482. * @type {TypedArray}
  17483. */
  17484. get array() {
  17485. return this.data.array;
  17486. }
  17487. /**
  17488. * Flag to indicate that this attribute has changed and should be re-sent to
  17489. * the GPU. Set this to `true` when you modify the value of the array.
  17490. *
  17491. * @type {number}
  17492. * @default false
  17493. * @param {boolean} value
  17494. */
  17495. set needsUpdate( value ) {
  17496. this.data.needsUpdate = value;
  17497. }
  17498. /**
  17499. * Applies the given 4x4 matrix to the given attribute. Only works with
  17500. * item size `3`.
  17501. *
  17502. * @param {Matrix4} m - The matrix to apply.
  17503. * @return {InterleavedBufferAttribute} A reference to this instance.
  17504. */
  17505. applyMatrix4( m ) {
  17506. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17507. _vector$7.fromBufferAttribute( this, i );
  17508. _vector$7.applyMatrix4( m );
  17509. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17510. }
  17511. return this;
  17512. }
  17513. /**
  17514. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17515. * item size `3`.
  17516. *
  17517. * @param {Matrix3} m - The normal matrix to apply.
  17518. * @return {InterleavedBufferAttribute} A reference to this instance.
  17519. */
  17520. applyNormalMatrix( m ) {
  17521. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17522. _vector$7.fromBufferAttribute( this, i );
  17523. _vector$7.applyNormalMatrix( m );
  17524. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17525. }
  17526. return this;
  17527. }
  17528. /**
  17529. * Applies the given 4x4 matrix to the given attribute. Only works with
  17530. * item size `3` and with direction vectors.
  17531. *
  17532. * @param {Matrix4} m - The matrix to apply.
  17533. * @return {InterleavedBufferAttribute} A reference to this instance.
  17534. */
  17535. transformDirection( m ) {
  17536. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17537. _vector$7.fromBufferAttribute( this, i );
  17538. _vector$7.transformDirection( m );
  17539. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17540. }
  17541. return this;
  17542. }
  17543. /**
  17544. * Returns the given component of the vector at the given index.
  17545. *
  17546. * @param {number} index - The index into the buffer attribute.
  17547. * @param {number} component - The component index.
  17548. * @return {number} The returned value.
  17549. */
  17550. getComponent( index, component ) {
  17551. let value = this.array[ index * this.data.stride + this.offset + component ];
  17552. if ( this.normalized ) value = denormalize( value, this.array );
  17553. return value;
  17554. }
  17555. /**
  17556. * Sets the given value to the given component of the vector at the given index.
  17557. *
  17558. * @param {number} index - The index into the buffer attribute.
  17559. * @param {number} component - The component index.
  17560. * @param {number} value - The value to set.
  17561. * @return {InterleavedBufferAttribute} A reference to this instance.
  17562. */
  17563. setComponent( index, component, value ) {
  17564. if ( this.normalized ) value = normalize( value, this.array );
  17565. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17566. return this;
  17567. }
  17568. /**
  17569. * Sets the x component of the vector at the given index.
  17570. *
  17571. * @param {number} index - The index into the buffer attribute.
  17572. * @param {number} x - The value to set.
  17573. * @return {InterleavedBufferAttribute} A reference to this instance.
  17574. */
  17575. setX( index, x ) {
  17576. if ( this.normalized ) x = normalize( x, this.array );
  17577. this.data.array[ index * this.data.stride + this.offset ] = x;
  17578. return this;
  17579. }
  17580. /**
  17581. * Sets the y component of the vector at the given index.
  17582. *
  17583. * @param {number} index - The index into the buffer attribute.
  17584. * @param {number} y - The value to set.
  17585. * @return {InterleavedBufferAttribute} A reference to this instance.
  17586. */
  17587. setY( index, y ) {
  17588. if ( this.normalized ) y = normalize( y, this.array );
  17589. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17590. return this;
  17591. }
  17592. /**
  17593. * Sets the z component of the vector at the given index.
  17594. *
  17595. * @param {number} index - The index into the buffer attribute.
  17596. * @param {number} z - The value to set.
  17597. * @return {InterleavedBufferAttribute} A reference to this instance.
  17598. */
  17599. setZ( index, z ) {
  17600. if ( this.normalized ) z = normalize( z, this.array );
  17601. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17602. return this;
  17603. }
  17604. /**
  17605. * Sets the w component of the vector at the given index.
  17606. *
  17607. * @param {number} index - The index into the buffer attribute.
  17608. * @param {number} w - The value to set.
  17609. * @return {InterleavedBufferAttribute} A reference to this instance.
  17610. */
  17611. setW( index, w ) {
  17612. if ( this.normalized ) w = normalize( w, this.array );
  17613. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17614. return this;
  17615. }
  17616. /**
  17617. * Returns the x component of the vector at the given index.
  17618. *
  17619. * @param {number} index - The index into the buffer attribute.
  17620. * @return {number} The x component.
  17621. */
  17622. getX( index ) {
  17623. let x = this.data.array[ index * this.data.stride + this.offset ];
  17624. if ( this.normalized ) x = denormalize( x, this.array );
  17625. return x;
  17626. }
  17627. /**
  17628. * Returns the y component of the vector at the given index.
  17629. *
  17630. * @param {number} index - The index into the buffer attribute.
  17631. * @return {number} The y component.
  17632. */
  17633. getY( index ) {
  17634. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17635. if ( this.normalized ) y = denormalize( y, this.array );
  17636. return y;
  17637. }
  17638. /**
  17639. * Returns the z component of the vector at the given index.
  17640. *
  17641. * @param {number} index - The index into the buffer attribute.
  17642. * @return {number} The z component.
  17643. */
  17644. getZ( index ) {
  17645. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17646. if ( this.normalized ) z = denormalize( z, this.array );
  17647. return z;
  17648. }
  17649. /**
  17650. * Returns the w component of the vector at the given index.
  17651. *
  17652. * @param {number} index - The index into the buffer attribute.
  17653. * @return {number} The w component.
  17654. */
  17655. getW( index ) {
  17656. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17657. if ( this.normalized ) w = denormalize( w, this.array );
  17658. return w;
  17659. }
  17660. /**
  17661. * Sets the x and y component of the vector at the given index.
  17662. *
  17663. * @param {number} index - The index into the buffer attribute.
  17664. * @param {number} x - The value for the x component to set.
  17665. * @param {number} y - The value for the y component to set.
  17666. * @return {InterleavedBufferAttribute} A reference to this instance.
  17667. */
  17668. setXY( index, x, y ) {
  17669. index = index * this.data.stride + this.offset;
  17670. if ( this.normalized ) {
  17671. x = normalize( x, this.array );
  17672. y = normalize( y, this.array );
  17673. }
  17674. this.data.array[ index + 0 ] = x;
  17675. this.data.array[ index + 1 ] = y;
  17676. return this;
  17677. }
  17678. /**
  17679. * Sets the x, y and z component of the vector at the given index.
  17680. *
  17681. * @param {number} index - The index into the buffer attribute.
  17682. * @param {number} x - The value for the x component to set.
  17683. * @param {number} y - The value for the y component to set.
  17684. * @param {number} z - The value for the z component to set.
  17685. * @return {InterleavedBufferAttribute} A reference to this instance.
  17686. */
  17687. setXYZ( index, x, y, z ) {
  17688. index = index * this.data.stride + this.offset;
  17689. if ( this.normalized ) {
  17690. x = normalize( x, this.array );
  17691. y = normalize( y, this.array );
  17692. z = normalize( z, this.array );
  17693. }
  17694. this.data.array[ index + 0 ] = x;
  17695. this.data.array[ index + 1 ] = y;
  17696. this.data.array[ index + 2 ] = z;
  17697. return this;
  17698. }
  17699. /**
  17700. * Sets the x, y, z and w component of the vector at the given index.
  17701. *
  17702. * @param {number} index - The index into the buffer attribute.
  17703. * @param {number} x - The value for the x component to set.
  17704. * @param {number} y - The value for the y component to set.
  17705. * @param {number} z - The value for the z component to set.
  17706. * @param {number} w - The value for the w component to set.
  17707. * @return {InterleavedBufferAttribute} A reference to this instance.
  17708. */
  17709. setXYZW( index, x, y, z, w ) {
  17710. index = index * this.data.stride + this.offset;
  17711. if ( this.normalized ) {
  17712. x = normalize( x, this.array );
  17713. y = normalize( y, this.array );
  17714. z = normalize( z, this.array );
  17715. w = normalize( w, this.array );
  17716. }
  17717. this.data.array[ index + 0 ] = x;
  17718. this.data.array[ index + 1 ] = y;
  17719. this.data.array[ index + 2 ] = z;
  17720. this.data.array[ index + 3 ] = w;
  17721. return this;
  17722. }
  17723. /**
  17724. * Returns a new buffer attribute with copied values from this instance.
  17725. *
  17726. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17727. *
  17728. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17729. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17730. */
  17731. clone( data ) {
  17732. if ( data === undefined ) {
  17733. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17734. const array = [];
  17735. for ( let i = 0; i < this.count; i ++ ) {
  17736. const index = i * this.data.stride + this.offset;
  17737. for ( let j = 0; j < this.itemSize; j ++ ) {
  17738. array.push( this.data.array[ index + j ] );
  17739. }
  17740. }
  17741. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17742. } else {
  17743. if ( data.interleavedBuffers === undefined ) {
  17744. data.interleavedBuffers = {};
  17745. }
  17746. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17747. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17748. }
  17749. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17750. }
  17751. }
  17752. /**
  17753. * Serializes the buffer attribute into JSON.
  17754. *
  17755. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17756. *
  17757. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17758. * @return {Object} A JSON object representing the serialized buffer attribute.
  17759. */
  17760. toJSON( data ) {
  17761. if ( data === undefined ) {
  17762. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17763. const array = [];
  17764. for ( let i = 0; i < this.count; i ++ ) {
  17765. const index = i * this.data.stride + this.offset;
  17766. for ( let j = 0; j < this.itemSize; j ++ ) {
  17767. array.push( this.data.array[ index + j ] );
  17768. }
  17769. }
  17770. // de-interleave data and save it as an ordinary buffer attribute for now
  17771. return {
  17772. itemSize: this.itemSize,
  17773. type: this.array.constructor.name,
  17774. array: array,
  17775. normalized: this.normalized
  17776. };
  17777. } else {
  17778. // save as true interleaved attribute
  17779. if ( data.interleavedBuffers === undefined ) {
  17780. data.interleavedBuffers = {};
  17781. }
  17782. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17783. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17784. }
  17785. return {
  17786. isInterleavedBufferAttribute: true,
  17787. itemSize: this.itemSize,
  17788. data: this.data.uuid,
  17789. offset: this.offset,
  17790. normalized: this.normalized
  17791. };
  17792. }
  17793. }
  17794. }
  17795. /**
  17796. * A material for rendering instances of {@link Sprite}.
  17797. *
  17798. * ```js
  17799. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17800. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17801. *
  17802. * const sprite = new THREE.Sprite( material );
  17803. * sprite.scale.set(200, 200, 1)
  17804. * scene.add( sprite );
  17805. * ```
  17806. *
  17807. * @augments Material
  17808. */
  17809. class SpriteMaterial extends Material {
  17810. /**
  17811. * Constructs a new sprite material.
  17812. *
  17813. * @param {Object} [parameters] - An object with one or more properties
  17814. * defining the material's appearance. Any property of the material
  17815. * (including any property from inherited materials) can be passed
  17816. * in here. Color values can be passed any type of value accepted
  17817. * by {@link Color#set}.
  17818. */
  17819. constructor( parameters ) {
  17820. super();
  17821. /**
  17822. * This flag can be used for type testing.
  17823. *
  17824. * @type {boolean}
  17825. * @readonly
  17826. * @default true
  17827. */
  17828. this.isSpriteMaterial = true;
  17829. this.type = 'SpriteMaterial';
  17830. /**
  17831. * Color of the material.
  17832. *
  17833. * @type {Color}
  17834. * @default (1,1,1)
  17835. */
  17836. this.color = new Color( 0xffffff );
  17837. /**
  17838. * The color map. May optionally include an alpha channel, typically combined
  17839. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17840. * color is modulated by the diffuse `color`.
  17841. *
  17842. * @type {?Texture}
  17843. * @default null
  17844. */
  17845. this.map = null;
  17846. /**
  17847. * The alpha map is a grayscale texture that controls the opacity across the
  17848. * surface (black: fully transparent; white: fully opaque).
  17849. *
  17850. * Only the color of the texture is used, ignoring the alpha channel if one
  17851. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17852. * when sampling this texture due to the extra bit of precision provided for
  17853. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17854. * luminance/alpha textures will also still work as expected.
  17855. *
  17856. * @type {?Texture}
  17857. * @default null
  17858. */
  17859. this.alphaMap = null;
  17860. /**
  17861. * The rotation of the sprite in radians.
  17862. *
  17863. * @type {number}
  17864. * @default 0
  17865. */
  17866. this.rotation = 0;
  17867. /**
  17868. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17869. *
  17870. * @type {boolean}
  17871. * @default true
  17872. */
  17873. this.sizeAttenuation = true;
  17874. /**
  17875. * Overwritten since sprite materials are transparent
  17876. * by default.
  17877. *
  17878. * @type {boolean}
  17879. * @default true
  17880. */
  17881. this.transparent = true;
  17882. /**
  17883. * Whether the material is affected by fog or not.
  17884. *
  17885. * @type {boolean}
  17886. * @default true
  17887. */
  17888. this.fog = true;
  17889. this.setValues( parameters );
  17890. }
  17891. copy( source ) {
  17892. super.copy( source );
  17893. this.color.copy( source.color );
  17894. this.map = source.map;
  17895. this.alphaMap = source.alphaMap;
  17896. this.rotation = source.rotation;
  17897. this.sizeAttenuation = source.sizeAttenuation;
  17898. this.fog = source.fog;
  17899. return this;
  17900. }
  17901. }
  17902. let _geometry;
  17903. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17904. const _worldScale = /*@__PURE__*/ new Vector3();
  17905. const _mvPosition = /*@__PURE__*/ new Vector3();
  17906. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17907. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17908. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17909. const _vA = /*@__PURE__*/ new Vector3();
  17910. const _vB = /*@__PURE__*/ new Vector3();
  17911. const _vC = /*@__PURE__*/ new Vector3();
  17912. const _uvA = /*@__PURE__*/ new Vector2();
  17913. const _uvB = /*@__PURE__*/ new Vector2();
  17914. const _uvC = /*@__PURE__*/ new Vector2();
  17915. /**
  17916. * A sprite is a plane that always faces towards the camera, generally with a
  17917. * partially transparent texture applied.
  17918. *
  17919. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17920. * have no effect.
  17921. *
  17922. * ```js
  17923. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17924. * const material = new THREE.SpriteMaterial( { map: map } );
  17925. *
  17926. * const sprite = new THREE.Sprite( material );
  17927. * scene.add( sprite );
  17928. * ```
  17929. *
  17930. * @augments Object3D
  17931. */
  17932. class Sprite extends Object3D {
  17933. /**
  17934. * Constructs a new sprite.
  17935. *
  17936. * @param {SpriteMaterial} [material] - The sprite material.
  17937. */
  17938. constructor( material = new SpriteMaterial() ) {
  17939. super();
  17940. /**
  17941. * This flag can be used for type testing.
  17942. *
  17943. * @type {boolean}
  17944. * @readonly
  17945. * @default true
  17946. */
  17947. this.isSprite = true;
  17948. this.type = 'Sprite';
  17949. if ( _geometry === undefined ) {
  17950. _geometry = new BufferGeometry();
  17951. const float32Array = new Float32Array( [
  17952. -0.5, -0.5, 0, 0, 0,
  17953. 0.5, -0.5, 0, 1, 0,
  17954. 0.5, 0.5, 0, 1, 1,
  17955. -0.5, 0.5, 0, 0, 1
  17956. ] );
  17957. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17958. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17959. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17960. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17961. }
  17962. /**
  17963. * The sprite geometry.
  17964. *
  17965. * @type {BufferGeometry}
  17966. */
  17967. this.geometry = _geometry;
  17968. /**
  17969. * The sprite material.
  17970. *
  17971. * @type {SpriteMaterial}
  17972. */
  17973. this.material = material;
  17974. /**
  17975. * The sprite's anchor point, and the point around which the sprite rotates.
  17976. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  17977. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  17978. *
  17979. * @type {Vector2}
  17980. * @default (0.5,0.5)
  17981. */
  17982. this.center = new Vector2( 0.5, 0.5 );
  17983. /**
  17984. * The number of instances of this sprite.
  17985. * Can only be used with {@link WebGPURenderer}.
  17986. *
  17987. * @type {number}
  17988. * @default 1
  17989. */
  17990. this.count = 1;
  17991. }
  17992. /**
  17993. * Computes intersection points between a casted ray and this sprite.
  17994. *
  17995. * @param {Raycaster} raycaster - The raycaster.
  17996. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17997. */
  17998. raycast( raycaster, intersects ) {
  17999. if ( raycaster.camera === null ) {
  18000. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18001. }
  18002. _worldScale.setFromMatrixScale( this.matrixWorld );
  18003. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18004. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18005. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18006. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18007. _worldScale.multiplyScalar( - _mvPosition.z );
  18008. }
  18009. const rotation = this.material.rotation;
  18010. let sin, cos;
  18011. if ( rotation !== 0 ) {
  18012. cos = Math.cos( rotation );
  18013. sin = Math.sin( rotation );
  18014. }
  18015. const center = this.center;
  18016. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18017. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18018. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18019. _uvA.set( 0, 0 );
  18020. _uvB.set( 1, 0 );
  18021. _uvC.set( 1, 1 );
  18022. // check first triangle
  18023. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18024. if ( intersect === null ) {
  18025. // check second triangle
  18026. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18027. _uvB.set( 0, 1 );
  18028. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18029. if ( intersect === null ) {
  18030. return;
  18031. }
  18032. }
  18033. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18034. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18035. intersects.push( {
  18036. distance: distance,
  18037. point: _intersectPoint.clone(),
  18038. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18039. face: null,
  18040. object: this
  18041. } );
  18042. }
  18043. copy( source, recursive ) {
  18044. super.copy( source, recursive );
  18045. if ( source.center !== undefined ) this.center.copy( source.center );
  18046. this.material = source.material;
  18047. return this;
  18048. }
  18049. }
  18050. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18051. // compute position in camera space
  18052. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18053. // to check if rotation is not zero
  18054. if ( sin !== undefined ) {
  18055. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18056. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18057. } else {
  18058. _rotatedPosition.copy( _alignedPosition );
  18059. }
  18060. vertexPosition.copy( mvPosition );
  18061. vertexPosition.x += _rotatedPosition.x;
  18062. vertexPosition.y += _rotatedPosition.y;
  18063. // transform to world space
  18064. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18065. }
  18066. const _v1$2 = /*@__PURE__*/ new Vector3();
  18067. const _v2$1 = /*@__PURE__*/ new Vector3();
  18068. /**
  18069. * A component for providing a basic Level of Detail (LOD) mechanism.
  18070. *
  18071. * Every LOD level is associated with an object, and rendering can be switched
  18072. * between them at the distances specified. Typically you would create, say,
  18073. * three meshes, one for far away (low detail), one for mid range (medium
  18074. * detail) and one for close up (high detail).
  18075. *
  18076. * ```js
  18077. * const lod = new THREE.LOD();
  18078. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18079. *
  18080. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18081. * for( let i = 0; i < 3; i++ ) {
  18082. *
  18083. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18084. * const mesh = new THREE.Mesh( geometry, material );
  18085. * lod.addLevel( mesh, i * 75 );
  18086. *
  18087. * }
  18088. *
  18089. * scene.add( lod );
  18090. * ```
  18091. *
  18092. * @augments Object3D
  18093. */
  18094. class LOD extends Object3D {
  18095. /**
  18096. * Constructs a new LOD.
  18097. */
  18098. constructor() {
  18099. super();
  18100. /**
  18101. * This flag can be used for type testing.
  18102. *
  18103. * @type {boolean}
  18104. * @readonly
  18105. * @default true
  18106. */
  18107. this.isLOD = true;
  18108. /**
  18109. * The current LOD index.
  18110. *
  18111. * @private
  18112. * @type {number}
  18113. * @default 0
  18114. */
  18115. this._currentLevel = 0;
  18116. this.type = 'LOD';
  18117. Object.defineProperties( this, {
  18118. /**
  18119. * This array holds the LOD levels.
  18120. *
  18121. * @name LOD#levels
  18122. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18123. */
  18124. levels: {
  18125. enumerable: true,
  18126. value: []
  18127. }
  18128. } );
  18129. /**
  18130. * Whether the LOD object is updated automatically by the renderer per frame
  18131. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18132. * render loop by yourself.
  18133. *
  18134. * @type {boolean}
  18135. * @default true
  18136. */
  18137. this.autoUpdate = true;
  18138. }
  18139. copy( source ) {
  18140. super.copy( source, false );
  18141. const levels = source.levels;
  18142. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18143. const level = levels[ i ];
  18144. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18145. }
  18146. this.autoUpdate = source.autoUpdate;
  18147. return this;
  18148. }
  18149. /**
  18150. * Adds a mesh that will display at a certain distance and greater. Typically
  18151. * the further away the distance, the lower the detail on the mesh.
  18152. *
  18153. * @param {Object3D} object - The 3D object to display at this level.
  18154. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18155. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18156. * @return {LOD} A reference to this instance.
  18157. */
  18158. addLevel( object, distance = 0, hysteresis = 0 ) {
  18159. distance = Math.abs( distance );
  18160. const levels = this.levels;
  18161. let l;
  18162. for ( l = 0; l < levels.length; l ++ ) {
  18163. if ( distance < levels[ l ].distance ) {
  18164. break;
  18165. }
  18166. }
  18167. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18168. this.add( object );
  18169. return this;
  18170. }
  18171. /**
  18172. * Removes an existing level, based on the distance from the camera.
  18173. * Returns `true` when the level has been removed. Otherwise `false`.
  18174. *
  18175. * @param {number} distance - Distance of the level to remove.
  18176. * @return {boolean} Whether the level has been removed or not.
  18177. */
  18178. removeLevel( distance ) {
  18179. const levels = this.levels;
  18180. for ( let i = 0; i < levels.length; i ++ ) {
  18181. if ( levels[ i ].distance === distance ) {
  18182. const removedElements = levels.splice( i, 1 );
  18183. this.remove( removedElements[ 0 ].object );
  18184. return true;
  18185. }
  18186. }
  18187. return false;
  18188. }
  18189. /**
  18190. * Returns the currently active LOD level index.
  18191. *
  18192. * @return {number} The current active LOD level index.
  18193. */
  18194. getCurrentLevel() {
  18195. return this._currentLevel;
  18196. }
  18197. /**
  18198. * Returns a reference to the first 3D object that is greater than
  18199. * the given distance.
  18200. *
  18201. * @param {number} distance - The LOD distance.
  18202. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  18203. */
  18204. getObjectForDistance( distance ) {
  18205. const levels = this.levels;
  18206. if ( levels.length > 0 ) {
  18207. let i, l;
  18208. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18209. let levelDistance = levels[ i ].distance;
  18210. if ( levels[ i ].object.visible ) {
  18211. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18212. }
  18213. if ( distance < levelDistance ) {
  18214. break;
  18215. }
  18216. }
  18217. return levels[ i - 1 ].object;
  18218. }
  18219. return null;
  18220. }
  18221. /**
  18222. * Computes intersection points between a casted ray and this LOD.
  18223. *
  18224. * @param {Raycaster} raycaster - The raycaster.
  18225. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18226. */
  18227. raycast( raycaster, intersects ) {
  18228. const levels = this.levels;
  18229. if ( levels.length > 0 ) {
  18230. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18231. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18232. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18233. }
  18234. }
  18235. /**
  18236. * Updates the LOD by computing which LOD level should be visible according
  18237. * to the current distance of the given camera.
  18238. *
  18239. * @param {Camera} camera - The camera the scene is rendered with.
  18240. */
  18241. update( camera ) {
  18242. const levels = this.levels;
  18243. if ( levels.length > 1 ) {
  18244. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18245. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18246. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18247. levels[ 0 ].object.visible = true;
  18248. let i, l;
  18249. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18250. let levelDistance = levels[ i ].distance;
  18251. if ( levels[ i ].object.visible ) {
  18252. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18253. }
  18254. if ( distance >= levelDistance ) {
  18255. levels[ i - 1 ].object.visible = false;
  18256. levels[ i ].object.visible = true;
  18257. } else {
  18258. break;
  18259. }
  18260. }
  18261. this._currentLevel = i - 1;
  18262. for ( ; i < l; i ++ ) {
  18263. levels[ i ].object.visible = false;
  18264. }
  18265. }
  18266. }
  18267. toJSON( meta ) {
  18268. const data = super.toJSON( meta );
  18269. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18270. data.object.levels = [];
  18271. const levels = this.levels;
  18272. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18273. const level = levels[ i ];
  18274. data.object.levels.push( {
  18275. object: level.object.uuid,
  18276. distance: level.distance,
  18277. hysteresis: level.hysteresis
  18278. } );
  18279. }
  18280. return data;
  18281. }
  18282. }
  18283. const _basePosition = /*@__PURE__*/ new Vector3();
  18284. const _skinIndex = /*@__PURE__*/ new Vector4();
  18285. const _skinWeight = /*@__PURE__*/ new Vector4();
  18286. const _vector3 = /*@__PURE__*/ new Vector3();
  18287. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18288. const _vertex = /*@__PURE__*/ new Vector3();
  18289. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18290. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18291. const _ray$2 = /*@__PURE__*/ new Ray();
  18292. /**
  18293. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18294. * vertices of the geometry with skinning/skeleton animation.
  18295. *
  18296. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18297. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18298. * vertex to a certain extend.
  18299. *
  18300. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18301. * or {@link FBXLoader } import respective models.
  18302. *
  18303. * @augments Mesh
  18304. */
  18305. class SkinnedMesh extends Mesh {
  18306. /**
  18307. * Constructs a new skinned mesh.
  18308. *
  18309. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18310. * @param {Material|Array<Material>} [material] - The mesh material.
  18311. */
  18312. constructor( geometry, material ) {
  18313. super( geometry, material );
  18314. /**
  18315. * This flag can be used for type testing.
  18316. *
  18317. * @type {boolean}
  18318. * @readonly
  18319. * @default true
  18320. */
  18321. this.isSkinnedMesh = true;
  18322. this.type = 'SkinnedMesh';
  18323. /**
  18324. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18325. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18326. * across multiple skinned meshes.
  18327. *
  18328. * @type {(AttachedBindMode|DetachedBindMode)}
  18329. * @default AttachedBindMode
  18330. */
  18331. this.bindMode = AttachedBindMode;
  18332. /**
  18333. * The base matrix that is used for the bound bone transforms.
  18334. *
  18335. * @type {Matrix4}
  18336. */
  18337. this.bindMatrix = new Matrix4();
  18338. /**
  18339. * The base matrix that is used for resetting the bound bone transforms.
  18340. *
  18341. * @type {Matrix4}
  18342. */
  18343. this.bindMatrixInverse = new Matrix4();
  18344. /**
  18345. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18346. *
  18347. * @type {?Box3}
  18348. * @default null
  18349. */
  18350. this.boundingBox = null;
  18351. /**
  18352. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18353. *
  18354. * @type {?Sphere}
  18355. * @default null
  18356. */
  18357. this.boundingSphere = null;
  18358. }
  18359. /**
  18360. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18361. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18362. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18363. * the current animation state.
  18364. */
  18365. computeBoundingBox() {
  18366. const geometry = this.geometry;
  18367. if ( this.boundingBox === null ) {
  18368. this.boundingBox = new Box3();
  18369. }
  18370. this.boundingBox.makeEmpty();
  18371. const positionAttribute = geometry.getAttribute( 'position' );
  18372. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18373. this.getVertexPosition( i, _vertex );
  18374. this.boundingBox.expandByPoint( _vertex );
  18375. }
  18376. }
  18377. /**
  18378. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18379. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18380. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18381. * per frame in order to reflect the current animation state.
  18382. */
  18383. computeBoundingSphere() {
  18384. const geometry = this.geometry;
  18385. if ( this.boundingSphere === null ) {
  18386. this.boundingSphere = new Sphere();
  18387. }
  18388. this.boundingSphere.makeEmpty();
  18389. const positionAttribute = geometry.getAttribute( 'position' );
  18390. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18391. this.getVertexPosition( i, _vertex );
  18392. this.boundingSphere.expandByPoint( _vertex );
  18393. }
  18394. }
  18395. copy( source, recursive ) {
  18396. super.copy( source, recursive );
  18397. this.bindMode = source.bindMode;
  18398. this.bindMatrix.copy( source.bindMatrix );
  18399. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18400. this.skeleton = source.skeleton;
  18401. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18402. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18403. return this;
  18404. }
  18405. raycast( raycaster, intersects ) {
  18406. const material = this.material;
  18407. const matrixWorld = this.matrixWorld;
  18408. if ( material === undefined ) return;
  18409. // test with bounding sphere in world space
  18410. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18411. _sphere$5.copy( this.boundingSphere );
  18412. _sphere$5.applyMatrix4( matrixWorld );
  18413. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18414. // convert ray to local space of skinned mesh
  18415. _inverseMatrix$2.copy( matrixWorld ).invert();
  18416. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18417. // test with bounding box in local space
  18418. if ( this.boundingBox !== null ) {
  18419. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18420. }
  18421. // test for intersections with geometry
  18422. this._computeIntersections( raycaster, intersects, _ray$2 );
  18423. }
  18424. getVertexPosition( index, target ) {
  18425. super.getVertexPosition( index, target );
  18426. this.applyBoneTransform( index, target );
  18427. return target;
  18428. }
  18429. /**
  18430. * Binds the given skeleton to the skinned mesh.
  18431. *
  18432. * @param {Skeleton} skeleton - The skeleton to bind.
  18433. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18434. * the skinned mesh's world matrix will be used instead.
  18435. */
  18436. bind( skeleton, bindMatrix ) {
  18437. this.skeleton = skeleton;
  18438. if ( bindMatrix === undefined ) {
  18439. this.updateMatrixWorld( true );
  18440. this.skeleton.calculateInverses();
  18441. bindMatrix = this.matrixWorld;
  18442. }
  18443. this.bindMatrix.copy( bindMatrix );
  18444. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18445. }
  18446. /**
  18447. * This method sets the skinned mesh in the rest pose).
  18448. */
  18449. pose() {
  18450. this.skeleton.pose();
  18451. }
  18452. /**
  18453. * Normalizes the skin weights which are defined as a buffer attribute
  18454. * in the skinned mesh's geometry.
  18455. */
  18456. normalizeSkinWeights() {
  18457. const vector = new Vector4();
  18458. const skinWeight = this.geometry.attributes.skinWeight;
  18459. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18460. vector.fromBufferAttribute( skinWeight, i );
  18461. const scale = 1.0 / vector.manhattanLength();
  18462. if ( scale !== Infinity ) {
  18463. vector.multiplyScalar( scale );
  18464. } else {
  18465. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18466. }
  18467. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18468. }
  18469. }
  18470. updateMatrixWorld( force ) {
  18471. super.updateMatrixWorld( force );
  18472. if ( this.bindMode === AttachedBindMode ) {
  18473. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18474. } else if ( this.bindMode === DetachedBindMode ) {
  18475. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18476. } else {
  18477. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18478. }
  18479. }
  18480. /**
  18481. * Applies the bone transform associated with the given index to the given
  18482. * vertex position. Returns the updated vector.
  18483. *
  18484. * @param {number} index - The vertex index.
  18485. * @param {Vector3} target - The target object that is used to store the method's result.
  18486. * the skinned mesh's world matrix will be used instead.
  18487. * @return {Vector3} The updated vertex position.
  18488. */
  18489. applyBoneTransform( index, target ) {
  18490. const skeleton = this.skeleton;
  18491. const geometry = this.geometry;
  18492. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18493. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18494. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18495. target.set( 0, 0, 0 );
  18496. for ( let i = 0; i < 4; i ++ ) {
  18497. const weight = _skinWeight.getComponent( i );
  18498. if ( weight !== 0 ) {
  18499. const boneIndex = _skinIndex.getComponent( i );
  18500. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18501. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18502. }
  18503. }
  18504. return target.applyMatrix4( this.bindMatrixInverse );
  18505. }
  18506. }
  18507. /**
  18508. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18509. * the {@link SkinnedMesh}.
  18510. *
  18511. * ```js
  18512. * const root = new THREE.Bone();
  18513. * const child = new THREE.Bone();
  18514. *
  18515. * root.add( child );
  18516. * child.position.y = 5;
  18517. * ```
  18518. *
  18519. * @augments Object3D
  18520. */
  18521. class Bone extends Object3D {
  18522. /**
  18523. * Constructs a new bone.
  18524. */
  18525. constructor() {
  18526. super();
  18527. /**
  18528. * This flag can be used for type testing.
  18529. *
  18530. * @type {boolean}
  18531. * @readonly
  18532. * @default true
  18533. */
  18534. this.isBone = true;
  18535. this.type = 'Bone';
  18536. }
  18537. }
  18538. /**
  18539. * Creates a texture directly from raw buffer data.
  18540. *
  18541. * The interpretation of the data depends on type and format: If the type is
  18542. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18543. * texel data. If the format is `RGBAFormat`, data needs four values for
  18544. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18545. *
  18546. * @augments Texture
  18547. */
  18548. class DataTexture extends Texture {
  18549. /**
  18550. * Constructs a new data texture.
  18551. *
  18552. * @param {?TypedArray} [data=null] - The buffer data.
  18553. * @param {number} [width=1] - The width of the texture.
  18554. * @param {number} [height=1] - The height of the texture.
  18555. * @param {number} [format=RGBAFormat] - The texture format.
  18556. * @param {number} [type=UnsignedByteType] - The texture type.
  18557. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18558. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18559. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18560. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18561. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18562. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18563. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18564. */
  18565. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18566. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18567. /**
  18568. * This flag can be used for type testing.
  18569. *
  18570. * @type {boolean}
  18571. * @readonly
  18572. * @default true
  18573. */
  18574. this.isDataTexture = true;
  18575. /**
  18576. * The image definition of a data texture.
  18577. *
  18578. * @type {{data:TypedArray,width:number,height:number}}
  18579. */
  18580. this.image = { data: data, width: width, height: height };
  18581. /**
  18582. * Whether to generate mipmaps (if possible) for a texture.
  18583. *
  18584. * Overwritten and set to `false` by default.
  18585. *
  18586. * @type {boolean}
  18587. * @default false
  18588. */
  18589. this.generateMipmaps = false;
  18590. /**
  18591. * If set to `true`, the texture is flipped along the vertical axis when
  18592. * uploaded to the GPU.
  18593. *
  18594. * Overwritten and set to `false` by default.
  18595. *
  18596. * @type {boolean}
  18597. * @default false
  18598. */
  18599. this.flipY = false;
  18600. /**
  18601. * Specifies the alignment requirements for the start of each pixel row in memory.
  18602. *
  18603. * Overwritten and set to `1` by default.
  18604. *
  18605. * @type {boolean}
  18606. * @default 1
  18607. */
  18608. this.unpackAlignment = 1;
  18609. }
  18610. }
  18611. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18612. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18613. /**
  18614. * Class for representing the armatures in `three.js`. The skeleton
  18615. * is defined by a hierarchy of bones.
  18616. *
  18617. * ```js
  18618. * const bones = [];
  18619. *
  18620. * const shoulder = new THREE.Bone();
  18621. * const elbow = new THREE.Bone();
  18622. * const hand = new THREE.Bone();
  18623. *
  18624. * shoulder.add( elbow );
  18625. * elbow.add( hand );
  18626. *
  18627. * bones.push( shoulder , elbow, hand);
  18628. *
  18629. * shoulder.position.y = -5;
  18630. * elbow.position.y = 0;
  18631. * hand.position.y = 5;
  18632. *
  18633. * const armSkeleton = new THREE.Skeleton( bones );
  18634. * ```
  18635. */
  18636. class Skeleton {
  18637. /**
  18638. * Constructs a new skeleton.
  18639. *
  18640. * @param {Array<Bone>} [bones] - An array of bones.
  18641. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18642. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18643. */
  18644. constructor( bones = [], boneInverses = [] ) {
  18645. this.uuid = generateUUID();
  18646. /**
  18647. * An array of bones defining the skeleton.
  18648. *
  18649. * @type {Array<Bone>}
  18650. */
  18651. this.bones = bones.slice( 0 );
  18652. /**
  18653. * An array of bone inverse matrices.
  18654. *
  18655. * @type {Array<Matrix4>}
  18656. */
  18657. this.boneInverses = boneInverses;
  18658. /**
  18659. * An array buffer holding the bone data.
  18660. * Input data for {@link Skeleton#boneTexture}.
  18661. *
  18662. * @type {?Float32Array}
  18663. * @default null
  18664. */
  18665. this.boneMatrices = null;
  18666. /**
  18667. * A texture holding the bone data for use
  18668. * in the vertex shader.
  18669. *
  18670. * @type {?DataTexture}
  18671. * @default null
  18672. */
  18673. this.boneTexture = null;
  18674. this.init();
  18675. }
  18676. /**
  18677. * Initializes the skeleton. This method gets automatically called by the constructor
  18678. * but depending on how the skeleton is created it might be necessary to call this method
  18679. * manually.
  18680. */
  18681. init() {
  18682. const bones = this.bones;
  18683. const boneInverses = this.boneInverses;
  18684. this.boneMatrices = new Float32Array( bones.length * 16 );
  18685. // calculate inverse bone matrices if necessary
  18686. if ( boneInverses.length === 0 ) {
  18687. this.calculateInverses();
  18688. } else {
  18689. // handle special case
  18690. if ( bones.length !== boneInverses.length ) {
  18691. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18692. this.boneInverses = [];
  18693. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18694. this.boneInverses.push( new Matrix4() );
  18695. }
  18696. }
  18697. }
  18698. }
  18699. /**
  18700. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18701. * and fills it with new matrices.
  18702. */
  18703. calculateInverses() {
  18704. this.boneInverses.length = 0;
  18705. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18706. const inverse = new Matrix4();
  18707. if ( this.bones[ i ] ) {
  18708. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18709. }
  18710. this.boneInverses.push( inverse );
  18711. }
  18712. }
  18713. /**
  18714. * Resets the skeleton to the base pose.
  18715. */
  18716. pose() {
  18717. // recover the bind-time world matrices
  18718. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18719. const bone = this.bones[ i ];
  18720. if ( bone ) {
  18721. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18722. }
  18723. }
  18724. // compute the local matrices, positions, rotations and scales
  18725. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18726. const bone = this.bones[ i ];
  18727. if ( bone ) {
  18728. if ( bone.parent && bone.parent.isBone ) {
  18729. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18730. bone.matrix.multiply( bone.matrixWorld );
  18731. } else {
  18732. bone.matrix.copy( bone.matrixWorld );
  18733. }
  18734. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18735. }
  18736. }
  18737. }
  18738. /**
  18739. * Resets the skeleton to the base pose.
  18740. */
  18741. update() {
  18742. const bones = this.bones;
  18743. const boneInverses = this.boneInverses;
  18744. const boneMatrices = this.boneMatrices;
  18745. const boneTexture = this.boneTexture;
  18746. // flatten bone matrices to array
  18747. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18748. // compute the offset between the current and the original transform
  18749. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18750. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18751. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18752. }
  18753. if ( boneTexture !== null ) {
  18754. boneTexture.needsUpdate = true;
  18755. }
  18756. }
  18757. /**
  18758. * Returns a new skeleton with copied values from this instance.
  18759. *
  18760. * @return {Skeleton} A clone of this instance.
  18761. */
  18762. clone() {
  18763. return new Skeleton( this.bones, this.boneInverses );
  18764. }
  18765. /**
  18766. * Computes a data texture for passing bone data to the vertex shader.
  18767. *
  18768. * @return {Skeleton} A reference of this instance.
  18769. */
  18770. computeBoneTexture() {
  18771. // layout (1 matrix = 4 pixels)
  18772. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18773. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18774. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18775. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18776. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18777. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18778. size = Math.ceil( size / 4 ) * 4;
  18779. size = Math.max( size, 4 );
  18780. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18781. boneMatrices.set( this.boneMatrices ); // copy current values
  18782. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18783. boneTexture.needsUpdate = true;
  18784. this.boneMatrices = boneMatrices;
  18785. this.boneTexture = boneTexture;
  18786. return this;
  18787. }
  18788. /**
  18789. * Searches through the skeleton's bone array and returns the first with a
  18790. * matching name.
  18791. *
  18792. * @param {string} name - The name of the bone.
  18793. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18794. */
  18795. getBoneByName( name ) {
  18796. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18797. const bone = this.bones[ i ];
  18798. if ( bone.name === name ) {
  18799. return bone;
  18800. }
  18801. }
  18802. return undefined;
  18803. }
  18804. /**
  18805. * Frees the GPU-related resources allocated by this instance. Call this
  18806. * method whenever this instance is no longer used in your app.
  18807. */
  18808. dispose( ) {
  18809. if ( this.boneTexture !== null ) {
  18810. this.boneTexture.dispose();
  18811. this.boneTexture = null;
  18812. }
  18813. }
  18814. /**
  18815. * Setups the skeleton by the given JSON and bones.
  18816. *
  18817. * @param {Object} json - The skeleton as serialized JSON.
  18818. * @param {Object<string, Bone>} bones - An array of bones.
  18819. * @return {Skeleton} A reference of this instance.
  18820. */
  18821. fromJSON( json, bones ) {
  18822. this.uuid = json.uuid;
  18823. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18824. const uuid = json.bones[ i ];
  18825. let bone = bones[ uuid ];
  18826. if ( bone === undefined ) {
  18827. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18828. bone = new Bone();
  18829. }
  18830. this.bones.push( bone );
  18831. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18832. }
  18833. this.init();
  18834. return this;
  18835. }
  18836. /**
  18837. * Serializes the skeleton into JSON.
  18838. *
  18839. * @return {Object} A JSON object representing the serialized skeleton.
  18840. * @see {@link ObjectLoader#parse}
  18841. */
  18842. toJSON() {
  18843. const data = {
  18844. metadata: {
  18845. version: 4.7,
  18846. type: 'Skeleton',
  18847. generator: 'Skeleton.toJSON'
  18848. },
  18849. bones: [],
  18850. boneInverses: []
  18851. };
  18852. data.uuid = this.uuid;
  18853. const bones = this.bones;
  18854. const boneInverses = this.boneInverses;
  18855. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18856. const bone = bones[ i ];
  18857. data.bones.push( bone.uuid );
  18858. const boneInverse = boneInverses[ i ];
  18859. data.boneInverses.push( boneInverse.toArray() );
  18860. }
  18861. return data;
  18862. }
  18863. }
  18864. /**
  18865. * An instanced version of a buffer attribute.
  18866. *
  18867. * @augments BufferAttribute
  18868. */
  18869. class InstancedBufferAttribute extends BufferAttribute {
  18870. /**
  18871. * Constructs a new instanced buffer attribute.
  18872. *
  18873. * @param {TypedArray} array - The array holding the attribute data.
  18874. * @param {number} itemSize - The item size.
  18875. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18876. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18877. */
  18878. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18879. super( array, itemSize, normalized );
  18880. /**
  18881. * This flag can be used for type testing.
  18882. *
  18883. * @type {boolean}
  18884. * @readonly
  18885. * @default true
  18886. */
  18887. this.isInstancedBufferAttribute = true;
  18888. /**
  18889. * Defines how often a value of this buffer attribute should be repeated. A
  18890. * value of one means that each value of the instanced attribute is used for
  18891. * a single instance. A value of two means that each value is used for two
  18892. * consecutive instances (and so on).
  18893. *
  18894. * @type {number}
  18895. * @default 1
  18896. */
  18897. this.meshPerAttribute = meshPerAttribute;
  18898. }
  18899. copy( source ) {
  18900. super.copy( source );
  18901. this.meshPerAttribute = source.meshPerAttribute;
  18902. return this;
  18903. }
  18904. toJSON() {
  18905. const data = super.toJSON();
  18906. data.meshPerAttribute = this.meshPerAttribute;
  18907. data.isInstancedBufferAttribute = true;
  18908. return data;
  18909. }
  18910. }
  18911. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18912. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18913. const _instanceIntersects = [];
  18914. const _box3 = /*@__PURE__*/ new Box3();
  18915. const _identity = /*@__PURE__*/ new Matrix4();
  18916. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18917. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18918. /**
  18919. * A special version of a mesh with instanced rendering support. Use
  18920. * this class if you have to render a large number of objects with the same
  18921. * geometry and material(s) but with different world transformations. The usage
  18922. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18923. * improve the overall rendering performance in your application.
  18924. *
  18925. * @augments Mesh
  18926. */
  18927. class InstancedMesh extends Mesh {
  18928. /**
  18929. * Constructs a new instanced mesh.
  18930. *
  18931. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18932. * @param {Material|Array<Material>} [material] - The mesh material.
  18933. * @param {number} count - The number of instances.
  18934. */
  18935. constructor( geometry, material, count ) {
  18936. super( geometry, material );
  18937. /**
  18938. * This flag can be used for type testing.
  18939. *
  18940. * @type {boolean}
  18941. * @readonly
  18942. * @default true
  18943. */
  18944. this.isInstancedMesh = true;
  18945. /**
  18946. * Represents the local transformation of all instances. You have to set its
  18947. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18948. * via {@link InstancedMesh#setMatrixAt}.
  18949. *
  18950. * @type {InstancedBufferAttribute}
  18951. */
  18952. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18953. /**
  18954. * Represents the color of all instances. You have to set its
  18955. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18956. * via {@link InstancedMesh#setColorAt}.
  18957. *
  18958. * @type {?InstancedBufferAttribute}
  18959. * @default null
  18960. */
  18961. this.instanceColor = null;
  18962. /**
  18963. * Represents the morph target weights of all instances. You have to set its
  18964. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  18965. * via {@link InstancedMesh#setMorphAt}.
  18966. *
  18967. * @type {?DataTexture}
  18968. * @default null
  18969. */
  18970. this.morphTexture = null;
  18971. /**
  18972. * The number of instances.
  18973. *
  18974. * @type {number}
  18975. */
  18976. this.count = count;
  18977. /**
  18978. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  18979. *
  18980. * @type {?Box3}
  18981. * @default null
  18982. */
  18983. this.boundingBox = null;
  18984. /**
  18985. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  18986. *
  18987. * @type {?Sphere}
  18988. * @default null
  18989. */
  18990. this.boundingSphere = null;
  18991. for ( let i = 0; i < count; i ++ ) {
  18992. this.setMatrixAt( i, _identity );
  18993. }
  18994. }
  18995. /**
  18996. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  18997. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18998. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  18999. */
  19000. computeBoundingBox() {
  19001. const geometry = this.geometry;
  19002. const count = this.count;
  19003. if ( this.boundingBox === null ) {
  19004. this.boundingBox = new Box3();
  19005. }
  19006. if ( geometry.boundingBox === null ) {
  19007. geometry.computeBoundingBox();
  19008. }
  19009. this.boundingBox.makeEmpty();
  19010. for ( let i = 0; i < count; i ++ ) {
  19011. this.getMatrixAt( i, _instanceLocalMatrix );
  19012. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19013. this.boundingBox.union( _box3 );
  19014. }
  19015. }
  19016. /**
  19017. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19018. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19019. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19020. */
  19021. computeBoundingSphere() {
  19022. const geometry = this.geometry;
  19023. const count = this.count;
  19024. if ( this.boundingSphere === null ) {
  19025. this.boundingSphere = new Sphere();
  19026. }
  19027. if ( geometry.boundingSphere === null ) {
  19028. geometry.computeBoundingSphere();
  19029. }
  19030. this.boundingSphere.makeEmpty();
  19031. for ( let i = 0; i < count; i ++ ) {
  19032. this.getMatrixAt( i, _instanceLocalMatrix );
  19033. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19034. this.boundingSphere.union( _sphere$4 );
  19035. }
  19036. }
  19037. copy( source, recursive ) {
  19038. super.copy( source, recursive );
  19039. this.instanceMatrix.copy( source.instanceMatrix );
  19040. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19041. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19042. this.count = source.count;
  19043. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19044. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19045. return this;
  19046. }
  19047. /**
  19048. * Gets the color of the defined instance.
  19049. *
  19050. * @param {number} index - The instance index.
  19051. * @param {Color} color - The target object that is used to store the method's result.
  19052. */
  19053. getColorAt( index, color ) {
  19054. color.fromArray( this.instanceColor.array, index * 3 );
  19055. }
  19056. /**
  19057. * Gets the local transformation matrix of the defined instance.
  19058. *
  19059. * @param {number} index - The instance index.
  19060. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19061. */
  19062. getMatrixAt( index, matrix ) {
  19063. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19064. }
  19065. /**
  19066. * Gets the morph target weights of the defined instance.
  19067. *
  19068. * @param {number} index - The instance index.
  19069. * @param {Mesh} object - The target object that is used to store the method's result.
  19070. */
  19071. getMorphAt( index, object ) {
  19072. const objectInfluences = object.morphTargetInfluences;
  19073. const array = this.morphTexture.source.data.data;
  19074. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19075. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19076. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19077. objectInfluences[ i ] = array[ dataIndex + i ];
  19078. }
  19079. }
  19080. raycast( raycaster, intersects ) {
  19081. const matrixWorld = this.matrixWorld;
  19082. const raycastTimes = this.count;
  19083. _mesh$1.geometry = this.geometry;
  19084. _mesh$1.material = this.material;
  19085. if ( _mesh$1.material === undefined ) return;
  19086. // test with bounding sphere first
  19087. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19088. _sphere$4.copy( this.boundingSphere );
  19089. _sphere$4.applyMatrix4( matrixWorld );
  19090. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19091. // now test each instance
  19092. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19093. // calculate the world matrix for each instance
  19094. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19095. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19096. // the mesh represents this single instance
  19097. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19098. _mesh$1.raycast( raycaster, _instanceIntersects );
  19099. // process the result of raycast
  19100. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19101. const intersect = _instanceIntersects[ i ];
  19102. intersect.instanceId = instanceId;
  19103. intersect.object = this;
  19104. intersects.push( intersect );
  19105. }
  19106. _instanceIntersects.length = 0;
  19107. }
  19108. }
  19109. /**
  19110. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19111. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19112. *
  19113. * @param {number} index - The instance index.
  19114. * @param {Color} color - The instance color.
  19115. */
  19116. setColorAt( index, color ) {
  19117. if ( this.instanceColor === null ) {
  19118. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19119. }
  19120. color.toArray( this.instanceColor.array, index * 3 );
  19121. }
  19122. /**
  19123. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19124. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19125. *
  19126. * @param {number} index - The instance index.
  19127. * @param {Matrix4} matrix - The local transformation.
  19128. */
  19129. setMatrixAt( index, matrix ) {
  19130. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19131. }
  19132. /**
  19133. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19134. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19135. *
  19136. * @param {number} index - The instance index.
  19137. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19138. * of a single instance.
  19139. */
  19140. setMorphAt( index, object ) {
  19141. const objectInfluences = object.morphTargetInfluences;
  19142. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19143. if ( this.morphTexture === null ) {
  19144. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19145. }
  19146. const array = this.morphTexture.source.data.data;
  19147. let morphInfluencesSum = 0;
  19148. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19149. morphInfluencesSum += objectInfluences[ i ];
  19150. }
  19151. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19152. const dataIndex = len * index;
  19153. array[ dataIndex ] = morphBaseInfluence;
  19154. array.set( objectInfluences, dataIndex + 1 );
  19155. }
  19156. updateMorphTargets() {
  19157. }
  19158. /**
  19159. * Frees the GPU-related resources allocated by this instance. Call this
  19160. * method whenever this instance is no longer used in your app.
  19161. */
  19162. dispose() {
  19163. this.dispatchEvent( { type: 'dispose' } );
  19164. if ( this.morphTexture !== null ) {
  19165. this.morphTexture.dispose();
  19166. this.morphTexture = null;
  19167. }
  19168. }
  19169. }
  19170. const _vector1 = /*@__PURE__*/ new Vector3();
  19171. const _vector2 = /*@__PURE__*/ new Vector3();
  19172. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19173. /**
  19174. * A two dimensional surface that extends infinitely in 3D space, represented
  19175. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19176. * by a unit length normal vector and a constant.
  19177. */
  19178. class Plane {
  19179. /**
  19180. * Constructs a new plane.
  19181. *
  19182. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19183. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19184. */
  19185. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19186. /**
  19187. * This flag can be used for type testing.
  19188. *
  19189. * @type {boolean}
  19190. * @readonly
  19191. * @default true
  19192. */
  19193. this.isPlane = true;
  19194. /**
  19195. * A unit length vector defining the normal of the plane.
  19196. *
  19197. * @type {Vector3}
  19198. */
  19199. this.normal = normal;
  19200. /**
  19201. * The signed distance from the origin to the plane.
  19202. *
  19203. * @type {number}
  19204. * @default 0
  19205. */
  19206. this.constant = constant;
  19207. }
  19208. /**
  19209. * Sets the plane components by copying the given values.
  19210. *
  19211. * @param {Vector3} normal - The normal.
  19212. * @param {number} constant - The constant.
  19213. * @return {Plane} A reference to this plane.
  19214. */
  19215. set( normal, constant ) {
  19216. this.normal.copy( normal );
  19217. this.constant = constant;
  19218. return this;
  19219. }
  19220. /**
  19221. * Sets the plane components by defining `x`, `y`, `z` as the
  19222. * plane normal and `w` as the constant.
  19223. *
  19224. * @param {number} x - The value for the normal's x component.
  19225. * @param {number} y - The value for the normal's y component.
  19226. * @param {number} z - The value for the normal's z component.
  19227. * @param {number} w - The constant value.
  19228. * @return {Plane} A reference to this plane.
  19229. */
  19230. setComponents( x, y, z, w ) {
  19231. this.normal.set( x, y, z );
  19232. this.constant = w;
  19233. return this;
  19234. }
  19235. /**
  19236. * Sets the plane from the given normal and coplanar point (that is a point
  19237. * that lies onto the plane).
  19238. *
  19239. * @param {Vector3} normal - The normal.
  19240. * @param {Vector3} point - A coplanar point.
  19241. * @return {Plane} A reference to this plane.
  19242. */
  19243. setFromNormalAndCoplanarPoint( normal, point ) {
  19244. this.normal.copy( normal );
  19245. this.constant = - point.dot( this.normal );
  19246. return this;
  19247. }
  19248. /**
  19249. * Sets the plane from three coplanar points. The winding order is
  19250. * assumed to be counter-clockwise, and determines the direction of
  19251. * the plane normal.
  19252. *
  19253. * @param {Vector3} a - The first coplanar point.
  19254. * @param {Vector3} b - The second coplanar point.
  19255. * @param {Vector3} c - The third coplanar point.
  19256. * @return {Plane} A reference to this plane.
  19257. */
  19258. setFromCoplanarPoints( a, b, c ) {
  19259. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19260. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19261. this.setFromNormalAndCoplanarPoint( normal, a );
  19262. return this;
  19263. }
  19264. /**
  19265. * Copies the values of the given plane to this instance.
  19266. *
  19267. * @param {Plane} plane - The plane to copy.
  19268. * @return {Plane} A reference to this plane.
  19269. */
  19270. copy( plane ) {
  19271. this.normal.copy( plane.normal );
  19272. this.constant = plane.constant;
  19273. return this;
  19274. }
  19275. /**
  19276. * Normalizes the plane normal and adjusts the constant accordingly.
  19277. *
  19278. * @return {Plane} A reference to this plane.
  19279. */
  19280. normalize() {
  19281. // Note: will lead to a divide by zero if the plane is invalid.
  19282. const inverseNormalLength = 1.0 / this.normal.length();
  19283. this.normal.multiplyScalar( inverseNormalLength );
  19284. this.constant *= inverseNormalLength;
  19285. return this;
  19286. }
  19287. /**
  19288. * Negates both the plane normal and the constant.
  19289. *
  19290. * @return {Plane} A reference to this plane.
  19291. */
  19292. negate() {
  19293. this.constant *= -1;
  19294. this.normal.negate();
  19295. return this;
  19296. }
  19297. /**
  19298. * Returns the signed distance from the given point to this plane.
  19299. *
  19300. * @param {Vector3} point - The point to compute the distance for.
  19301. * @return {number} The signed distance.
  19302. */
  19303. distanceToPoint( point ) {
  19304. return this.normal.dot( point ) + this.constant;
  19305. }
  19306. /**
  19307. * Returns the signed distance from the given sphere to this plane.
  19308. *
  19309. * @param {Sphere} sphere - The sphere to compute the distance for.
  19310. * @return {number} The signed distance.
  19311. */
  19312. distanceToSphere( sphere ) {
  19313. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19314. }
  19315. /**
  19316. * Projects a the given point onto the plane.
  19317. *
  19318. * @param {Vector3} point - The point to project.
  19319. * @param {Vector3} target - The target vector that is used to store the method's result.
  19320. * @return {Vector3} The projected point on the plane.
  19321. */
  19322. projectPoint( point, target ) {
  19323. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19324. }
  19325. /**
  19326. * Returns the intersection point of the passed line and the plane. Returns
  19327. * `null` if the line does not intersect. Returns the line's starting point if
  19328. * the line is coplanar with the plane.
  19329. *
  19330. * @param {Line3} line - The line to compute the intersection for.
  19331. * @param {Vector3} target - The target vector that is used to store the method's result.
  19332. * @return {?Vector3} The intersection point.
  19333. */
  19334. intersectLine( line, target ) {
  19335. const direction = line.delta( _vector1 );
  19336. const denominator = this.normal.dot( direction );
  19337. if ( denominator === 0 ) {
  19338. // line is coplanar, return origin
  19339. if ( this.distanceToPoint( line.start ) === 0 ) {
  19340. return target.copy( line.start );
  19341. }
  19342. // Unsure if this is the correct method to handle this case.
  19343. return null;
  19344. }
  19345. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19346. if ( t < 0 || t > 1 ) {
  19347. return null;
  19348. }
  19349. return target.copy( line.start ).addScaledVector( direction, t );
  19350. }
  19351. /**
  19352. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19353. *
  19354. * @param {Line3} line - The line to test.
  19355. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19356. */
  19357. intersectsLine( line ) {
  19358. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19359. const startSign = this.distanceToPoint( line.start );
  19360. const endSign = this.distanceToPoint( line.end );
  19361. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19362. }
  19363. /**
  19364. * Returns `true` if the given bounding box intersects with the plane.
  19365. *
  19366. * @param {Box3} box - The bounding box to test.
  19367. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19368. */
  19369. intersectsBox( box ) {
  19370. return box.intersectsPlane( this );
  19371. }
  19372. /**
  19373. * Returns `true` if the given bounding sphere intersects with the plane.
  19374. *
  19375. * @param {Sphere} sphere - The bounding sphere to test.
  19376. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19377. */
  19378. intersectsSphere( sphere ) {
  19379. return sphere.intersectsPlane( this );
  19380. }
  19381. /**
  19382. * Returns a coplanar vector to the plane, by calculating the
  19383. * projection of the normal at the origin onto the plane.
  19384. *
  19385. * @param {Vector3} target - The target vector that is used to store the method's result.
  19386. * @return {Vector3} The coplanar point.
  19387. */
  19388. coplanarPoint( target ) {
  19389. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19390. }
  19391. /**
  19392. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19393. *
  19394. * The optional normal matrix can be pre-computed like so:
  19395. * ```js
  19396. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19397. * ```
  19398. *
  19399. * @param {Matrix4} matrix - The transformation matrix.
  19400. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19401. * @return {Plane} A reference to this plane.
  19402. */
  19403. applyMatrix4( matrix, optionalNormalMatrix ) {
  19404. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19405. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19406. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19407. this.constant = - referencePoint.dot( normal );
  19408. return this;
  19409. }
  19410. /**
  19411. * Translates the plane by the distance defined by the given offset vector.
  19412. * Note that this only affects the plane constant and will not affect the normal vector.
  19413. *
  19414. * @param {Vector3} offset - The offset vector.
  19415. * @return {Plane} A reference to this plane.
  19416. */
  19417. translate( offset ) {
  19418. this.constant -= offset.dot( this.normal );
  19419. return this;
  19420. }
  19421. /**
  19422. * Returns `true` if this plane is equal with the given one.
  19423. *
  19424. * @param {Plane} plane - The plane to test for equality.
  19425. * @return {boolean} Whether this plane is equal with the given one.
  19426. */
  19427. equals( plane ) {
  19428. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19429. }
  19430. /**
  19431. * Returns a new plane with copied values from this instance.
  19432. *
  19433. * @return {Plane} A clone of this instance.
  19434. */
  19435. clone() {
  19436. return new this.constructor().copy( this );
  19437. }
  19438. }
  19439. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19440. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19441. const _vector$6 = /*@__PURE__*/ new Vector3();
  19442. /**
  19443. * Frustums are used to determine what is inside the camera's field of view.
  19444. * They help speed up the rendering process - objects which lie outside a camera's
  19445. * frustum can safely be excluded from rendering.
  19446. *
  19447. * This class is mainly intended for use internally by a renderer.
  19448. */
  19449. class Frustum {
  19450. /**
  19451. * Constructs a new frustum.
  19452. *
  19453. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19454. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19455. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19456. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19457. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19458. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19459. */
  19460. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19461. /**
  19462. * This array holds the planes that enclose the frustum.
  19463. *
  19464. * @type {Array<Plane>}
  19465. */
  19466. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19467. }
  19468. /**
  19469. * Sets the frustum planes by copying the given planes.
  19470. *
  19471. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19472. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19473. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19474. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19475. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19476. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19477. * @return {Frustum} A reference to this frustum.
  19478. */
  19479. set( p0, p1, p2, p3, p4, p5 ) {
  19480. const planes = this.planes;
  19481. planes[ 0 ].copy( p0 );
  19482. planes[ 1 ].copy( p1 );
  19483. planes[ 2 ].copy( p2 );
  19484. planes[ 3 ].copy( p3 );
  19485. planes[ 4 ].copy( p4 );
  19486. planes[ 5 ].copy( p5 );
  19487. return this;
  19488. }
  19489. /**
  19490. * Copies the values of the given frustum to this instance.
  19491. *
  19492. * @param {Frustum} frustum - The frustum to copy.
  19493. * @return {Frustum} A reference to this frustum.
  19494. */
  19495. copy( frustum ) {
  19496. const planes = this.planes;
  19497. for ( let i = 0; i < 6; i ++ ) {
  19498. planes[ i ].copy( frustum.planes[ i ] );
  19499. }
  19500. return this;
  19501. }
  19502. /**
  19503. * Sets the frustum planes from the given projection matrix.
  19504. *
  19505. * @param {Matrix4} m - The projection matrix.
  19506. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19507. * @return {Frustum} A reference to this frustum.
  19508. */
  19509. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  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. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  19521. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19522. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  19523. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19524. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  19525. } else {
  19526. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19527. }
  19528. return this;
  19529. }
  19530. /**
  19531. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19532. *
  19533. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19534. *
  19535. * @param {Object3D} object - The 3D object to test.
  19536. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19537. */
  19538. intersectsObject( object ) {
  19539. if ( object.boundingSphere !== undefined ) {
  19540. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19541. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19542. } else {
  19543. const geometry = object.geometry;
  19544. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19545. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19546. }
  19547. return this.intersectsSphere( _sphere$3 );
  19548. }
  19549. /**
  19550. * Returns `true` if the given sprite is intersecting this frustum.
  19551. *
  19552. * @param {Sprite} sprite - The sprite to test.
  19553. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19554. */
  19555. intersectsSprite( sprite ) {
  19556. _sphere$3.center.set( 0, 0, 0 );
  19557. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19558. _sphere$3.radius = 0.7071067811865476 + offset;
  19559. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19560. return this.intersectsSphere( _sphere$3 );
  19561. }
  19562. /**
  19563. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19564. *
  19565. * @param {Sphere} sphere - The bounding sphere to test.
  19566. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19567. */
  19568. intersectsSphere( sphere ) {
  19569. const planes = this.planes;
  19570. const center = sphere.center;
  19571. const negRadius = - sphere.radius;
  19572. for ( let i = 0; i < 6; i ++ ) {
  19573. const distance = planes[ i ].distanceToPoint( center );
  19574. if ( distance < negRadius ) {
  19575. return false;
  19576. }
  19577. }
  19578. return true;
  19579. }
  19580. /**
  19581. * Returns `true` if the given bounding box is intersecting this frustum.
  19582. *
  19583. * @param {Box3} box - The bounding box to test.
  19584. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19585. */
  19586. intersectsBox( box ) {
  19587. const planes = this.planes;
  19588. for ( let i = 0; i < 6; i ++ ) {
  19589. const plane = planes[ i ];
  19590. // corner at max distance
  19591. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19592. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19593. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19594. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19595. return false;
  19596. }
  19597. }
  19598. return true;
  19599. }
  19600. /**
  19601. * Returns `true` if the given point lies within the frustum.
  19602. *
  19603. * @param {Vector3} point - The point to test.
  19604. * @return {boolean} Whether the point lies within this frustum or not.
  19605. */
  19606. containsPoint( point ) {
  19607. const planes = this.planes;
  19608. for ( let i = 0; i < 6; i ++ ) {
  19609. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19610. return false;
  19611. }
  19612. }
  19613. return true;
  19614. }
  19615. /**
  19616. * Returns a new frustum with copied values from this instance.
  19617. *
  19618. * @return {Frustum} A clone of this instance.
  19619. */
  19620. clone() {
  19621. return new this.constructor().copy( this );
  19622. }
  19623. }
  19624. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19625. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19626. /**
  19627. * FrustumArray is used to determine if an object is visible in at least one camera
  19628. * from an array of cameras. This is particularly useful for multi-view renderers.
  19629. */
  19630. class FrustumArray {
  19631. /**
  19632. * Constructs a new frustum array.
  19633. *
  19634. */
  19635. constructor() {
  19636. /**
  19637. * The coordinate system to use.
  19638. *
  19639. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19640. * @default WebGLCoordinateSystem
  19641. */
  19642. this.coordinateSystem = WebGLCoordinateSystem;
  19643. }
  19644. /**
  19645. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19646. * from the camera array.
  19647. *
  19648. * @param {Object3D} object - The 3D object to test.
  19649. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19650. * @return {boolean} Whether the 3D object is visible in any camera.
  19651. */
  19652. intersectsObject( object, cameraArray ) {
  19653. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19654. return false;
  19655. }
  19656. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19657. const camera = cameraArray.cameras[ i ];
  19658. _projScreenMatrix$2.multiplyMatrices(
  19659. camera.projectionMatrix,
  19660. camera.matrixWorldInverse
  19661. );
  19662. _frustum$1.setFromProjectionMatrix(
  19663. _projScreenMatrix$2,
  19664. this.coordinateSystem
  19665. );
  19666. if ( _frustum$1.intersectsObject( object ) ) {
  19667. return true; // Object is visible in at least one camera
  19668. }
  19669. }
  19670. return false; // Not visible in any camera
  19671. }
  19672. /**
  19673. * Returns `true` if the given sprite is intersecting any frustum
  19674. * from the camera array.
  19675. *
  19676. * @param {Sprite} sprite - The sprite to test.
  19677. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19678. * @return {boolean} Whether the sprite is visible in any camera.
  19679. */
  19680. intersectsSprite( sprite, cameraArray ) {
  19681. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19682. return false;
  19683. }
  19684. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19685. const camera = cameraArray.cameras[ i ];
  19686. _projScreenMatrix$2.multiplyMatrices(
  19687. camera.projectionMatrix,
  19688. camera.matrixWorldInverse
  19689. );
  19690. _frustum$1.setFromProjectionMatrix(
  19691. _projScreenMatrix$2,
  19692. this.coordinateSystem
  19693. );
  19694. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19695. return true; // Sprite is visible in at least one camera
  19696. }
  19697. }
  19698. return false; // Not visible in any camera
  19699. }
  19700. /**
  19701. * Returns `true` if the given bounding sphere is intersecting any frustum
  19702. * from the camera array.
  19703. *
  19704. * @param {Sphere} sphere - The bounding sphere to test.
  19705. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19706. * @return {boolean} Whether the sphere is visible in any camera.
  19707. */
  19708. intersectsSphere( sphere, cameraArray ) {
  19709. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19710. return false;
  19711. }
  19712. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19713. const camera = cameraArray.cameras[ i ];
  19714. _projScreenMatrix$2.multiplyMatrices(
  19715. camera.projectionMatrix,
  19716. camera.matrixWorldInverse
  19717. );
  19718. _frustum$1.setFromProjectionMatrix(
  19719. _projScreenMatrix$2,
  19720. this.coordinateSystem
  19721. );
  19722. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19723. return true; // Sphere is visible in at least one camera
  19724. }
  19725. }
  19726. return false; // Not visible in any camera
  19727. }
  19728. /**
  19729. * Returns `true` if the given bounding box is intersecting any frustum
  19730. * from the camera array.
  19731. *
  19732. * @param {Box3} box - The bounding box to test.
  19733. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19734. * @return {boolean} Whether the box is visible in any camera.
  19735. */
  19736. intersectsBox( box, cameraArray ) {
  19737. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19738. return false;
  19739. }
  19740. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19741. const camera = cameraArray.cameras[ i ];
  19742. _projScreenMatrix$2.multiplyMatrices(
  19743. camera.projectionMatrix,
  19744. camera.matrixWorldInverse
  19745. );
  19746. _frustum$1.setFromProjectionMatrix(
  19747. _projScreenMatrix$2,
  19748. this.coordinateSystem
  19749. );
  19750. if ( _frustum$1.intersectsBox( box ) ) {
  19751. return true; // Box is visible in at least one camera
  19752. }
  19753. }
  19754. return false; // Not visible in any camera
  19755. }
  19756. /**
  19757. * Returns `true` if the given point lies within any frustum
  19758. * from the camera array.
  19759. *
  19760. * @param {Vector3} point - The point to test.
  19761. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19762. * @return {boolean} Whether the point is visible in any camera.
  19763. */
  19764. containsPoint( point, cameraArray ) {
  19765. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19766. return false;
  19767. }
  19768. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19769. const camera = cameraArray.cameras[ i ];
  19770. _projScreenMatrix$2.multiplyMatrices(
  19771. camera.projectionMatrix,
  19772. camera.matrixWorldInverse
  19773. );
  19774. _frustum$1.setFromProjectionMatrix(
  19775. _projScreenMatrix$2,
  19776. this.coordinateSystem
  19777. );
  19778. if ( _frustum$1.containsPoint( point ) ) {
  19779. return true; // Point is visible in at least one camera
  19780. }
  19781. }
  19782. return false; // Not visible in any camera
  19783. }
  19784. /**
  19785. * Returns a new frustum array with copied values from this instance.
  19786. *
  19787. * @return {FrustumArray} A clone of this instance.
  19788. */
  19789. clone() {
  19790. return new FrustumArray();
  19791. }
  19792. }
  19793. function ascIdSort( a, b ) {
  19794. return a - b;
  19795. }
  19796. function sortOpaque( a, b ) {
  19797. return a.z - b.z;
  19798. }
  19799. function sortTransparent( a, b ) {
  19800. return b.z - a.z;
  19801. }
  19802. class MultiDrawRenderList {
  19803. constructor() {
  19804. this.index = 0;
  19805. this.pool = [];
  19806. this.list = [];
  19807. }
  19808. push( start, count, z, index ) {
  19809. const pool = this.pool;
  19810. const list = this.list;
  19811. if ( this.index >= pool.length ) {
  19812. pool.push( {
  19813. start: -1,
  19814. count: -1,
  19815. z: -1,
  19816. index: -1,
  19817. } );
  19818. }
  19819. const item = pool[ this.index ];
  19820. list.push( item );
  19821. this.index ++;
  19822. item.start = start;
  19823. item.count = count;
  19824. item.z = z;
  19825. item.index = index;
  19826. }
  19827. reset() {
  19828. this.list.length = 0;
  19829. this.index = 0;
  19830. }
  19831. }
  19832. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19833. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19834. const _frustum = /*@__PURE__*/ new Frustum();
  19835. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19836. const _box$1 = /*@__PURE__*/ new Box3();
  19837. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19838. const _vector$5 = /*@__PURE__*/ new Vector3();
  19839. const _forward$1 = /*@__PURE__*/ new Vector3();
  19840. const _temp = /*@__PURE__*/ new Vector3();
  19841. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19842. const _mesh = /*@__PURE__*/ new Mesh();
  19843. const _batchIntersects = [];
  19844. // copies data from attribute "src" into "target" starting at "targetOffset"
  19845. function copyAttributeData( src, target, targetOffset = 0 ) {
  19846. const itemSize = target.itemSize;
  19847. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19848. // use the component getters and setters if the array data cannot
  19849. // be copied directly
  19850. const vertexCount = src.count;
  19851. for ( let i = 0; i < vertexCount; i ++ ) {
  19852. for ( let c = 0; c < itemSize; c ++ ) {
  19853. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19854. }
  19855. }
  19856. } else {
  19857. // faster copy approach using typed array set function
  19858. target.array.set( src.array, targetOffset * itemSize );
  19859. }
  19860. target.needsUpdate = true;
  19861. }
  19862. // safely copies array contents to a potentially smaller array
  19863. function copyArrayContents( src, target ) {
  19864. if ( src.constructor !== target.constructor ) {
  19865. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19866. const len = Math.min( src.length, target.length );
  19867. for ( let i = 0; i < len; i ++ ) {
  19868. target[ i ] = src[ i ];
  19869. }
  19870. } else {
  19871. // if the arrays use the same data layout we can use a fast block copy
  19872. const len = Math.min( src.length, target.length );
  19873. target.set( new src.constructor( src.buffer, 0, len ) );
  19874. }
  19875. }
  19876. /**
  19877. * A special version of a mesh with multi draw batch rendering support. Use
  19878. * this class if you have to render a large number of objects with the same
  19879. * material but with different geometries or world transformations. The usage of
  19880. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19881. * rendering performance in your application.
  19882. *
  19883. * ```js
  19884. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19885. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19886. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19887. *
  19888. * // initialize and add geometries into the batched mesh
  19889. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19890. * const boxGeometryId = batchedMesh.addGeometry( box );
  19891. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19892. *
  19893. * // create instances of those geometries
  19894. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19895. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19896. *
  19897. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19898. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19899. *
  19900. * // position the geometries
  19901. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19902. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19903. *
  19904. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19905. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19906. *
  19907. * scene.add( batchedMesh );
  19908. * ```
  19909. *
  19910. * @augments Mesh
  19911. */
  19912. class BatchedMesh extends Mesh {
  19913. /**
  19914. * Constructs a new batched mesh.
  19915. *
  19916. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19917. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19918. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19919. * @param {Material|Array<Material>} [material] - The mesh material.
  19920. */
  19921. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19922. super( new BufferGeometry(), material );
  19923. /**
  19924. * This flag can be used for type testing.
  19925. *
  19926. * @type {boolean}
  19927. * @readonly
  19928. * @default true
  19929. */
  19930. this.isBatchedMesh = true;
  19931. /**
  19932. * When set ot `true`, the individual objects of a batch are frustum culled.
  19933. *
  19934. * @type {boolean}
  19935. * @default true
  19936. */
  19937. this.perObjectFrustumCulled = true;
  19938. /**
  19939. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  19940. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  19941. * rendered front to back.
  19942. *
  19943. * @type {boolean}
  19944. * @default true
  19945. */
  19946. this.sortObjects = true;
  19947. /**
  19948. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  19949. *
  19950. * @type {?Box3}
  19951. * @default null
  19952. */
  19953. this.boundingBox = null;
  19954. /**
  19955. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  19956. *
  19957. * @type {?Sphere}
  19958. * @default null
  19959. */
  19960. this.boundingSphere = null;
  19961. /**
  19962. * Takes a sort a function that is run before render. The function takes a list of instances to
  19963. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  19964. * sort with.
  19965. *
  19966. * @type {?Function}
  19967. * @default null
  19968. */
  19969. this.customSort = null;
  19970. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  19971. this._instanceInfo = [];
  19972. this._geometryInfo = [];
  19973. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  19974. this._availableInstanceIds = [];
  19975. this._availableGeometryIds = [];
  19976. // used to track where the next point is that geometry should be inserted
  19977. this._nextIndexStart = 0;
  19978. this._nextVertexStart = 0;
  19979. this._geometryCount = 0;
  19980. // flags
  19981. this._visibilityChanged = true;
  19982. this._geometryInitialized = false;
  19983. // cached user options
  19984. this._maxInstanceCount = maxInstanceCount;
  19985. this._maxVertexCount = maxVertexCount;
  19986. this._maxIndexCount = maxIndexCount;
  19987. // buffers for multi draw
  19988. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  19989. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  19990. this._multiDrawCount = 0;
  19991. this._multiDrawInstances = null;
  19992. // Local matrix per geometry by using data texture
  19993. this._matricesTexture = null;
  19994. this._indirectTexture = null;
  19995. this._colorsTexture = null;
  19996. this._initMatricesTexture();
  19997. this._initIndirectTexture();
  19998. }
  19999. /**
  20000. * The maximum number of individual instances that can be stored in the batch.
  20001. *
  20002. * @type {number}
  20003. * @readonly
  20004. */
  20005. get maxInstanceCount() {
  20006. return this._maxInstanceCount;
  20007. }
  20008. /**
  20009. * The instance count.
  20010. *
  20011. * @type {number}
  20012. * @readonly
  20013. */
  20014. get instanceCount() {
  20015. return this._instanceInfo.length - this._availableInstanceIds.length;
  20016. }
  20017. /**
  20018. * The number of unused vertices.
  20019. *
  20020. * @type {number}
  20021. * @readonly
  20022. */
  20023. get unusedVertexCount() {
  20024. return this._maxVertexCount - this._nextVertexStart;
  20025. }
  20026. /**
  20027. * The number of unused indices.
  20028. *
  20029. * @type {number}
  20030. * @readonly
  20031. */
  20032. get unusedIndexCount() {
  20033. return this._maxIndexCount - this._nextIndexStart;
  20034. }
  20035. _initMatricesTexture() {
  20036. // layout (1 matrix = 4 pixels)
  20037. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20038. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20039. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20040. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20041. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20042. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20043. size = Math.ceil( size / 4 ) * 4;
  20044. size = Math.max( size, 4 );
  20045. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20046. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20047. this._matricesTexture = matricesTexture;
  20048. }
  20049. _initIndirectTexture() {
  20050. let size = Math.sqrt( this._maxInstanceCount );
  20051. size = Math.ceil( size );
  20052. const indirectArray = new Uint32Array( size * size );
  20053. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20054. this._indirectTexture = indirectTexture;
  20055. }
  20056. _initColorsTexture() {
  20057. let size = Math.sqrt( this._maxInstanceCount );
  20058. size = Math.ceil( size );
  20059. // 4 floats per RGBA pixel initialized to white
  20060. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20061. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20062. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20063. this._colorsTexture = colorsTexture;
  20064. }
  20065. _initializeGeometry( reference ) {
  20066. const geometry = this.geometry;
  20067. const maxVertexCount = this._maxVertexCount;
  20068. const maxIndexCount = this._maxIndexCount;
  20069. if ( this._geometryInitialized === false ) {
  20070. for ( const attributeName in reference.attributes ) {
  20071. const srcAttribute = reference.getAttribute( attributeName );
  20072. const { array, itemSize, normalized } = srcAttribute;
  20073. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20074. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20075. geometry.setAttribute( attributeName, dstAttribute );
  20076. }
  20077. if ( reference.getIndex() !== null ) {
  20078. // Reserve last u16 index for primitive restart.
  20079. const indexArray = maxVertexCount > 65535
  20080. ? new Uint32Array( maxIndexCount )
  20081. : new Uint16Array( maxIndexCount );
  20082. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20083. }
  20084. this._geometryInitialized = true;
  20085. }
  20086. }
  20087. // Make sure the geometry is compatible with the existing combined geometry attributes
  20088. _validateGeometry( geometry ) {
  20089. // check to ensure the geometries are using consistent attributes and indices
  20090. const batchGeometry = this.geometry;
  20091. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20092. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20093. }
  20094. for ( const attributeName in batchGeometry.attributes ) {
  20095. if ( ! geometry.hasAttribute( attributeName ) ) {
  20096. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20097. }
  20098. const srcAttribute = geometry.getAttribute( attributeName );
  20099. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20100. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20101. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20102. }
  20103. }
  20104. }
  20105. /**
  20106. * Validates the instance defined by the given ID.
  20107. *
  20108. * @param {number} instanceId - The instance to validate.
  20109. */
  20110. validateInstanceId( instanceId ) {
  20111. const instanceInfo = this._instanceInfo;
  20112. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20113. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20114. }
  20115. }
  20116. /**
  20117. * Validates the geometry defined by the given ID.
  20118. *
  20119. * @param {number} geometryId - The geometry to validate.
  20120. */
  20121. validateGeometryId( geometryId ) {
  20122. const geometryInfoList = this._geometryInfo;
  20123. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20124. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20125. }
  20126. }
  20127. /**
  20128. * Takes a sort a function that is run before render. The function takes a list of instances to
  20129. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20130. *
  20131. * @param {Function} func - The custom sort function.
  20132. * @return {BatchedMesh} A reference to this batched mesh.
  20133. */
  20134. setCustomSort( func ) {
  20135. this.customSort = func;
  20136. return this;
  20137. }
  20138. /**
  20139. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20140. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20141. * otherwise they are `null`.
  20142. */
  20143. computeBoundingBox() {
  20144. if ( this.boundingBox === null ) {
  20145. this.boundingBox = new Box3();
  20146. }
  20147. const boundingBox = this.boundingBox;
  20148. const instanceInfo = this._instanceInfo;
  20149. boundingBox.makeEmpty();
  20150. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20151. if ( instanceInfo[ i ].active === false ) continue;
  20152. const geometryId = instanceInfo[ i ].geometryIndex;
  20153. this.getMatrixAt( i, _matrix$1 );
  20154. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20155. boundingBox.union( _box$1 );
  20156. }
  20157. }
  20158. /**
  20159. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20160. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20161. * otherwise they are `null`.
  20162. */
  20163. computeBoundingSphere() {
  20164. if ( this.boundingSphere === null ) {
  20165. this.boundingSphere = new Sphere();
  20166. }
  20167. const boundingSphere = this.boundingSphere;
  20168. const instanceInfo = this._instanceInfo;
  20169. boundingSphere.makeEmpty();
  20170. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20171. if ( instanceInfo[ i ].active === false ) continue;
  20172. const geometryId = instanceInfo[ i ].geometryIndex;
  20173. this.getMatrixAt( i, _matrix$1 );
  20174. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20175. boundingSphere.union( _sphere$2 );
  20176. }
  20177. }
  20178. /**
  20179. * Adds a new instance to the batch using the geometry of the given ID and returns
  20180. * a new id referring to the new instance to be used by other functions.
  20181. *
  20182. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20183. * @return {number} The instance ID.
  20184. */
  20185. addInstance( geometryId ) {
  20186. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20187. // ensure we're not over geometry
  20188. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20189. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20190. }
  20191. const instanceInfo = {
  20192. visible: true,
  20193. active: true,
  20194. geometryIndex: geometryId,
  20195. };
  20196. let drawId = null;
  20197. // Prioritize using previously freed instance ids
  20198. if ( this._availableInstanceIds.length > 0 ) {
  20199. this._availableInstanceIds.sort( ascIdSort );
  20200. drawId = this._availableInstanceIds.shift();
  20201. this._instanceInfo[ drawId ] = instanceInfo;
  20202. } else {
  20203. drawId = this._instanceInfo.length;
  20204. this._instanceInfo.push( instanceInfo );
  20205. }
  20206. const matricesTexture = this._matricesTexture;
  20207. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20208. matricesTexture.needsUpdate = true;
  20209. const colorsTexture = this._colorsTexture;
  20210. if ( colorsTexture ) {
  20211. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20212. colorsTexture.needsUpdate = true;
  20213. }
  20214. this._visibilityChanged = true;
  20215. return drawId;
  20216. }
  20217. /**
  20218. * Adds the given geometry to the batch and returns the associated
  20219. * geometry id referring to it to be used in other functions.
  20220. *
  20221. * @param {BufferGeometry} geometry - The geometry to add.
  20222. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20223. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20224. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20225. * Defaults to the length of the given geometry vertex buffer.
  20226. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20227. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20228. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20229. * the length of the given geometry index buffer.
  20230. * @return {number} The geometry ID.
  20231. */
  20232. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20233. this._initializeGeometry( geometry );
  20234. this._validateGeometry( geometry );
  20235. const geometryInfo = {
  20236. // geometry information
  20237. vertexStart: -1,
  20238. vertexCount: -1,
  20239. reservedVertexCount: -1,
  20240. indexStart: -1,
  20241. indexCount: -1,
  20242. reservedIndexCount: -1,
  20243. // draw range information
  20244. start: -1,
  20245. count: -1,
  20246. // state
  20247. boundingBox: null,
  20248. boundingSphere: null,
  20249. active: true,
  20250. };
  20251. const geometryInfoList = this._geometryInfo;
  20252. geometryInfo.vertexStart = this._nextVertexStart;
  20253. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20254. const index = geometry.getIndex();
  20255. const hasIndex = index !== null;
  20256. if ( hasIndex ) {
  20257. geometryInfo.indexStart = this._nextIndexStart;
  20258. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20259. }
  20260. if (
  20261. geometryInfo.indexStart !== -1 &&
  20262. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20263. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20264. ) {
  20265. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20266. }
  20267. // update id
  20268. let geometryId;
  20269. if ( this._availableGeometryIds.length > 0 ) {
  20270. this._availableGeometryIds.sort( ascIdSort );
  20271. geometryId = this._availableGeometryIds.shift();
  20272. geometryInfoList[ geometryId ] = geometryInfo;
  20273. } else {
  20274. geometryId = this._geometryCount;
  20275. this._geometryCount ++;
  20276. geometryInfoList.push( geometryInfo );
  20277. }
  20278. // update the geometry
  20279. this.setGeometryAt( geometryId, geometry );
  20280. // increment the next geometry position
  20281. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20282. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20283. return geometryId;
  20284. }
  20285. /**
  20286. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20287. * is not enough space reserved for geometry. Calling this will change all instances that are
  20288. * rendering that geometry.
  20289. *
  20290. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20291. * @param {BufferGeometry} geometry - The new geometry.
  20292. * @return {number} The geometry ID.
  20293. */
  20294. setGeometryAt( geometryId, geometry ) {
  20295. if ( geometryId >= this._geometryCount ) {
  20296. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20297. }
  20298. this._validateGeometry( geometry );
  20299. const batchGeometry = this.geometry;
  20300. const hasIndex = batchGeometry.getIndex() !== null;
  20301. const dstIndex = batchGeometry.getIndex();
  20302. const srcIndex = geometry.getIndex();
  20303. const geometryInfo = this._geometryInfo[ geometryId ];
  20304. if (
  20305. hasIndex &&
  20306. srcIndex.count > geometryInfo.reservedIndexCount ||
  20307. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20308. ) {
  20309. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20310. }
  20311. // copy geometry buffer data over
  20312. const vertexStart = geometryInfo.vertexStart;
  20313. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20314. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20315. for ( const attributeName in batchGeometry.attributes ) {
  20316. // copy attribute data
  20317. const srcAttribute = geometry.getAttribute( attributeName );
  20318. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20319. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20320. // fill the rest in with zeroes
  20321. const itemSize = srcAttribute.itemSize;
  20322. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20323. const index = vertexStart + i;
  20324. for ( let c = 0; c < itemSize; c ++ ) {
  20325. dstAttribute.setComponent( index, c, 0 );
  20326. }
  20327. }
  20328. dstAttribute.needsUpdate = true;
  20329. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20330. }
  20331. // copy index
  20332. if ( hasIndex ) {
  20333. const indexStart = geometryInfo.indexStart;
  20334. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20335. geometryInfo.indexCount = geometry.getIndex().count;
  20336. // copy index data over
  20337. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20338. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20339. }
  20340. // fill the rest in with zeroes
  20341. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20342. dstIndex.setX( indexStart + i, vertexStart );
  20343. }
  20344. dstIndex.needsUpdate = true;
  20345. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20346. }
  20347. // update the draw range
  20348. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20349. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20350. // store the bounding boxes
  20351. geometryInfo.boundingBox = null;
  20352. if ( geometry.boundingBox !== null ) {
  20353. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20354. }
  20355. geometryInfo.boundingSphere = null;
  20356. if ( geometry.boundingSphere !== null ) {
  20357. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20358. }
  20359. this._visibilityChanged = true;
  20360. return geometryId;
  20361. }
  20362. /**
  20363. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20364. * this geometry will also be removed as a side effect.
  20365. *
  20366. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20367. * @return {BatchedMesh} A reference to this batched mesh.
  20368. */
  20369. deleteGeometry( geometryId ) {
  20370. const geometryInfoList = this._geometryInfo;
  20371. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20372. return this;
  20373. }
  20374. // delete any instances associated with this geometry
  20375. const instanceInfo = this._instanceInfo;
  20376. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20377. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20378. this.deleteInstance( i );
  20379. }
  20380. }
  20381. geometryInfoList[ geometryId ].active = false;
  20382. this._availableGeometryIds.push( geometryId );
  20383. this._visibilityChanged = true;
  20384. return this;
  20385. }
  20386. /**
  20387. * Deletes an existing instance from the batch using the given ID.
  20388. *
  20389. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20390. * @return {BatchedMesh} A reference to this batched mesh.
  20391. */
  20392. deleteInstance( instanceId ) {
  20393. this.validateInstanceId( instanceId );
  20394. this._instanceInfo[ instanceId ].active = false;
  20395. this._availableInstanceIds.push( instanceId );
  20396. this._visibilityChanged = true;
  20397. return this;
  20398. }
  20399. /**
  20400. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20401. * previously deleted geometry, freeing up space to add new geometry.
  20402. *
  20403. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20404. * @return {BatchedMesh} A reference to this batched mesh.
  20405. */
  20406. optimize() {
  20407. // track the next indices to copy data to
  20408. let nextVertexStart = 0;
  20409. let nextIndexStart = 0;
  20410. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20411. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20412. const geometryInfoList = this._geometryInfo;
  20413. const indices = geometryInfoList
  20414. .map( ( e, i ) => i )
  20415. .sort( ( a, b ) => {
  20416. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20417. } );
  20418. const geometry = this.geometry;
  20419. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20420. // if a geometry range is inactive then don't copy anything
  20421. const index = indices[ i ];
  20422. const geometryInfo = geometryInfoList[ index ];
  20423. if ( geometryInfo.active === false ) {
  20424. continue;
  20425. }
  20426. // if a geometry contains an index buffer then shift it, as well
  20427. if ( geometry.index !== null ) {
  20428. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20429. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20430. const index = geometry.index;
  20431. const array = index.array;
  20432. // shift the index pointers based on how the vertex data will shift
  20433. // adjusting the index must happen first so the original vertex start value is available
  20434. const elementDelta = nextVertexStart - vertexStart;
  20435. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20436. array[ j ] = array[ j ] + elementDelta;
  20437. }
  20438. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20439. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20440. geometryInfo.indexStart = nextIndexStart;
  20441. }
  20442. nextIndexStart += geometryInfo.reservedIndexCount;
  20443. }
  20444. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20445. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20446. const { vertexStart, reservedVertexCount } = geometryInfo;
  20447. const attributes = geometry.attributes;
  20448. for ( const key in attributes ) {
  20449. const attribute = attributes[ key ];
  20450. const { array, itemSize } = attribute;
  20451. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20452. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20453. }
  20454. geometryInfo.vertexStart = nextVertexStart;
  20455. }
  20456. nextVertexStart += geometryInfo.reservedVertexCount;
  20457. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20458. // step the next geometry points to the shifted position
  20459. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20460. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20461. }
  20462. return this;
  20463. }
  20464. /**
  20465. * Returns the bounding box for the given geometry.
  20466. *
  20467. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20468. * @param {Box3} target - The target object that is used to store the method's result.
  20469. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20470. */
  20471. getBoundingBoxAt( geometryId, target ) {
  20472. if ( geometryId >= this._geometryCount ) {
  20473. return null;
  20474. }
  20475. // compute bounding box
  20476. const geometry = this.geometry;
  20477. const geometryInfo = this._geometryInfo[ geometryId ];
  20478. if ( geometryInfo.boundingBox === null ) {
  20479. const box = new Box3();
  20480. const index = geometry.index;
  20481. const position = geometry.attributes.position;
  20482. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20483. let iv = i;
  20484. if ( index ) {
  20485. iv = index.getX( iv );
  20486. }
  20487. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20488. }
  20489. geometryInfo.boundingBox = box;
  20490. }
  20491. target.copy( geometryInfo.boundingBox );
  20492. return target;
  20493. }
  20494. /**
  20495. * Returns the bounding sphere for the given geometry.
  20496. *
  20497. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20498. * @param {Sphere} target - The target object that is used to store the method's result.
  20499. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20500. */
  20501. getBoundingSphereAt( geometryId, target ) {
  20502. if ( geometryId >= this._geometryCount ) {
  20503. return null;
  20504. }
  20505. // compute bounding sphere
  20506. const geometry = this.geometry;
  20507. const geometryInfo = this._geometryInfo[ geometryId ];
  20508. if ( geometryInfo.boundingSphere === null ) {
  20509. const sphere = new Sphere();
  20510. this.getBoundingBoxAt( geometryId, _box$1 );
  20511. _box$1.getCenter( sphere.center );
  20512. const index = geometry.index;
  20513. const position = geometry.attributes.position;
  20514. let maxRadiusSq = 0;
  20515. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20516. let iv = i;
  20517. if ( index ) {
  20518. iv = index.getX( iv );
  20519. }
  20520. _vector$5.fromBufferAttribute( position, iv );
  20521. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20522. }
  20523. sphere.radius = Math.sqrt( maxRadiusSq );
  20524. geometryInfo.boundingSphere = sphere;
  20525. }
  20526. target.copy( geometryInfo.boundingSphere );
  20527. return target;
  20528. }
  20529. /**
  20530. * Sets the given local transformation matrix to the defined instance.
  20531. * Negatively scaled matrices are not supported.
  20532. *
  20533. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20534. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20535. * @return {BatchedMesh} A reference to this batched mesh.
  20536. */
  20537. setMatrixAt( instanceId, matrix ) {
  20538. this.validateInstanceId( instanceId );
  20539. const matricesTexture = this._matricesTexture;
  20540. const matricesArray = this._matricesTexture.image.data;
  20541. matrix.toArray( matricesArray, instanceId * 16 );
  20542. matricesTexture.needsUpdate = true;
  20543. return this;
  20544. }
  20545. /**
  20546. * Returns the local transformation matrix of the defined instance.
  20547. *
  20548. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20549. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20550. * @return {Matrix4} The instance's local transformation matrix.
  20551. */
  20552. getMatrixAt( instanceId, matrix ) {
  20553. this.validateInstanceId( instanceId );
  20554. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20555. }
  20556. /**
  20557. * Sets the given color to the defined instance.
  20558. *
  20559. * @param {number} instanceId - The ID of an instance to set the color of.
  20560. * @param {Color} color - The color to set the instance to.
  20561. * @return {BatchedMesh} A reference to this batched mesh.
  20562. */
  20563. setColorAt( instanceId, color ) {
  20564. this.validateInstanceId( instanceId );
  20565. if ( this._colorsTexture === null ) {
  20566. this._initColorsTexture();
  20567. }
  20568. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20569. this._colorsTexture.needsUpdate = true;
  20570. return this;
  20571. }
  20572. /**
  20573. * Returns the color of the defined instance.
  20574. *
  20575. * @param {number} instanceId - The ID of an instance to get the color of.
  20576. * @param {Color} color - The target object that is used to store the method's result.
  20577. * @return {Color} The instance's color.
  20578. */
  20579. getColorAt( instanceId, color ) {
  20580. this.validateInstanceId( instanceId );
  20581. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20582. }
  20583. /**
  20584. * Sets the visibility of the instance.
  20585. *
  20586. * @param {number} instanceId - The id of the instance to set the visibility of.
  20587. * @param {boolean} visible - Whether the instance is visible or not.
  20588. * @return {BatchedMesh} A reference to this batched mesh.
  20589. */
  20590. setVisibleAt( instanceId, visible ) {
  20591. this.validateInstanceId( instanceId );
  20592. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20593. return this;
  20594. }
  20595. this._instanceInfo[ instanceId ].visible = visible;
  20596. this._visibilityChanged = true;
  20597. return this;
  20598. }
  20599. /**
  20600. * Returns the visibility state of the defined instance.
  20601. *
  20602. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20603. * @return {boolean} Whether the instance is visible or not.
  20604. */
  20605. getVisibleAt( instanceId ) {
  20606. this.validateInstanceId( instanceId );
  20607. return this._instanceInfo[ instanceId ].visible;
  20608. }
  20609. /**
  20610. * Sets the geometry ID of the instance at the given index.
  20611. *
  20612. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20613. * @param {number} geometryId - The geometry ID to be use by the instance.
  20614. * @return {BatchedMesh} A reference to this batched mesh.
  20615. */
  20616. setGeometryIdAt( instanceId, geometryId ) {
  20617. this.validateInstanceId( instanceId );
  20618. this.validateGeometryId( geometryId );
  20619. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20620. return this;
  20621. }
  20622. /**
  20623. * Returns the geometry ID of the defined instance.
  20624. *
  20625. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20626. * @return {number} The instance's geometry ID.
  20627. */
  20628. getGeometryIdAt( instanceId ) {
  20629. this.validateInstanceId( instanceId );
  20630. return this._instanceInfo[ instanceId ].geometryIndex;
  20631. }
  20632. /**
  20633. * Get the range representing the subset of triangles related to the attached geometry,
  20634. * indicating the starting offset and count, or `null` if invalid.
  20635. *
  20636. * @param {number} geometryId - The id of the geometry to get the range of.
  20637. * @param {Object} [target] - The target object that is used to store the method's result.
  20638. * @return {{
  20639. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20640. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20641. * start:number,count:number
  20642. * }} The result object with range data.
  20643. */
  20644. getGeometryRangeAt( geometryId, target = {} ) {
  20645. this.validateGeometryId( geometryId );
  20646. const geometryInfo = this._geometryInfo[ geometryId ];
  20647. target.vertexStart = geometryInfo.vertexStart;
  20648. target.vertexCount = geometryInfo.vertexCount;
  20649. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20650. target.indexStart = geometryInfo.indexStart;
  20651. target.indexCount = geometryInfo.indexCount;
  20652. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20653. target.start = geometryInfo.start;
  20654. target.count = geometryInfo.count;
  20655. return target;
  20656. }
  20657. /**
  20658. * Resizes the necessary buffers to support the provided number of instances.
  20659. * If the provided arguments shrink the number of instances but there are not enough
  20660. * unused Ids at the end of the list then an error is thrown.
  20661. *
  20662. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20663. */
  20664. setInstanceCount( maxInstanceCount ) {
  20665. // shrink the available instances as much as possible
  20666. const availableInstanceIds = this._availableInstanceIds;
  20667. const instanceInfo = this._instanceInfo;
  20668. availableInstanceIds.sort( ascIdSort );
  20669. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20670. instanceInfo.pop();
  20671. availableInstanceIds.pop();
  20672. }
  20673. // throw an error if it can't be shrunk to the desired size
  20674. if ( maxInstanceCount < instanceInfo.length ) {
  20675. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20676. }
  20677. // copy the multi draw counts
  20678. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20679. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20680. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20681. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20682. this._multiDrawCounts = multiDrawCounts;
  20683. this._multiDrawStarts = multiDrawStarts;
  20684. this._maxInstanceCount = maxInstanceCount;
  20685. // update texture data for instance sampling
  20686. const indirectTexture = this._indirectTexture;
  20687. const matricesTexture = this._matricesTexture;
  20688. const colorsTexture = this._colorsTexture;
  20689. indirectTexture.dispose();
  20690. this._initIndirectTexture();
  20691. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20692. matricesTexture.dispose();
  20693. this._initMatricesTexture();
  20694. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20695. if ( colorsTexture ) {
  20696. colorsTexture.dispose();
  20697. this._initColorsTexture();
  20698. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20699. }
  20700. }
  20701. /**
  20702. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20703. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20704. * end of the geometry attributes then an error is thrown.
  20705. *
  20706. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20707. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20708. */
  20709. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20710. // Check if we can shrink to the requested vertex attribute size
  20711. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20712. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20713. if ( requiredVertexLength > maxVertexCount ) {
  20714. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20715. }
  20716. // Check if we can shrink to the requested index attribute size
  20717. if ( this.geometry.index ) {
  20718. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20719. if ( requiredIndexLength > maxIndexCount ) {
  20720. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20721. }
  20722. }
  20723. //
  20724. // dispose of the previous geometry
  20725. const oldGeometry = this.geometry;
  20726. oldGeometry.dispose();
  20727. // recreate the geometry needed based on the previous variant
  20728. this._maxVertexCount = maxVertexCount;
  20729. this._maxIndexCount = maxIndexCount;
  20730. if ( this._geometryInitialized ) {
  20731. this._geometryInitialized = false;
  20732. this.geometry = new BufferGeometry();
  20733. this._initializeGeometry( oldGeometry );
  20734. }
  20735. // copy data from the previous geometry
  20736. const geometry = this.geometry;
  20737. if ( oldGeometry.index ) {
  20738. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20739. }
  20740. for ( const key in oldGeometry.attributes ) {
  20741. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20742. }
  20743. }
  20744. raycast( raycaster, intersects ) {
  20745. const instanceInfo = this._instanceInfo;
  20746. const geometryInfoList = this._geometryInfo;
  20747. const matrixWorld = this.matrixWorld;
  20748. const batchGeometry = this.geometry;
  20749. // iterate over each geometry
  20750. _mesh.material = this.material;
  20751. _mesh.geometry.index = batchGeometry.index;
  20752. _mesh.geometry.attributes = batchGeometry.attributes;
  20753. if ( _mesh.geometry.boundingBox === null ) {
  20754. _mesh.geometry.boundingBox = new Box3();
  20755. }
  20756. if ( _mesh.geometry.boundingSphere === null ) {
  20757. _mesh.geometry.boundingSphere = new Sphere();
  20758. }
  20759. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20760. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20761. continue;
  20762. }
  20763. const geometryId = instanceInfo[ i ].geometryIndex;
  20764. const geometryInfo = geometryInfoList[ geometryId ];
  20765. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20766. // get the intersects
  20767. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20768. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20769. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20770. _mesh.raycast( raycaster, _batchIntersects );
  20771. // add batch id to the intersects
  20772. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20773. const intersect = _batchIntersects[ j ];
  20774. intersect.object = this;
  20775. intersect.batchId = i;
  20776. intersects.push( intersect );
  20777. }
  20778. _batchIntersects.length = 0;
  20779. }
  20780. _mesh.material = null;
  20781. _mesh.geometry.index = null;
  20782. _mesh.geometry.attributes = {};
  20783. _mesh.geometry.setDrawRange( 0, Infinity );
  20784. }
  20785. copy( source ) {
  20786. super.copy( source );
  20787. this.geometry = source.geometry.clone();
  20788. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20789. this.sortObjects = source.sortObjects;
  20790. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20791. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20792. this._geometryInfo = source._geometryInfo.map( info => ( {
  20793. ...info,
  20794. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20795. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20796. } ) );
  20797. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20798. this._availableInstanceIds = source._availableInstanceIds.slice();
  20799. this._availableGeometryIds = source._availableGeometryIds.slice();
  20800. this._nextIndexStart = source._nextIndexStart;
  20801. this._nextVertexStart = source._nextVertexStart;
  20802. this._geometryCount = source._geometryCount;
  20803. this._maxInstanceCount = source._maxInstanceCount;
  20804. this._maxVertexCount = source._maxVertexCount;
  20805. this._maxIndexCount = source._maxIndexCount;
  20806. this._geometryInitialized = source._geometryInitialized;
  20807. this._multiDrawCounts = source._multiDrawCounts.slice();
  20808. this._multiDrawStarts = source._multiDrawStarts.slice();
  20809. this._indirectTexture = source._indirectTexture.clone();
  20810. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20811. this._matricesTexture = source._matricesTexture.clone();
  20812. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20813. if ( this._colorsTexture !== null ) {
  20814. this._colorsTexture = source._colorsTexture.clone();
  20815. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20816. }
  20817. return this;
  20818. }
  20819. /**
  20820. * Frees the GPU-related resources allocated by this instance. Call this
  20821. * method whenever this instance is no longer used in your app.
  20822. */
  20823. dispose() {
  20824. // Assuming the geometry is not shared with other meshes
  20825. this.geometry.dispose();
  20826. this._matricesTexture.dispose();
  20827. this._matricesTexture = null;
  20828. this._indirectTexture.dispose();
  20829. this._indirectTexture = null;
  20830. if ( this._colorsTexture !== null ) {
  20831. this._colorsTexture.dispose();
  20832. this._colorsTexture = null;
  20833. }
  20834. }
  20835. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20836. // if visibility has not changed and frustum culling and object sorting is not required
  20837. // then skip iterating over all items
  20838. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20839. return;
  20840. }
  20841. // the indexed version of the multi draw function requires specifying the start
  20842. // offset in bytes.
  20843. const index = geometry.getIndex();
  20844. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20845. const instanceInfo = this._instanceInfo;
  20846. const multiDrawStarts = this._multiDrawStarts;
  20847. const multiDrawCounts = this._multiDrawCounts;
  20848. const geometryInfoList = this._geometryInfo;
  20849. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20850. const indirectTexture = this._indirectTexture;
  20851. const indirectArray = indirectTexture.image.data;
  20852. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20853. // prepare the frustum in the local frame
  20854. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20855. _matrix$1
  20856. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20857. .multiply( this.matrixWorld );
  20858. _frustum.setFromProjectionMatrix(
  20859. _matrix$1,
  20860. renderer.coordinateSystem
  20861. );
  20862. }
  20863. let multiDrawCount = 0;
  20864. if ( this.sortObjects ) {
  20865. // get the camera position in the local frame
  20866. _matrix$1.copy( this.matrixWorld ).invert();
  20867. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20868. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20869. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20870. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20871. const geometryId = instanceInfo[ i ].geometryIndex;
  20872. // get the bounds in world space
  20873. this.getMatrixAt( i, _matrix$1 );
  20874. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20875. // determine whether the batched geometry is within the frustum
  20876. let culled = false;
  20877. if ( perObjectFrustumCulled ) {
  20878. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20879. }
  20880. if ( ! culled ) {
  20881. // get the distance from camera used for sorting
  20882. const geometryInfo = geometryInfoList[ geometryId ];
  20883. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20884. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20885. }
  20886. }
  20887. }
  20888. // Sort the draw ranges and prep for rendering
  20889. const list = _renderList.list;
  20890. const customSort = this.customSort;
  20891. if ( customSort === null ) {
  20892. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20893. } else {
  20894. customSort.call( this, list, camera );
  20895. }
  20896. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20897. const item = list[ i ];
  20898. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20899. multiDrawCounts[ multiDrawCount ] = item.count;
  20900. indirectArray[ multiDrawCount ] = item.index;
  20901. multiDrawCount ++;
  20902. }
  20903. _renderList.reset();
  20904. } else {
  20905. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20906. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20907. const geometryId = instanceInfo[ i ].geometryIndex;
  20908. // determine whether the batched geometry is within the frustum
  20909. let culled = false;
  20910. if ( perObjectFrustumCulled ) {
  20911. // get the bounds in world space
  20912. this.getMatrixAt( i, _matrix$1 );
  20913. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20914. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20915. }
  20916. if ( ! culled ) {
  20917. const geometryInfo = geometryInfoList[ geometryId ];
  20918. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20919. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20920. indirectArray[ multiDrawCount ] = i;
  20921. multiDrawCount ++;
  20922. }
  20923. }
  20924. }
  20925. }
  20926. indirectTexture.needsUpdate = true;
  20927. this._multiDrawCount = multiDrawCount;
  20928. this._visibilityChanged = false;
  20929. }
  20930. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20931. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20932. }
  20933. }
  20934. /**
  20935. * A material for rendering line primitives.
  20936. *
  20937. * Materials define the appearance of renderable 3D objects.
  20938. *
  20939. * ```js
  20940. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  20941. * ```
  20942. *
  20943. * @augments Material
  20944. */
  20945. class LineBasicMaterial extends Material {
  20946. /**
  20947. * Constructs a new line basic material.
  20948. *
  20949. * @param {Object} [parameters] - An object with one or more properties
  20950. * defining the material's appearance. Any property of the material
  20951. * (including any property from inherited materials) can be passed
  20952. * in here. Color values can be passed any type of value accepted
  20953. * by {@link Color#set}.
  20954. */
  20955. constructor( parameters ) {
  20956. super();
  20957. /**
  20958. * This flag can be used for type testing.
  20959. *
  20960. * @type {boolean}
  20961. * @readonly
  20962. * @default true
  20963. */
  20964. this.isLineBasicMaterial = true;
  20965. this.type = 'LineBasicMaterial';
  20966. /**
  20967. * Color of the material.
  20968. *
  20969. * @type {Color}
  20970. * @default (1,1,1)
  20971. */
  20972. this.color = new Color( 0xffffff );
  20973. /**
  20974. * Sets the color of the lines using data from a texture. The texture map
  20975. * color is modulated by the diffuse `color`.
  20976. *
  20977. * @type {?Texture}
  20978. * @default null
  20979. */
  20980. this.map = null;
  20981. /**
  20982. * Controls line thickness or lines.
  20983. *
  20984. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  20985. * ignore this setting and always render line primitives with a
  20986. * width of one pixel.
  20987. *
  20988. * @type {number}
  20989. * @default 1
  20990. */
  20991. this.linewidth = 1;
  20992. /**
  20993. * Defines appearance of line ends.
  20994. *
  20995. * Can only be used with {@link SVGRenderer}.
  20996. *
  20997. * @type {('butt'|'round'|'square')}
  20998. * @default 'round'
  20999. */
  21000. this.linecap = 'round';
  21001. /**
  21002. * Defines appearance of line joints.
  21003. *
  21004. * Can only be used with {@link SVGRenderer}.
  21005. *
  21006. * @type {('round'|'bevel'|'miter')}
  21007. * @default 'round'
  21008. */
  21009. this.linejoin = 'round';
  21010. /**
  21011. * Whether the material is affected by fog or not.
  21012. *
  21013. * @type {boolean}
  21014. * @default true
  21015. */
  21016. this.fog = true;
  21017. this.setValues( parameters );
  21018. }
  21019. copy( source ) {
  21020. super.copy( source );
  21021. this.color.copy( source.color );
  21022. this.map = source.map;
  21023. this.linewidth = source.linewidth;
  21024. this.linecap = source.linecap;
  21025. this.linejoin = source.linejoin;
  21026. this.fog = source.fog;
  21027. return this;
  21028. }
  21029. }
  21030. const _vStart = /*@__PURE__*/ new Vector3();
  21031. const _vEnd = /*@__PURE__*/ new Vector3();
  21032. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21033. const _ray$1 = /*@__PURE__*/ new Ray();
  21034. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21035. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21036. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21037. /**
  21038. * A continuous line. The line are rendered by connecting consecutive
  21039. * vertices with straight lines.
  21040. *
  21041. * ```js
  21042. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21043. *
  21044. * const points = [];
  21045. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21046. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21047. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21048. *
  21049. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21050. *
  21051. * const line = new THREE.Line( geometry, material );
  21052. * scene.add( line );
  21053. * ```
  21054. *
  21055. * @augments Object3D
  21056. */
  21057. class Line extends Object3D {
  21058. /**
  21059. * Constructs a new line.
  21060. *
  21061. * @param {BufferGeometry} [geometry] - The line geometry.
  21062. * @param {Material|Array<Material>} [material] - The line material.
  21063. */
  21064. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21065. super();
  21066. /**
  21067. * This flag can be used for type testing.
  21068. *
  21069. * @type {boolean}
  21070. * @readonly
  21071. * @default true
  21072. */
  21073. this.isLine = true;
  21074. this.type = 'Line';
  21075. /**
  21076. * The line geometry.
  21077. *
  21078. * @type {BufferGeometry}
  21079. */
  21080. this.geometry = geometry;
  21081. /**
  21082. * The line material.
  21083. *
  21084. * @type {Material|Array<Material>}
  21085. * @default LineBasicMaterial
  21086. */
  21087. this.material = material;
  21088. /**
  21089. * A dictionary representing the morph targets in the geometry. The key is the
  21090. * morph targets name, the value its attribute index. This member is `undefined`
  21091. * by default and only set when morph targets are detected in the geometry.
  21092. *
  21093. * @type {Object<String,number>|undefined}
  21094. * @default undefined
  21095. */
  21096. this.morphTargetDictionary = undefined;
  21097. /**
  21098. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21099. * is applied. This member is `undefined` by default and only set when morph targets are
  21100. * detected in the geometry.
  21101. *
  21102. * @type {Array<number>|undefined}
  21103. * @default undefined
  21104. */
  21105. this.morphTargetInfluences = undefined;
  21106. this.updateMorphTargets();
  21107. }
  21108. copy( source, recursive ) {
  21109. super.copy( source, recursive );
  21110. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21111. this.geometry = source.geometry;
  21112. return this;
  21113. }
  21114. /**
  21115. * Computes an array of distance values which are necessary for rendering dashed lines.
  21116. * For each vertex in the geometry, the method calculates the cumulative length from the
  21117. * current point to the very beginning of the line.
  21118. *
  21119. * @return {Line} A reference to this line.
  21120. */
  21121. computeLineDistances() {
  21122. const geometry = this.geometry;
  21123. // we assume non-indexed geometry
  21124. if ( geometry.index === null ) {
  21125. const positionAttribute = geometry.attributes.position;
  21126. const lineDistances = [ 0 ];
  21127. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21128. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21129. _vEnd.fromBufferAttribute( positionAttribute, i );
  21130. lineDistances[ i ] = lineDistances[ i - 1 ];
  21131. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21132. }
  21133. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21134. } else {
  21135. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21136. }
  21137. return this;
  21138. }
  21139. /**
  21140. * Computes intersection points between a casted ray and this line.
  21141. *
  21142. * @param {Raycaster} raycaster - The raycaster.
  21143. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21144. */
  21145. raycast( raycaster, intersects ) {
  21146. const geometry = this.geometry;
  21147. const matrixWorld = this.matrixWorld;
  21148. const threshold = raycaster.params.Line.threshold;
  21149. const drawRange = geometry.drawRange;
  21150. // Checking boundingSphere distance to ray
  21151. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21152. _sphere$1.copy( geometry.boundingSphere );
  21153. _sphere$1.applyMatrix4( matrixWorld );
  21154. _sphere$1.radius += threshold;
  21155. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21156. //
  21157. _inverseMatrix$1.copy( matrixWorld ).invert();
  21158. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21159. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21160. const localThresholdSq = localThreshold * localThreshold;
  21161. const step = this.isLineSegments ? 2 : 1;
  21162. const index = geometry.index;
  21163. const attributes = geometry.attributes;
  21164. const positionAttribute = attributes.position;
  21165. if ( index !== null ) {
  21166. const start = Math.max( 0, drawRange.start );
  21167. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21168. for ( let i = start, l = end - 1; i < l; i += step ) {
  21169. const a = index.getX( i );
  21170. const b = index.getX( i + 1 );
  21171. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21172. if ( intersect ) {
  21173. intersects.push( intersect );
  21174. }
  21175. }
  21176. if ( this.isLineLoop ) {
  21177. const a = index.getX( end - 1 );
  21178. const b = index.getX( start );
  21179. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21180. if ( intersect ) {
  21181. intersects.push( intersect );
  21182. }
  21183. }
  21184. } else {
  21185. const start = Math.max( 0, drawRange.start );
  21186. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21187. for ( let i = start, l = end - 1; i < l; i += step ) {
  21188. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21189. if ( intersect ) {
  21190. intersects.push( intersect );
  21191. }
  21192. }
  21193. if ( this.isLineLoop ) {
  21194. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21195. if ( intersect ) {
  21196. intersects.push( intersect );
  21197. }
  21198. }
  21199. }
  21200. }
  21201. /**
  21202. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21203. * to make sure existing morph targets can influence this 3D object.
  21204. */
  21205. updateMorphTargets() {
  21206. const geometry = this.geometry;
  21207. const morphAttributes = geometry.morphAttributes;
  21208. const keys = Object.keys( morphAttributes );
  21209. if ( keys.length > 0 ) {
  21210. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21211. if ( morphAttribute !== undefined ) {
  21212. this.morphTargetInfluences = [];
  21213. this.morphTargetDictionary = {};
  21214. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21215. const name = morphAttribute[ m ].name || String( m );
  21216. this.morphTargetInfluences.push( 0 );
  21217. this.morphTargetDictionary[ name ] = m;
  21218. }
  21219. }
  21220. }
  21221. }
  21222. }
  21223. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21224. const positionAttribute = object.geometry.attributes.position;
  21225. _vStart.fromBufferAttribute( positionAttribute, a );
  21226. _vEnd.fromBufferAttribute( positionAttribute, b );
  21227. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21228. if ( distSq > thresholdSq ) return;
  21229. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21230. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21231. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21232. return {
  21233. distance: distance,
  21234. // What do we want? intersection point on the ray or on the segment??
  21235. // point: raycaster.ray.at( distance ),
  21236. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21237. index: i,
  21238. face: null,
  21239. faceIndex: null,
  21240. barycoord: null,
  21241. object: object
  21242. };
  21243. }
  21244. const _start = /*@__PURE__*/ new Vector3();
  21245. const _end = /*@__PURE__*/ new Vector3();
  21246. /**
  21247. * A series of lines drawn between pairs of vertices.
  21248. *
  21249. * @augments Line
  21250. */
  21251. class LineSegments extends Line {
  21252. /**
  21253. * Constructs a new line segments.
  21254. *
  21255. * @param {BufferGeometry} [geometry] - The line geometry.
  21256. * @param {Material|Array<Material>} [material] - The line material.
  21257. */
  21258. constructor( geometry, material ) {
  21259. super( geometry, material );
  21260. /**
  21261. * This flag can be used for type testing.
  21262. *
  21263. * @type {boolean}
  21264. * @readonly
  21265. * @default true
  21266. */
  21267. this.isLineSegments = true;
  21268. this.type = 'LineSegments';
  21269. }
  21270. computeLineDistances() {
  21271. const geometry = this.geometry;
  21272. // we assume non-indexed geometry
  21273. if ( geometry.index === null ) {
  21274. const positionAttribute = geometry.attributes.position;
  21275. const lineDistances = [];
  21276. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21277. _start.fromBufferAttribute( positionAttribute, i );
  21278. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21279. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21280. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21281. }
  21282. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21283. } else {
  21284. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21285. }
  21286. return this;
  21287. }
  21288. }
  21289. /**
  21290. * A continuous line. This is nearly the same as {@link Line} the only difference
  21291. * is that the last vertex is connected with the first vertex in order to close
  21292. * the line to form a loop.
  21293. *
  21294. * @augments Line
  21295. */
  21296. class LineLoop extends Line {
  21297. /**
  21298. * Constructs a new line loop.
  21299. *
  21300. * @param {BufferGeometry} [geometry] - The line geometry.
  21301. * @param {Material|Array<Material>} [material] - The line material.
  21302. */
  21303. constructor( geometry, material ) {
  21304. super( geometry, material );
  21305. /**
  21306. * This flag can be used for type testing.
  21307. *
  21308. * @type {boolean}
  21309. * @readonly
  21310. * @default true
  21311. */
  21312. this.isLineLoop = true;
  21313. this.type = 'LineLoop';
  21314. }
  21315. }
  21316. /**
  21317. * A material for rendering point primitives.
  21318. *
  21319. * Materials define the appearance of renderable 3D objects.
  21320. *
  21321. * ```js
  21322. * const vertices = [];
  21323. *
  21324. * for ( let i = 0; i < 10000; i ++ ) {
  21325. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21326. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21327. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21328. *
  21329. * vertices.push( x, y, z );
  21330. * }
  21331. *
  21332. * const geometry = new THREE.BufferGeometry();
  21333. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21334. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21335. * const points = new THREE.Points( geometry, material );
  21336. * scene.add( points );
  21337. * ```
  21338. *
  21339. * @augments Material
  21340. */
  21341. class PointsMaterial extends Material {
  21342. /**
  21343. * Constructs a new points material.
  21344. *
  21345. * @param {Object} [parameters] - An object with one or more properties
  21346. * defining the material's appearance. Any property of the material
  21347. * (including any property from inherited materials) can be passed
  21348. * in here. Color values can be passed any type of value accepted
  21349. * by {@link Color#set}.
  21350. */
  21351. constructor( parameters ) {
  21352. super();
  21353. /**
  21354. * This flag can be used for type testing.
  21355. *
  21356. * @type {boolean}
  21357. * @readonly
  21358. * @default true
  21359. */
  21360. this.isPointsMaterial = true;
  21361. this.type = 'PointsMaterial';
  21362. /**
  21363. * Color of the material.
  21364. *
  21365. * @type {Color}
  21366. * @default (1,1,1)
  21367. */
  21368. this.color = new Color( 0xffffff );
  21369. /**
  21370. * The color map. May optionally include an alpha channel, typically combined
  21371. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21372. * color is modulated by the diffuse `color`.
  21373. *
  21374. * @type {?Texture}
  21375. * @default null
  21376. */
  21377. this.map = null;
  21378. /**
  21379. * The alpha map is a grayscale texture that controls the opacity across the
  21380. * surface (black: fully transparent; white: fully opaque).
  21381. *
  21382. * Only the color of the texture is used, ignoring the alpha channel if one
  21383. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21384. * when sampling this texture due to the extra bit of precision provided for
  21385. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21386. * luminance/alpha textures will also still work as expected.
  21387. *
  21388. * @type {?Texture}
  21389. * @default null
  21390. */
  21391. this.alphaMap = null;
  21392. /**
  21393. * Defines the size of the points in pixels.
  21394. *
  21395. * 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}.
  21396. *
  21397. * @type {number}
  21398. * @default 1
  21399. */
  21400. this.size = 1;
  21401. /**
  21402. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21403. *
  21404. * @type {boolean}
  21405. * @default true
  21406. */
  21407. this.sizeAttenuation = true;
  21408. /**
  21409. * Whether the material is affected by fog or not.
  21410. *
  21411. * @type {boolean}
  21412. * @default true
  21413. */
  21414. this.fog = true;
  21415. this.setValues( parameters );
  21416. }
  21417. copy( source ) {
  21418. super.copy( source );
  21419. this.color.copy( source.color );
  21420. this.map = source.map;
  21421. this.alphaMap = source.alphaMap;
  21422. this.size = source.size;
  21423. this.sizeAttenuation = source.sizeAttenuation;
  21424. this.fog = source.fog;
  21425. return this;
  21426. }
  21427. }
  21428. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21429. const _ray = /*@__PURE__*/ new Ray();
  21430. const _sphere = /*@__PURE__*/ new Sphere();
  21431. const _position$2 = /*@__PURE__*/ new Vector3();
  21432. /**
  21433. * A class for displaying points or point clouds.
  21434. *
  21435. * @augments Object3D
  21436. */
  21437. class Points extends Object3D {
  21438. /**
  21439. * Constructs a new point cloud.
  21440. *
  21441. * @param {BufferGeometry} [geometry] - The points geometry.
  21442. * @param {Material|Array<Material>} [material] - The points material.
  21443. */
  21444. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21445. super();
  21446. /**
  21447. * This flag can be used for type testing.
  21448. *
  21449. * @type {boolean}
  21450. * @readonly
  21451. * @default true
  21452. */
  21453. this.isPoints = true;
  21454. this.type = 'Points';
  21455. /**
  21456. * The points geometry.
  21457. *
  21458. * @type {BufferGeometry}
  21459. */
  21460. this.geometry = geometry;
  21461. /**
  21462. * The line material.
  21463. *
  21464. * @type {Material|Array<Material>}
  21465. * @default PointsMaterial
  21466. */
  21467. this.material = material;
  21468. /**
  21469. * A dictionary representing the morph targets in the geometry. The key is the
  21470. * morph targets name, the value its attribute index. This member is `undefined`
  21471. * by default and only set when morph targets are detected in the geometry.
  21472. *
  21473. * @type {Object<String,number>|undefined}
  21474. * @default undefined
  21475. */
  21476. this.morphTargetDictionary = undefined;
  21477. /**
  21478. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21479. * is applied. This member is `undefined` by default and only set when morph targets are
  21480. * detected in the geometry.
  21481. *
  21482. * @type {Array<number>|undefined}
  21483. * @default undefined
  21484. */
  21485. this.morphTargetInfluences = undefined;
  21486. this.updateMorphTargets();
  21487. }
  21488. copy( source, recursive ) {
  21489. super.copy( source, recursive );
  21490. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21491. this.geometry = source.geometry;
  21492. return this;
  21493. }
  21494. /**
  21495. * Computes intersection points between a casted ray and this point cloud.
  21496. *
  21497. * @param {Raycaster} raycaster - The raycaster.
  21498. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21499. */
  21500. raycast( raycaster, intersects ) {
  21501. const geometry = this.geometry;
  21502. const matrixWorld = this.matrixWorld;
  21503. const threshold = raycaster.params.Points.threshold;
  21504. const drawRange = geometry.drawRange;
  21505. // Checking boundingSphere distance to ray
  21506. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21507. _sphere.copy( geometry.boundingSphere );
  21508. _sphere.applyMatrix4( matrixWorld );
  21509. _sphere.radius += threshold;
  21510. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21511. //
  21512. _inverseMatrix.copy( matrixWorld ).invert();
  21513. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21514. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21515. const localThresholdSq = localThreshold * localThreshold;
  21516. const index = geometry.index;
  21517. const attributes = geometry.attributes;
  21518. const positionAttribute = attributes.position;
  21519. if ( index !== null ) {
  21520. const start = Math.max( 0, drawRange.start );
  21521. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21522. for ( let i = start, il = end; i < il; i ++ ) {
  21523. const a = index.getX( i );
  21524. _position$2.fromBufferAttribute( positionAttribute, a );
  21525. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21526. }
  21527. } else {
  21528. const start = Math.max( 0, drawRange.start );
  21529. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21530. for ( let i = start, l = end; i < l; i ++ ) {
  21531. _position$2.fromBufferAttribute( positionAttribute, i );
  21532. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21533. }
  21534. }
  21535. }
  21536. /**
  21537. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21538. * to make sure existing morph targets can influence this 3D object.
  21539. */
  21540. updateMorphTargets() {
  21541. const geometry = this.geometry;
  21542. const morphAttributes = geometry.morphAttributes;
  21543. const keys = Object.keys( morphAttributes );
  21544. if ( keys.length > 0 ) {
  21545. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21546. if ( morphAttribute !== undefined ) {
  21547. this.morphTargetInfluences = [];
  21548. this.morphTargetDictionary = {};
  21549. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21550. const name = morphAttribute[ m ].name || String( m );
  21551. this.morphTargetInfluences.push( 0 );
  21552. this.morphTargetDictionary[ name ] = m;
  21553. }
  21554. }
  21555. }
  21556. }
  21557. }
  21558. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21559. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21560. if ( rayPointDistanceSq < localThresholdSq ) {
  21561. const intersectPoint = new Vector3();
  21562. _ray.closestPointToPoint( point, intersectPoint );
  21563. intersectPoint.applyMatrix4( matrixWorld );
  21564. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21565. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21566. intersects.push( {
  21567. distance: distance,
  21568. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21569. point: intersectPoint,
  21570. index: index,
  21571. face: null,
  21572. faceIndex: null,
  21573. barycoord: null,
  21574. object: object
  21575. } );
  21576. }
  21577. }
  21578. /**
  21579. * A texture for use with a video.
  21580. *
  21581. * ```js
  21582. * // assuming you have created a HTML video element with id="video"
  21583. * const video = document.getElementById( 'video' );
  21584. * const texture = new THREE.VideoTexture( video );
  21585. * ```
  21586. *
  21587. * Note: After the initial use of a texture, its dimensions, format, and type
  21588. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21589. *
  21590. * @augments Texture
  21591. */
  21592. class VideoTexture extends Texture {
  21593. /**
  21594. * Constructs a new video texture.
  21595. *
  21596. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21597. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21598. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21599. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21600. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21601. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21602. * @param {number} [format=RGBAFormat] - The texture format.
  21603. * @param {number} [type=UnsignedByteType] - The texture type.
  21604. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21605. */
  21606. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21607. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21608. /**
  21609. * This flag can be used for type testing.
  21610. *
  21611. * @type {boolean}
  21612. * @readonly
  21613. * @default true
  21614. */
  21615. this.isVideoTexture = true;
  21616. /**
  21617. * Whether to generate mipmaps (if possible) for a texture.
  21618. *
  21619. * Overwritten and set to `false` by default.
  21620. *
  21621. * @type {boolean}
  21622. * @default false
  21623. */
  21624. this.generateMipmaps = false;
  21625. /**
  21626. * The video frame request callback identifier, which is a positive integer.
  21627. *
  21628. * Value of 0 represents no scheduled rVFC.
  21629. *
  21630. * @private
  21631. * @type {number}
  21632. */
  21633. this._requestVideoFrameCallbackId = 0;
  21634. const scope = this;
  21635. function updateVideo() {
  21636. scope.needsUpdate = true;
  21637. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21638. }
  21639. if ( 'requestVideoFrameCallback' in video ) {
  21640. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21641. }
  21642. }
  21643. clone() {
  21644. return new this.constructor( this.image ).copy( this );
  21645. }
  21646. /**
  21647. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21648. * to `true` every time a new frame is available.
  21649. *
  21650. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21651. */
  21652. update() {
  21653. const video = this.image;
  21654. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21655. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21656. this.needsUpdate = true;
  21657. }
  21658. }
  21659. /**
  21660. * @override
  21661. */
  21662. dispose() {
  21663. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21664. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21665. }
  21666. super.dispose();
  21667. }
  21668. }
  21669. /**
  21670. * This class can be used as an alternative way to define video data. Instead of using
  21671. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21672. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21673. * video frames are decoded with the WebCodecs API.
  21674. *
  21675. * ```js
  21676. * const texture = new THREE.VideoFrameTexture();
  21677. * texture.setFrame( frame );
  21678. * ```
  21679. *
  21680. * @augments VideoTexture
  21681. */
  21682. class VideoFrameTexture extends VideoTexture {
  21683. /**
  21684. * Constructs a new video frame texture.
  21685. *
  21686. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21687. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21688. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21689. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21690. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21691. * @param {number} [format=RGBAFormat] - The texture format.
  21692. * @param {number} [type=UnsignedByteType] - The texture type.
  21693. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21694. */
  21695. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21696. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21697. /**
  21698. * This flag can be used for type testing.
  21699. *
  21700. * @type {boolean}
  21701. * @readonly
  21702. * @default true
  21703. */
  21704. this.isVideoFrameTexture = true;
  21705. }
  21706. /**
  21707. * This method overwritten with an empty implementation since
  21708. * this type of texture is updated via `setFrame()`.
  21709. */
  21710. update() {}
  21711. clone() {
  21712. return new this.constructor().copy( this ); // restoring Texture.clone()
  21713. }
  21714. /**
  21715. * Sets the current frame of the video. This will automatically update the texture
  21716. * so the data can be used for rendering.
  21717. *
  21718. * @param {VideoFrame} frame - The video frame.
  21719. */
  21720. setFrame( frame ) {
  21721. this.image = frame;
  21722. this.needsUpdate = true;
  21723. }
  21724. }
  21725. /**
  21726. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21727. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21728. * as a texture for further usage.
  21729. *
  21730. * ```js
  21731. * const pixelRatio = window.devicePixelRatio;
  21732. * const textureSize = 128 * pixelRatio;
  21733. *
  21734. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21735. *
  21736. * // calculate start position for copying part of the frame data
  21737. * const vector = new Vector2();
  21738. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21739. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21740. *
  21741. * renderer.render( scene, camera );
  21742. *
  21743. * // copy part of the rendered frame into the framebuffer texture
  21744. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21745. * ```
  21746. *
  21747. * @augments Texture
  21748. */
  21749. class FramebufferTexture extends Texture {
  21750. /**
  21751. * Constructs a new framebuffer texture.
  21752. *
  21753. * @param {number} [width] - The width of the texture.
  21754. * @param {number} [height] - The height of the texture.
  21755. */
  21756. constructor( width, height ) {
  21757. super( { width, height } );
  21758. /**
  21759. * This flag can be used for type testing.
  21760. *
  21761. * @type {boolean}
  21762. * @readonly
  21763. * @default true
  21764. */
  21765. this.isFramebufferTexture = true;
  21766. /**
  21767. * How the texture is sampled when a texel covers more than one pixel.
  21768. *
  21769. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21770. *
  21771. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21772. * @default NearestFilter
  21773. */
  21774. this.magFilter = NearestFilter;
  21775. /**
  21776. * How the texture is sampled when a texel covers less than one pixel.
  21777. *
  21778. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21779. *
  21780. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21781. * @default NearestFilter
  21782. */
  21783. this.minFilter = NearestFilter;
  21784. /**
  21785. * Whether to generate mipmaps (if possible) for a texture.
  21786. *
  21787. * Overwritten and set to `false` by default.
  21788. *
  21789. * @type {boolean}
  21790. * @default false
  21791. */
  21792. this.generateMipmaps = false;
  21793. this.needsUpdate = true;
  21794. }
  21795. }
  21796. /**
  21797. * Creates a texture based on data in compressed form.
  21798. *
  21799. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21800. *
  21801. * @augments Texture
  21802. */
  21803. class CompressedTexture extends Texture {
  21804. /**
  21805. * Constructs a new compressed texture.
  21806. *
  21807. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21808. * the data and dimensions.
  21809. * @param {number} width - The width of the texture.
  21810. * @param {number} height - The height of the texture.
  21811. * @param {number} [format=RGBAFormat] - The texture format.
  21812. * @param {number} [type=UnsignedByteType] - The texture type.
  21813. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21814. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21815. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21816. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21817. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21818. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21819. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21820. */
  21821. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21822. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21823. /**
  21824. * This flag can be used for type testing.
  21825. *
  21826. * @type {boolean}
  21827. * @readonly
  21828. * @default true
  21829. */
  21830. this.isCompressedTexture = true;
  21831. /**
  21832. * The image property of a compressed texture just defines its dimensions.
  21833. *
  21834. * @type {{width:number,height:number}}
  21835. */
  21836. this.image = { width: width, height: height };
  21837. /**
  21838. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21839. *
  21840. * @type {Array<Object>}
  21841. */
  21842. this.mipmaps = mipmaps;
  21843. /**
  21844. * If set to `true`, the texture is flipped along the vertical axis when
  21845. * uploaded to the GPU.
  21846. *
  21847. * Overwritten and set to `false` by default since it is not possible to
  21848. * flip compressed textures.
  21849. *
  21850. * @type {boolean}
  21851. * @default false
  21852. * @readonly
  21853. */
  21854. this.flipY = false;
  21855. /**
  21856. * Whether to generate mipmaps (if possible) for a texture.
  21857. *
  21858. * Overwritten and set to `false` by default since it is not
  21859. * possible to generate mipmaps for compressed data. Mipmaps
  21860. * must be embedded in the compressed texture file.
  21861. *
  21862. * @type {boolean}
  21863. * @default false
  21864. * @readonly
  21865. */
  21866. this.generateMipmaps = false;
  21867. }
  21868. }
  21869. /**
  21870. * Creates a texture 2D array based on data in compressed form.
  21871. *
  21872. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21873. *
  21874. * @augments CompressedTexture
  21875. */
  21876. class CompressedArrayTexture extends CompressedTexture {
  21877. /**
  21878. * Constructs a new compressed array texture.
  21879. *
  21880. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21881. * the data and dimensions.
  21882. * @param {number} width - The width of the texture.
  21883. * @param {number} height - The height of the texture.
  21884. * @param {number} depth - The depth of the texture.
  21885. * @param {number} [format=RGBAFormat] - The min filter value.
  21886. * @param {number} [type=UnsignedByteType] - The min filter value.
  21887. */
  21888. constructor( mipmaps, width, height, depth, format, type ) {
  21889. super( mipmaps, width, height, format, type );
  21890. /**
  21891. * This flag can be used for type testing.
  21892. *
  21893. * @type {boolean}
  21894. * @readonly
  21895. * @default true
  21896. */
  21897. this.isCompressedArrayTexture = true;
  21898. /**
  21899. * The image property of a compressed texture just defines its dimensions.
  21900. *
  21901. * @name CompressedArrayTexture#image
  21902. * @type {{width:number,height:number,depth:number}}
  21903. */
  21904. this.image.depth = depth;
  21905. /**
  21906. * This defines how the texture is wrapped in the depth and corresponds to
  21907. * *W* in UVW mapping.
  21908. *
  21909. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21910. * @default ClampToEdgeWrapping
  21911. */
  21912. this.wrapR = ClampToEdgeWrapping;
  21913. /**
  21914. * A set of all layers which need to be updated in the texture.
  21915. *
  21916. * @type {Set<number>}
  21917. */
  21918. this.layerUpdates = new Set();
  21919. }
  21920. /**
  21921. * Describes that a specific layer of the texture needs to be updated.
  21922. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21923. * entire compressed texture array is sent to the GPU. Marking specific
  21924. * layers will only transmit subsets of all mipmaps associated with a
  21925. * specific depth in the array which is often much more performant.
  21926. *
  21927. * @param {number} layerIndex - The layer index that should be updated.
  21928. */
  21929. addLayerUpdate( layerIndex ) {
  21930. this.layerUpdates.add( layerIndex );
  21931. }
  21932. /**
  21933. * Resets the layer updates registry.
  21934. */
  21935. clearLayerUpdates() {
  21936. this.layerUpdates.clear();
  21937. }
  21938. }
  21939. /**
  21940. * Creates a cube texture based on data in compressed form.
  21941. *
  21942. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21943. *
  21944. * @augments CompressedTexture
  21945. */
  21946. class CompressedCubeTexture extends CompressedTexture {
  21947. /**
  21948. * Constructs a new compressed texture.
  21949. *
  21950. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  21951. * @param {number} [format=RGBAFormat] - The texture format.
  21952. * @param {number} [type=UnsignedByteType] - The texture type.
  21953. */
  21954. constructor( images, format, type ) {
  21955. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  21956. /**
  21957. * This flag can be used for type testing.
  21958. *
  21959. * @type {boolean}
  21960. * @readonly
  21961. * @default true
  21962. */
  21963. this.isCompressedCubeTexture = true;
  21964. /**
  21965. * This flag can be used for type testing.
  21966. *
  21967. * @type {boolean}
  21968. * @readonly
  21969. * @default true
  21970. */
  21971. this.isCubeTexture = true;
  21972. this.image = images;
  21973. }
  21974. }
  21975. /**
  21976. * Creates a texture from a canvas element.
  21977. *
  21978. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  21979. * to `true` immediately since a canvas can directly be used for rendering.
  21980. *
  21981. * @augments Texture
  21982. */
  21983. class CanvasTexture extends Texture {
  21984. /**
  21985. * Constructs a new texture.
  21986. *
  21987. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  21988. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21989. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21990. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21991. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21992. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21993. * @param {number} [format=RGBAFormat] - The texture format.
  21994. * @param {number} [type=UnsignedByteType] - The texture type.
  21995. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21996. */
  21997. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21998. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21999. /**
  22000. * This flag can be used for type testing.
  22001. *
  22002. * @type {boolean}
  22003. * @readonly
  22004. * @default true
  22005. */
  22006. this.isCanvasTexture = true;
  22007. this.needsUpdate = true;
  22008. }
  22009. }
  22010. /**
  22011. * This class can be used to automatically save the depth information of a
  22012. * rendering into a texture.
  22013. *
  22014. * @augments Texture
  22015. */
  22016. class DepthTexture extends Texture {
  22017. /**
  22018. * Constructs a new depth texture.
  22019. *
  22020. * @param {number} width - The width of the texture.
  22021. * @param {number} height - The height of the texture.
  22022. * @param {number} [type=UnsignedIntType] - The texture type.
  22023. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22024. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22025. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22026. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22027. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22028. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22029. * @param {number} [format=DepthFormat] - The texture format.
  22030. * @param {number} [depth=1] - The depth of the texture.
  22031. */
  22032. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22033. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22034. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22035. }
  22036. const image = { width: width, height: height, depth: depth };
  22037. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22038. /**
  22039. * This flag can be used for type testing.
  22040. *
  22041. * @type {boolean}
  22042. * @readonly
  22043. * @default true
  22044. */
  22045. this.isDepthTexture = true;
  22046. /**
  22047. * If set to `true`, the texture is flipped along the vertical axis when
  22048. * uploaded to the GPU.
  22049. *
  22050. * Overwritten and set to `false` by default.
  22051. *
  22052. * @type {boolean}
  22053. * @default false
  22054. */
  22055. this.flipY = false;
  22056. /**
  22057. * Whether to generate mipmaps (if possible) for a texture.
  22058. *
  22059. * Overwritten and set to `false` by default.
  22060. *
  22061. * @type {boolean}
  22062. * @default false
  22063. */
  22064. this.generateMipmaps = false;
  22065. /**
  22066. * Code corresponding to the depth compare function.
  22067. *
  22068. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22069. * @default null
  22070. */
  22071. this.compareFunction = null;
  22072. }
  22073. copy( source ) {
  22074. super.copy( source );
  22075. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22076. this.compareFunction = source.compareFunction;
  22077. return this;
  22078. }
  22079. toJSON( meta ) {
  22080. const data = super.toJSON( meta );
  22081. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22082. return data;
  22083. }
  22084. }
  22085. /**
  22086. * A geometry class for representing a capsule.
  22087. *
  22088. * ```js
  22089. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22090. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22091. * const capsule = new THREE.Mesh( geometry, material );
  22092. * scene.add( capsule );
  22093. * ```
  22094. *
  22095. * @augments BufferGeometry
  22096. */
  22097. class CapsuleGeometry extends BufferGeometry {
  22098. /**
  22099. * Constructs a new capsule geometry.
  22100. *
  22101. * @param {number} [radius=1] - Radius of the capsule.
  22102. * @param {number} [height=1] - Height of the middle section.
  22103. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22104. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22105. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22106. */
  22107. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22108. super();
  22109. this.type = 'CapsuleGeometry';
  22110. /**
  22111. * Holds the constructor parameters that have been
  22112. * used to generate the geometry. Any modification
  22113. * after instantiation does not change the geometry.
  22114. *
  22115. * @type {Object}
  22116. */
  22117. this.parameters = {
  22118. radius: radius,
  22119. height: height,
  22120. capSegments: capSegments,
  22121. radialSegments: radialSegments,
  22122. heightSegments: heightSegments,
  22123. };
  22124. height = Math.max( 0, height );
  22125. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22126. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22127. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22128. // buffers
  22129. const indices = [];
  22130. const vertices = [];
  22131. const normals = [];
  22132. const uvs = [];
  22133. // helper variables
  22134. const halfHeight = height / 2;
  22135. const capArcLength = ( Math.PI / 2 ) * radius;
  22136. const cylinderPartLength = height;
  22137. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22138. const numVerticalSegments = capSegments * 2 + heightSegments;
  22139. const verticesPerRow = radialSegments + 1;
  22140. const normal = new Vector3();
  22141. const vertex = new Vector3();
  22142. // generate vertices, normals, and uvs
  22143. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22144. let currentArcLength = 0;
  22145. let profileY = 0;
  22146. let profileRadius = 0;
  22147. let normalYComponent = 0;
  22148. if ( iy <= capSegments ) {
  22149. // bottom cap
  22150. const segmentProgress = iy / capSegments;
  22151. const angle = ( segmentProgress * Math.PI ) / 2;
  22152. profileY = - halfHeight - radius * Math.cos( angle );
  22153. profileRadius = radius * Math.sin( angle );
  22154. normalYComponent = - radius * Math.cos( angle );
  22155. currentArcLength = segmentProgress * capArcLength;
  22156. } else if ( iy <= capSegments + heightSegments ) {
  22157. // middle section
  22158. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22159. profileY = - halfHeight + segmentProgress * height;
  22160. profileRadius = radius;
  22161. normalYComponent = 0;
  22162. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22163. } else {
  22164. // top cap
  22165. const segmentProgress =
  22166. ( iy - capSegments - heightSegments ) / capSegments;
  22167. const angle = ( segmentProgress * Math.PI ) / 2;
  22168. profileY = halfHeight + radius * Math.sin( angle );
  22169. profileRadius = radius * Math.cos( angle );
  22170. normalYComponent = radius * Math.sin( angle );
  22171. currentArcLength =
  22172. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22173. }
  22174. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22175. // special case for the poles
  22176. let uOffset = 0;
  22177. if ( iy === 0 ) {
  22178. uOffset = 0.5 / radialSegments;
  22179. } else if ( iy === numVerticalSegments ) {
  22180. uOffset = -0.5 / radialSegments;
  22181. }
  22182. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22183. const u = ix / radialSegments;
  22184. const theta = u * Math.PI * 2;
  22185. const sinTheta = Math.sin( theta );
  22186. const cosTheta = Math.cos( theta );
  22187. // vertex
  22188. vertex.x = - profileRadius * cosTheta;
  22189. vertex.y = profileY;
  22190. vertex.z = profileRadius * sinTheta;
  22191. vertices.push( vertex.x, vertex.y, vertex.z );
  22192. // normal
  22193. normal.set(
  22194. - profileRadius * cosTheta,
  22195. normalYComponent,
  22196. profileRadius * sinTheta
  22197. );
  22198. normal.normalize();
  22199. normals.push( normal.x, normal.y, normal.z );
  22200. // uv
  22201. uvs.push( u + uOffset, v );
  22202. }
  22203. if ( iy > 0 ) {
  22204. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22205. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22206. const i1 = prevIndexRow + ix;
  22207. const i2 = prevIndexRow + ix + 1;
  22208. const i3 = iy * verticesPerRow + ix;
  22209. const i4 = iy * verticesPerRow + ix + 1;
  22210. indices.push( i1, i2, i3 );
  22211. indices.push( i2, i4, i3 );
  22212. }
  22213. }
  22214. }
  22215. // build geometry
  22216. this.setIndex( indices );
  22217. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22218. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22219. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22220. }
  22221. copy( source ) {
  22222. super.copy( source );
  22223. this.parameters = Object.assign( {}, source.parameters );
  22224. return this;
  22225. }
  22226. /**
  22227. * Factory method for creating an instance of this class from the given
  22228. * JSON object.
  22229. *
  22230. * @param {Object} data - A JSON object representing the serialized geometry.
  22231. * @return {CapsuleGeometry} A new instance.
  22232. */
  22233. static fromJSON( data ) {
  22234. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22235. }
  22236. }
  22237. /**
  22238. * A simple shape of Euclidean geometry. It is constructed from a
  22239. * number of triangular segments that are oriented around a central point and
  22240. * extend as far out as a given radius. It is built counter-clockwise from a
  22241. * start angle and a given central angle. It can also be used to create
  22242. * regular polygons, where the number of segments determines the number of
  22243. * sides.
  22244. *
  22245. * ```js
  22246. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22247. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22248. * const circle = new THREE.Mesh( geometry, material );
  22249. * scene.add( circle )
  22250. * ```
  22251. *
  22252. * @augments BufferGeometry
  22253. */
  22254. class CircleGeometry extends BufferGeometry {
  22255. /**
  22256. * Constructs a new circle geometry.
  22257. *
  22258. * @param {number} [radius=1] - Radius of the circle.
  22259. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22260. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22261. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22262. * of the circular sector in radians. The default value results in a complete circle.
  22263. */
  22264. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22265. super();
  22266. this.type = 'CircleGeometry';
  22267. /**
  22268. * Holds the constructor parameters that have been
  22269. * used to generate the geometry. Any modification
  22270. * after instantiation does not change the geometry.
  22271. *
  22272. * @type {Object}
  22273. */
  22274. this.parameters = {
  22275. radius: radius,
  22276. segments: segments,
  22277. thetaStart: thetaStart,
  22278. thetaLength: thetaLength
  22279. };
  22280. segments = Math.max( 3, segments );
  22281. // buffers
  22282. const indices = [];
  22283. const vertices = [];
  22284. const normals = [];
  22285. const uvs = [];
  22286. // helper variables
  22287. const vertex = new Vector3();
  22288. const uv = new Vector2();
  22289. // center point
  22290. vertices.push( 0, 0, 0 );
  22291. normals.push( 0, 0, 1 );
  22292. uvs.push( 0.5, 0.5 );
  22293. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22294. const segment = thetaStart + s / segments * thetaLength;
  22295. // vertex
  22296. vertex.x = radius * Math.cos( segment );
  22297. vertex.y = radius * Math.sin( segment );
  22298. vertices.push( vertex.x, vertex.y, vertex.z );
  22299. // normal
  22300. normals.push( 0, 0, 1 );
  22301. // uvs
  22302. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22303. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22304. uvs.push( uv.x, uv.y );
  22305. }
  22306. // indices
  22307. for ( let i = 1; i <= segments; i ++ ) {
  22308. indices.push( i, i + 1, 0 );
  22309. }
  22310. // build geometry
  22311. this.setIndex( indices );
  22312. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22313. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22314. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22315. }
  22316. copy( source ) {
  22317. super.copy( source );
  22318. this.parameters = Object.assign( {}, source.parameters );
  22319. return this;
  22320. }
  22321. /**
  22322. * Factory method for creating an instance of this class from the given
  22323. * JSON object.
  22324. *
  22325. * @param {Object} data - A JSON object representing the serialized geometry.
  22326. * @return {CircleGeometry} A new instance.
  22327. */
  22328. static fromJSON( data ) {
  22329. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22330. }
  22331. }
  22332. /**
  22333. * A geometry class for representing a cylinder.
  22334. *
  22335. * ```js
  22336. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22337. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22338. * const cylinder = new THREE.Mesh( geometry, material );
  22339. * scene.add( cylinder );
  22340. * ```
  22341. *
  22342. * @augments BufferGeometry
  22343. */
  22344. class CylinderGeometry extends BufferGeometry {
  22345. /**
  22346. * Constructs a new cylinder geometry.
  22347. *
  22348. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22349. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22350. * @param {number} [height=1] - Height of the cylinder.
  22351. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22352. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22353. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22354. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22355. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22356. * The default value results in a complete cylinder.
  22357. */
  22358. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22359. super();
  22360. this.type = 'CylinderGeometry';
  22361. /**
  22362. * Holds the constructor parameters that have been
  22363. * used to generate the geometry. Any modification
  22364. * after instantiation does not change the geometry.
  22365. *
  22366. * @type {Object}
  22367. */
  22368. this.parameters = {
  22369. radiusTop: radiusTop,
  22370. radiusBottom: radiusBottom,
  22371. height: height,
  22372. radialSegments: radialSegments,
  22373. heightSegments: heightSegments,
  22374. openEnded: openEnded,
  22375. thetaStart: thetaStart,
  22376. thetaLength: thetaLength
  22377. };
  22378. const scope = this;
  22379. radialSegments = Math.floor( radialSegments );
  22380. heightSegments = Math.floor( heightSegments );
  22381. // buffers
  22382. const indices = [];
  22383. const vertices = [];
  22384. const normals = [];
  22385. const uvs = [];
  22386. // helper variables
  22387. let index = 0;
  22388. const indexArray = [];
  22389. const halfHeight = height / 2;
  22390. let groupStart = 0;
  22391. // generate geometry
  22392. generateTorso();
  22393. if ( openEnded === false ) {
  22394. if ( radiusTop > 0 ) generateCap( true );
  22395. if ( radiusBottom > 0 ) generateCap( false );
  22396. }
  22397. // build geometry
  22398. this.setIndex( indices );
  22399. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22400. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22401. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22402. function generateTorso() {
  22403. const normal = new Vector3();
  22404. const vertex = new Vector3();
  22405. let groupCount = 0;
  22406. // this will be used to calculate the normal
  22407. const slope = ( radiusBottom - radiusTop ) / height;
  22408. // generate vertices, normals and uvs
  22409. for ( let y = 0; y <= heightSegments; y ++ ) {
  22410. const indexRow = [];
  22411. const v = y / heightSegments;
  22412. // calculate the radius of the current row
  22413. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22414. for ( let x = 0; x <= radialSegments; x ++ ) {
  22415. const u = x / radialSegments;
  22416. const theta = u * thetaLength + thetaStart;
  22417. const sinTheta = Math.sin( theta );
  22418. const cosTheta = Math.cos( theta );
  22419. // vertex
  22420. vertex.x = radius * sinTheta;
  22421. vertex.y = - v * height + halfHeight;
  22422. vertex.z = radius * cosTheta;
  22423. vertices.push( vertex.x, vertex.y, vertex.z );
  22424. // normal
  22425. normal.set( sinTheta, slope, cosTheta ).normalize();
  22426. normals.push( normal.x, normal.y, normal.z );
  22427. // uv
  22428. uvs.push( u, 1 - v );
  22429. // save index of vertex in respective row
  22430. indexRow.push( index ++ );
  22431. }
  22432. // now save vertices of the row in our index array
  22433. indexArray.push( indexRow );
  22434. }
  22435. // generate indices
  22436. for ( let x = 0; x < radialSegments; x ++ ) {
  22437. for ( let y = 0; y < heightSegments; y ++ ) {
  22438. // we use the index array to access the correct indices
  22439. const a = indexArray[ y ][ x ];
  22440. const b = indexArray[ y + 1 ][ x ];
  22441. const c = indexArray[ y + 1 ][ x + 1 ];
  22442. const d = indexArray[ y ][ x + 1 ];
  22443. // faces
  22444. if ( radiusTop > 0 || y !== 0 ) {
  22445. indices.push( a, b, d );
  22446. groupCount += 3;
  22447. }
  22448. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22449. indices.push( b, c, d );
  22450. groupCount += 3;
  22451. }
  22452. }
  22453. }
  22454. // add a group to the geometry. this will ensure multi material support
  22455. scope.addGroup( groupStart, groupCount, 0 );
  22456. // calculate new start value for groups
  22457. groupStart += groupCount;
  22458. }
  22459. function generateCap( top ) {
  22460. // save the index of the first center vertex
  22461. const centerIndexStart = index;
  22462. const uv = new Vector2();
  22463. const vertex = new Vector3();
  22464. let groupCount = 0;
  22465. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22466. const sign = ( top === true ) ? 1 : -1;
  22467. // first we generate the center vertex data of the cap.
  22468. // because the geometry needs one set of uvs per face,
  22469. // we must generate a center vertex per face/segment
  22470. for ( let x = 1; x <= radialSegments; x ++ ) {
  22471. // vertex
  22472. vertices.push( 0, halfHeight * sign, 0 );
  22473. // normal
  22474. normals.push( 0, sign, 0 );
  22475. // uv
  22476. uvs.push( 0.5, 0.5 );
  22477. // increase index
  22478. index ++;
  22479. }
  22480. // save the index of the last center vertex
  22481. const centerIndexEnd = index;
  22482. // now we generate the surrounding vertices, normals and uvs
  22483. for ( let x = 0; x <= radialSegments; x ++ ) {
  22484. const u = x / radialSegments;
  22485. const theta = u * thetaLength + thetaStart;
  22486. const cosTheta = Math.cos( theta );
  22487. const sinTheta = Math.sin( theta );
  22488. // vertex
  22489. vertex.x = radius * sinTheta;
  22490. vertex.y = halfHeight * sign;
  22491. vertex.z = radius * cosTheta;
  22492. vertices.push( vertex.x, vertex.y, vertex.z );
  22493. // normal
  22494. normals.push( 0, sign, 0 );
  22495. // uv
  22496. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22497. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22498. uvs.push( uv.x, uv.y );
  22499. // increase index
  22500. index ++;
  22501. }
  22502. // generate indices
  22503. for ( let x = 0; x < radialSegments; x ++ ) {
  22504. const c = centerIndexStart + x;
  22505. const i = centerIndexEnd + x;
  22506. if ( top === true ) {
  22507. // face top
  22508. indices.push( i, i + 1, c );
  22509. } else {
  22510. // face bottom
  22511. indices.push( i + 1, i, c );
  22512. }
  22513. groupCount += 3;
  22514. }
  22515. // add a group to the geometry. this will ensure multi material support
  22516. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22517. // calculate new start value for groups
  22518. groupStart += groupCount;
  22519. }
  22520. }
  22521. copy( source ) {
  22522. super.copy( source );
  22523. this.parameters = Object.assign( {}, source.parameters );
  22524. return this;
  22525. }
  22526. /**
  22527. * Factory method for creating an instance of this class from the given
  22528. * JSON object.
  22529. *
  22530. * @param {Object} data - A JSON object representing the serialized geometry.
  22531. * @return {CylinderGeometry} A new instance.
  22532. */
  22533. static fromJSON( data ) {
  22534. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22535. }
  22536. }
  22537. /**
  22538. * A geometry class for representing a cone.
  22539. *
  22540. * ```js
  22541. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22542. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22543. * const cone = new THREE.Mesh(geometry, material );
  22544. * scene.add( cone );
  22545. * ```
  22546. *
  22547. * @augments CylinderGeometry
  22548. */
  22549. class ConeGeometry extends CylinderGeometry {
  22550. /**
  22551. * Constructs a new cone geometry.
  22552. *
  22553. * @param {number} [radius=1] - Radius of the cone base.
  22554. * @param {number} [height=1] - Height of the cone.
  22555. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22556. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22557. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22558. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22559. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22560. * The default value results in a complete cone.
  22561. */
  22562. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22563. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22564. this.type = 'ConeGeometry';
  22565. /**
  22566. * Holds the constructor parameters that have been
  22567. * used to generate the geometry. Any modification
  22568. * after instantiation does not change the geometry.
  22569. *
  22570. * @type {Object}
  22571. */
  22572. this.parameters = {
  22573. radius: radius,
  22574. height: height,
  22575. radialSegments: radialSegments,
  22576. heightSegments: heightSegments,
  22577. openEnded: openEnded,
  22578. thetaStart: thetaStart,
  22579. thetaLength: thetaLength
  22580. };
  22581. }
  22582. /**
  22583. * Factory method for creating an instance of this class from the given
  22584. * JSON object.
  22585. *
  22586. * @param {Object} data - A JSON object representing the serialized geometry.
  22587. * @return {ConeGeometry} A new instance.
  22588. */
  22589. static fromJSON( data ) {
  22590. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22591. }
  22592. }
  22593. /**
  22594. * A polyhedron is a solid in three dimensions with flat faces. This class
  22595. * will take an array of vertices, project them onto a sphere, and then
  22596. * divide them up to the desired level of detail.
  22597. *
  22598. * @augments BufferGeometry
  22599. */
  22600. class PolyhedronGeometry extends BufferGeometry {
  22601. /**
  22602. * Constructs a new polyhedron geometry.
  22603. *
  22604. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22605. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22606. * @param {number} [radius=1] - The radius of the shape.
  22607. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22608. */
  22609. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22610. super();
  22611. this.type = 'PolyhedronGeometry';
  22612. /**
  22613. * Holds the constructor parameters that have been
  22614. * used to generate the geometry. Any modification
  22615. * after instantiation does not change the geometry.
  22616. *
  22617. * @type {Object}
  22618. */
  22619. this.parameters = {
  22620. vertices: vertices,
  22621. indices: indices,
  22622. radius: radius,
  22623. detail: detail
  22624. };
  22625. // default buffer data
  22626. const vertexBuffer = [];
  22627. const uvBuffer = [];
  22628. // the subdivision creates the vertex buffer data
  22629. subdivide( detail );
  22630. // all vertices should lie on a conceptual sphere with a given radius
  22631. applyRadius( radius );
  22632. // finally, create the uv data
  22633. generateUVs();
  22634. // build non-indexed geometry
  22635. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22636. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22637. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22638. if ( detail === 0 ) {
  22639. this.computeVertexNormals(); // flat normals
  22640. } else {
  22641. this.normalizeNormals(); // smooth normals
  22642. }
  22643. // helper functions
  22644. function subdivide( detail ) {
  22645. const a = new Vector3();
  22646. const b = new Vector3();
  22647. const c = new Vector3();
  22648. // iterate over all faces and apply a subdivision with the given detail value
  22649. for ( let i = 0; i < indices.length; i += 3 ) {
  22650. // get the vertices of the face
  22651. getVertexByIndex( indices[ i + 0 ], a );
  22652. getVertexByIndex( indices[ i + 1 ], b );
  22653. getVertexByIndex( indices[ i + 2 ], c );
  22654. // perform subdivision
  22655. subdivideFace( a, b, c, detail );
  22656. }
  22657. }
  22658. function subdivideFace( a, b, c, detail ) {
  22659. const cols = detail + 1;
  22660. // we use this multidimensional array as a data structure for creating the subdivision
  22661. const v = [];
  22662. // construct all of the vertices for this subdivision
  22663. for ( let i = 0; i <= cols; i ++ ) {
  22664. v[ i ] = [];
  22665. const aj = a.clone().lerp( c, i / cols );
  22666. const bj = b.clone().lerp( c, i / cols );
  22667. const rows = cols - i;
  22668. for ( let j = 0; j <= rows; j ++ ) {
  22669. if ( j === 0 && i === cols ) {
  22670. v[ i ][ j ] = aj;
  22671. } else {
  22672. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22673. }
  22674. }
  22675. }
  22676. // construct all of the faces
  22677. for ( let i = 0; i < cols; i ++ ) {
  22678. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22679. const k = Math.floor( j / 2 );
  22680. if ( j % 2 === 0 ) {
  22681. pushVertex( v[ i ][ k + 1 ] );
  22682. pushVertex( v[ i + 1 ][ k ] );
  22683. pushVertex( v[ i ][ k ] );
  22684. } else {
  22685. pushVertex( v[ i ][ k + 1 ] );
  22686. pushVertex( v[ i + 1 ][ k + 1 ] );
  22687. pushVertex( v[ i + 1 ][ k ] );
  22688. }
  22689. }
  22690. }
  22691. }
  22692. function applyRadius( radius ) {
  22693. const vertex = new Vector3();
  22694. // iterate over the entire buffer and apply the radius to each vertex
  22695. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22696. vertex.x = vertexBuffer[ i + 0 ];
  22697. vertex.y = vertexBuffer[ i + 1 ];
  22698. vertex.z = vertexBuffer[ i + 2 ];
  22699. vertex.normalize().multiplyScalar( radius );
  22700. vertexBuffer[ i + 0 ] = vertex.x;
  22701. vertexBuffer[ i + 1 ] = vertex.y;
  22702. vertexBuffer[ i + 2 ] = vertex.z;
  22703. }
  22704. }
  22705. function generateUVs() {
  22706. const vertex = new Vector3();
  22707. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22708. vertex.x = vertexBuffer[ i + 0 ];
  22709. vertex.y = vertexBuffer[ i + 1 ];
  22710. vertex.z = vertexBuffer[ i + 2 ];
  22711. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22712. const v = inclination( vertex ) / Math.PI + 0.5;
  22713. uvBuffer.push( u, 1 - v );
  22714. }
  22715. correctUVs();
  22716. correctSeam();
  22717. }
  22718. function correctSeam() {
  22719. // handle case when face straddles the seam, see #3269
  22720. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22721. // uv data of a single face
  22722. const x0 = uvBuffer[ i + 0 ];
  22723. const x1 = uvBuffer[ i + 2 ];
  22724. const x2 = uvBuffer[ i + 4 ];
  22725. const max = Math.max( x0, x1, x2 );
  22726. const min = Math.min( x0, x1, x2 );
  22727. // 0.9 is somewhat arbitrary
  22728. if ( max > 0.9 && min < 0.1 ) {
  22729. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22730. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22731. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22732. }
  22733. }
  22734. }
  22735. function pushVertex( vertex ) {
  22736. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22737. }
  22738. function getVertexByIndex( index, vertex ) {
  22739. const stride = index * 3;
  22740. vertex.x = vertices[ stride + 0 ];
  22741. vertex.y = vertices[ stride + 1 ];
  22742. vertex.z = vertices[ stride + 2 ];
  22743. }
  22744. function correctUVs() {
  22745. const a = new Vector3();
  22746. const b = new Vector3();
  22747. const c = new Vector3();
  22748. const centroid = new Vector3();
  22749. const uvA = new Vector2();
  22750. const uvB = new Vector2();
  22751. const uvC = new Vector2();
  22752. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22753. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22754. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22755. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22756. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22757. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22758. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22759. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22760. const azi = azimuth( centroid );
  22761. correctUV( uvA, j + 0, a, azi );
  22762. correctUV( uvB, j + 2, b, azi );
  22763. correctUV( uvC, j + 4, c, azi );
  22764. }
  22765. }
  22766. function correctUV( uv, stride, vector, azimuth ) {
  22767. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22768. uvBuffer[ stride ] = uv.x - 1;
  22769. }
  22770. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22771. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22772. }
  22773. }
  22774. // Angle around the Y axis, counter-clockwise when looking from above.
  22775. function azimuth( vector ) {
  22776. return Math.atan2( vector.z, - vector.x );
  22777. }
  22778. // Angle above the XZ plane.
  22779. function inclination( vector ) {
  22780. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22781. }
  22782. }
  22783. copy( source ) {
  22784. super.copy( source );
  22785. this.parameters = Object.assign( {}, source.parameters );
  22786. return this;
  22787. }
  22788. /**
  22789. * Factory method for creating an instance of this class from the given
  22790. * JSON object.
  22791. *
  22792. * @param {Object} data - A JSON object representing the serialized geometry.
  22793. * @return {PolyhedronGeometry} A new instance.
  22794. */
  22795. static fromJSON( data ) {
  22796. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22797. }
  22798. }
  22799. /**
  22800. * A geometry class for representing a dodecahedron.
  22801. *
  22802. * ```js
  22803. * const geometry = new THREE.DodecahedronGeometry();
  22804. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22805. * const dodecahedron = new THREE.Mesh( geometry, material );
  22806. * scene.add( dodecahedron );
  22807. * ```
  22808. *
  22809. * @augments PolyhedronGeometry
  22810. */
  22811. class DodecahedronGeometry extends PolyhedronGeometry {
  22812. /**
  22813. * Constructs a new dodecahedron geometry.
  22814. *
  22815. * @param {number} [radius=1] - Radius of the dodecahedron.
  22816. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22817. */
  22818. constructor( radius = 1, detail = 0 ) {
  22819. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22820. const r = 1 / t;
  22821. const vertices = [
  22822. // (±1, ±1, ±1)
  22823. -1, -1, -1, -1, -1, 1,
  22824. -1, 1, -1, -1, 1, 1,
  22825. 1, -1, -1, 1, -1, 1,
  22826. 1, 1, -1, 1, 1, 1,
  22827. // (0, ±1/φ, ±φ)
  22828. 0, - r, - t, 0, - r, t,
  22829. 0, r, - t, 0, r, t,
  22830. // (±1/φ, ±φ, 0)
  22831. - r, - t, 0, - r, t, 0,
  22832. r, - t, 0, r, t, 0,
  22833. // (±φ, 0, ±1/φ)
  22834. - t, 0, - r, t, 0, - r,
  22835. - t, 0, r, t, 0, r
  22836. ];
  22837. const indices = [
  22838. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22839. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22840. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22841. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22842. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22843. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22844. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22845. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22846. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22847. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22848. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22849. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22850. ];
  22851. super( vertices, indices, radius, detail );
  22852. this.type = 'DodecahedronGeometry';
  22853. /**
  22854. * Holds the constructor parameters that have been
  22855. * used to generate the geometry. Any modification
  22856. * after instantiation does not change the geometry.
  22857. *
  22858. * @type {Object}
  22859. */
  22860. this.parameters = {
  22861. radius: radius,
  22862. detail: detail
  22863. };
  22864. }
  22865. /**
  22866. * Factory method for creating an instance of this class from the given
  22867. * JSON object.
  22868. *
  22869. * @param {Object} data - A JSON object representing the serialized geometry.
  22870. * @return {DodecahedronGeometry} A new instance.
  22871. */
  22872. static fromJSON( data ) {
  22873. return new DodecahedronGeometry( data.radius, data.detail );
  22874. }
  22875. }
  22876. const _v0 = /*@__PURE__*/ new Vector3();
  22877. const _v1$1 = /*@__PURE__*/ new Vector3();
  22878. const _normal = /*@__PURE__*/ new Vector3();
  22879. const _triangle = /*@__PURE__*/ new Triangle();
  22880. /**
  22881. * Can be used as a helper object to view the edges of a geometry.
  22882. *
  22883. * ```js
  22884. * const geometry = new THREE.BoxGeometry();
  22885. * const edges = new THREE.EdgesGeometry( geometry );
  22886. * const line = new THREE.LineSegments( edges );
  22887. * scene.add( line );
  22888. * ```
  22889. *
  22890. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22891. *
  22892. * @augments BufferGeometry
  22893. */
  22894. class EdgesGeometry extends BufferGeometry {
  22895. /**
  22896. * Constructs a new edges geometry.
  22897. *
  22898. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22899. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  22900. * between the face normals of the adjoining faces exceeds this value.
  22901. */
  22902. constructor( geometry = null, thresholdAngle = 1 ) {
  22903. super();
  22904. this.type = 'EdgesGeometry';
  22905. /**
  22906. * Holds the constructor parameters that have been
  22907. * used to generate the geometry. Any modification
  22908. * after instantiation does not change the geometry.
  22909. *
  22910. * @type {Object}
  22911. */
  22912. this.parameters = {
  22913. geometry: geometry,
  22914. thresholdAngle: thresholdAngle
  22915. };
  22916. if ( geometry !== null ) {
  22917. const precisionPoints = 4;
  22918. const precision = Math.pow( 10, precisionPoints );
  22919. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22920. const indexAttr = geometry.getIndex();
  22921. const positionAttr = geometry.getAttribute( 'position' );
  22922. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22923. const indexArr = [ 0, 0, 0 ];
  22924. const vertKeys = [ 'a', 'b', 'c' ];
  22925. const hashes = new Array( 3 );
  22926. const edgeData = {};
  22927. const vertices = [];
  22928. for ( let i = 0; i < indexCount; i += 3 ) {
  22929. if ( indexAttr ) {
  22930. indexArr[ 0 ] = indexAttr.getX( i );
  22931. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22932. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22933. } else {
  22934. indexArr[ 0 ] = i;
  22935. indexArr[ 1 ] = i + 1;
  22936. indexArr[ 2 ] = i + 2;
  22937. }
  22938. const { a, b, c } = _triangle;
  22939. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22940. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22941. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22942. _triangle.getNormal( _normal );
  22943. // create hashes for the edge from the vertices
  22944. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22945. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22946. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22947. // skip degenerate triangles
  22948. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22949. continue;
  22950. }
  22951. // iterate over every edge
  22952. for ( let j = 0; j < 3; j ++ ) {
  22953. // get the first and next vertex making up the edge
  22954. const jNext = ( j + 1 ) % 3;
  22955. const vecHash0 = hashes[ j ];
  22956. const vecHash1 = hashes[ jNext ];
  22957. const v0 = _triangle[ vertKeys[ j ] ];
  22958. const v1 = _triangle[ vertKeys[ jNext ] ];
  22959. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22960. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22961. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22962. // if we found a sibling edge add it into the vertex array if
  22963. // it meets the angle threshold and delete the edge from the map.
  22964. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22965. vertices.push( v0.x, v0.y, v0.z );
  22966. vertices.push( v1.x, v1.y, v1.z );
  22967. }
  22968. edgeData[ reverseHash ] = null;
  22969. } else if ( ! ( hash in edgeData ) ) {
  22970. // if we've already got an edge here then skip adding a new one
  22971. edgeData[ hash ] = {
  22972. index0: indexArr[ j ],
  22973. index1: indexArr[ jNext ],
  22974. normal: _normal.clone(),
  22975. };
  22976. }
  22977. }
  22978. }
  22979. // iterate over all remaining, unmatched edges and add them to the vertex array
  22980. for ( const key in edgeData ) {
  22981. if ( edgeData[ key ] ) {
  22982. const { index0, index1 } = edgeData[ key ];
  22983. _v0.fromBufferAttribute( positionAttr, index0 );
  22984. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22985. vertices.push( _v0.x, _v0.y, _v0.z );
  22986. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22987. }
  22988. }
  22989. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22990. }
  22991. }
  22992. copy( source ) {
  22993. super.copy( source );
  22994. this.parameters = Object.assign( {}, source.parameters );
  22995. return this;
  22996. }
  22997. }
  22998. /**
  22999. * An abstract base class for creating an analytic curve object that contains methods
  23000. * for interpolation.
  23001. *
  23002. * @abstract
  23003. */
  23004. class Curve {
  23005. /**
  23006. * Constructs a new curve.
  23007. */
  23008. constructor() {
  23009. /**
  23010. * The type property is used for detecting the object type
  23011. * in context of serialization/deserialization.
  23012. *
  23013. * @type {string}
  23014. * @readonly
  23015. */
  23016. this.type = 'Curve';
  23017. /**
  23018. * This value determines the amount of divisions when calculating the
  23019. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23020. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23021. * recommended to increase the value of this property if the curve is very large.
  23022. *
  23023. * @type {number}
  23024. * @default 200
  23025. */
  23026. this.arcLengthDivisions = 200;
  23027. /**
  23028. * Must be set to `true` if the curve parameters have changed.
  23029. *
  23030. * @type {boolean}
  23031. * @default false
  23032. */
  23033. this.needsUpdate = false;
  23034. /**
  23035. * An internal cache that holds precomputed curve length values.
  23036. *
  23037. * @private
  23038. * @type {?Array<number>}
  23039. * @default null
  23040. */
  23041. this.cacheArcLengths = null;
  23042. }
  23043. /**
  23044. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23045. * for the given interpolation factor.
  23046. *
  23047. * @abstract
  23048. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23049. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23050. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23051. */
  23052. getPoint( /* t, optionalTarget */ ) {
  23053. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23054. }
  23055. /**
  23056. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23057. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23058. * of the curve which equidistant samples.
  23059. *
  23060. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23061. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23062. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23063. */
  23064. getPointAt( u, optionalTarget ) {
  23065. const t = this.getUtoTmapping( u );
  23066. return this.getPoint( t, optionalTarget );
  23067. }
  23068. /**
  23069. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23070. * the curve shape.
  23071. *
  23072. * @param {number} [divisions=5] - The number of divisions.
  23073. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23074. */
  23075. getPoints( divisions = 5 ) {
  23076. const points = [];
  23077. for ( let d = 0; d <= divisions; d ++ ) {
  23078. points.push( this.getPoint( d / divisions ) );
  23079. }
  23080. return points;
  23081. }
  23082. // Get sequence of points using getPointAt( u )
  23083. /**
  23084. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23085. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23086. * curve.
  23087. *
  23088. * @param {number} [divisions=5] - The number of divisions.
  23089. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23090. */
  23091. getSpacedPoints( divisions = 5 ) {
  23092. const points = [];
  23093. for ( let d = 0; d <= divisions; d ++ ) {
  23094. points.push( this.getPointAt( d / divisions ) );
  23095. }
  23096. return points;
  23097. }
  23098. /**
  23099. * Returns the total arc length of the curve.
  23100. *
  23101. * @return {number} The length of the curve.
  23102. */
  23103. getLength() {
  23104. const lengths = this.getLengths();
  23105. return lengths[ lengths.length - 1 ];
  23106. }
  23107. /**
  23108. * Returns an array of cumulative segment lengths of the curve.
  23109. *
  23110. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23111. * @return {Array<number>} An array holding the cumulative segment lengths.
  23112. */
  23113. getLengths( divisions = this.arcLengthDivisions ) {
  23114. if ( this.cacheArcLengths &&
  23115. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23116. ! this.needsUpdate ) {
  23117. return this.cacheArcLengths;
  23118. }
  23119. this.needsUpdate = false;
  23120. const cache = [];
  23121. let current, last = this.getPoint( 0 );
  23122. let sum = 0;
  23123. cache.push( 0 );
  23124. for ( let p = 1; p <= divisions; p ++ ) {
  23125. current = this.getPoint( p / divisions );
  23126. sum += current.distanceTo( last );
  23127. cache.push( sum );
  23128. last = current;
  23129. }
  23130. this.cacheArcLengths = cache;
  23131. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23132. }
  23133. /**
  23134. * Update the cumulative segment distance cache. The method must be called
  23135. * every time curve parameters are changed. If an updated curve is part of a
  23136. * composed curve like {@link CurvePath}, this method must be called on the
  23137. * composed curve, too.
  23138. */
  23139. updateArcLengths() {
  23140. this.needsUpdate = true;
  23141. this.getLengths();
  23142. }
  23143. /**
  23144. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23145. * interpolation factor in the same range that can be ued to sample equidistant points
  23146. * from a curve.
  23147. *
  23148. * @param {number} u - The interpolation factor.
  23149. * @param {?number} distance - An optional distance on the curve.
  23150. * @return {number} The updated interpolation factor.
  23151. */
  23152. getUtoTmapping( u, distance = null ) {
  23153. const arcLengths = this.getLengths();
  23154. let i = 0;
  23155. const il = arcLengths.length;
  23156. let targetArcLength; // The targeted u distance value to get
  23157. if ( distance ) {
  23158. targetArcLength = distance;
  23159. } else {
  23160. targetArcLength = u * arcLengths[ il - 1 ];
  23161. }
  23162. // binary search for the index with largest value smaller than target u distance
  23163. let low = 0, high = il - 1, comparison;
  23164. while ( low <= high ) {
  23165. 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
  23166. comparison = arcLengths[ i ] - targetArcLength;
  23167. if ( comparison < 0 ) {
  23168. low = i + 1;
  23169. } else if ( comparison > 0 ) {
  23170. high = i - 1;
  23171. } else {
  23172. high = i;
  23173. break;
  23174. // DONE
  23175. }
  23176. }
  23177. i = high;
  23178. if ( arcLengths[ i ] === targetArcLength ) {
  23179. return i / ( il - 1 );
  23180. }
  23181. // we could get finer grain at lengths, or use simple interpolation between two points
  23182. const lengthBefore = arcLengths[ i ];
  23183. const lengthAfter = arcLengths[ i + 1 ];
  23184. const segmentLength = lengthAfter - lengthBefore;
  23185. // determine where we are between the 'before' and 'after' points
  23186. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23187. // add that fractional amount to t
  23188. const t = ( i + segmentFraction ) / ( il - 1 );
  23189. return t;
  23190. }
  23191. /**
  23192. * Returns a unit vector tangent for the given interpolation factor.
  23193. * If the derived curve does not implement its tangent derivation,
  23194. * two points a small delta apart will be used to find its gradient
  23195. * which seems to give a reasonable approximation.
  23196. *
  23197. * @param {number} t - The interpolation factor.
  23198. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23199. * @return {(Vector2|Vector3)} The tangent vector.
  23200. */
  23201. getTangent( t, optionalTarget ) {
  23202. const delta = 0.0001;
  23203. let t1 = t - delta;
  23204. let t2 = t + delta;
  23205. // Capping in case of danger
  23206. if ( t1 < 0 ) t1 = 0;
  23207. if ( t2 > 1 ) t2 = 1;
  23208. const pt1 = this.getPoint( t1 );
  23209. const pt2 = this.getPoint( t2 );
  23210. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23211. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23212. return tangent;
  23213. }
  23214. /**
  23215. * Same as {@link Curve#getTangent} but with equidistant samples.
  23216. *
  23217. * @param {number} u - The interpolation factor.
  23218. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23219. * @return {(Vector2|Vector3)} The tangent vector.
  23220. * @see {@link Curve#getPointAt}
  23221. */
  23222. getTangentAt( u, optionalTarget ) {
  23223. const t = this.getUtoTmapping( u );
  23224. return this.getTangent( t, optionalTarget );
  23225. }
  23226. /**
  23227. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23228. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23229. *
  23230. * @param {number} segments - The number of segments.
  23231. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23232. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23233. */
  23234. computeFrenetFrames( segments, closed = false ) {
  23235. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23236. const normal = new Vector3();
  23237. const tangents = [];
  23238. const normals = [];
  23239. const binormals = [];
  23240. const vec = new Vector3();
  23241. const mat = new Matrix4();
  23242. // compute the tangent vectors for each segment on the curve
  23243. for ( let i = 0; i <= segments; i ++ ) {
  23244. const u = i / segments;
  23245. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23246. }
  23247. // select an initial normal vector perpendicular to the first tangent vector,
  23248. // and in the direction of the minimum tangent xyz component
  23249. normals[ 0 ] = new Vector3();
  23250. binormals[ 0 ] = new Vector3();
  23251. let min = Number.MAX_VALUE;
  23252. const tx = Math.abs( tangents[ 0 ].x );
  23253. const ty = Math.abs( tangents[ 0 ].y );
  23254. const tz = Math.abs( tangents[ 0 ].z );
  23255. if ( tx <= min ) {
  23256. min = tx;
  23257. normal.set( 1, 0, 0 );
  23258. }
  23259. if ( ty <= min ) {
  23260. min = ty;
  23261. normal.set( 0, 1, 0 );
  23262. }
  23263. if ( tz <= min ) {
  23264. normal.set( 0, 0, 1 );
  23265. }
  23266. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23267. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23268. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23269. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23270. for ( let i = 1; i <= segments; i ++ ) {
  23271. normals[ i ] = normals[ i - 1 ].clone();
  23272. binormals[ i ] = binormals[ i - 1 ].clone();
  23273. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23274. if ( vec.length() > Number.EPSILON ) {
  23275. vec.normalize();
  23276. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23277. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23278. }
  23279. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23280. }
  23281. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23282. if ( closed === true ) {
  23283. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23284. theta /= segments;
  23285. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23286. theta = - theta;
  23287. }
  23288. for ( let i = 1; i <= segments; i ++ ) {
  23289. // twist a little...
  23290. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23291. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23292. }
  23293. }
  23294. return {
  23295. tangents: tangents,
  23296. normals: normals,
  23297. binormals: binormals
  23298. };
  23299. }
  23300. /**
  23301. * Returns a new curve with copied values from this instance.
  23302. *
  23303. * @return {Curve} A clone of this instance.
  23304. */
  23305. clone() {
  23306. return new this.constructor().copy( this );
  23307. }
  23308. /**
  23309. * Copies the values of the given curve to this instance.
  23310. *
  23311. * @param {Curve} source - The curve to copy.
  23312. * @return {Curve} A reference to this curve.
  23313. */
  23314. copy( source ) {
  23315. this.arcLengthDivisions = source.arcLengthDivisions;
  23316. return this;
  23317. }
  23318. /**
  23319. * Serializes the curve into JSON.
  23320. *
  23321. * @return {Object} A JSON object representing the serialized curve.
  23322. * @see {@link ObjectLoader#parse}
  23323. */
  23324. toJSON() {
  23325. const data = {
  23326. metadata: {
  23327. version: 4.7,
  23328. type: 'Curve',
  23329. generator: 'Curve.toJSON'
  23330. }
  23331. };
  23332. data.arcLengthDivisions = this.arcLengthDivisions;
  23333. data.type = this.type;
  23334. return data;
  23335. }
  23336. /**
  23337. * Deserializes the curve from the given JSON.
  23338. *
  23339. * @param {Object} json - The JSON holding the serialized curve.
  23340. * @return {Curve} A reference to this curve.
  23341. */
  23342. fromJSON( json ) {
  23343. this.arcLengthDivisions = json.arcLengthDivisions;
  23344. return this;
  23345. }
  23346. }
  23347. /**
  23348. * A curve representing an ellipse.
  23349. *
  23350. * ```js
  23351. * const curve = new THREE.EllipseCurve(
  23352. * 0, 0,
  23353. * 10, 10,
  23354. * 0, 2 * Math.PI,
  23355. * false,
  23356. * 0
  23357. * );
  23358. *
  23359. * const points = curve.getPoints( 50 );
  23360. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23361. *
  23362. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23363. *
  23364. * // Create the final object to add to the scene
  23365. * const ellipse = new THREE.Line( geometry, material );
  23366. * ```
  23367. *
  23368. * @augments Curve
  23369. */
  23370. class EllipseCurve extends Curve {
  23371. /**
  23372. * Constructs a new ellipse curve.
  23373. *
  23374. * @param {number} [aX=0] - The X center of the ellipse.
  23375. * @param {number} [aY=0] - The Y center of the ellipse.
  23376. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23377. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23378. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23379. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23380. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23381. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23382. */
  23383. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23384. super();
  23385. /**
  23386. * This flag can be used for type testing.
  23387. *
  23388. * @type {boolean}
  23389. * @readonly
  23390. * @default true
  23391. */
  23392. this.isEllipseCurve = true;
  23393. this.type = 'EllipseCurve';
  23394. /**
  23395. * The X center of the ellipse.
  23396. *
  23397. * @type {number}
  23398. * @default 0
  23399. */
  23400. this.aX = aX;
  23401. /**
  23402. * The Y center of the ellipse.
  23403. *
  23404. * @type {number}
  23405. * @default 0
  23406. */
  23407. this.aY = aY;
  23408. /**
  23409. * The radius of the ellipse in the x direction.
  23410. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23411. *
  23412. * @type {number}
  23413. * @default 1
  23414. */
  23415. this.xRadius = xRadius;
  23416. /**
  23417. * The radius of the ellipse in the y direction.
  23418. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23419. *
  23420. * @type {number}
  23421. * @default 1
  23422. */
  23423. this.yRadius = yRadius;
  23424. /**
  23425. * The start angle of the curve in radians starting from the positive X axis.
  23426. *
  23427. * @type {number}
  23428. * @default 0
  23429. */
  23430. this.aStartAngle = aStartAngle;
  23431. /**
  23432. * The end angle of the curve in radians starting from the positive X axis.
  23433. *
  23434. * @type {number}
  23435. * @default Math.PI*2
  23436. */
  23437. this.aEndAngle = aEndAngle;
  23438. /**
  23439. * Whether the ellipse is drawn clockwise or not.
  23440. *
  23441. * @type {boolean}
  23442. * @default false
  23443. */
  23444. this.aClockwise = aClockwise;
  23445. /**
  23446. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23447. *
  23448. * @type {number}
  23449. * @default 0
  23450. */
  23451. this.aRotation = aRotation;
  23452. }
  23453. /**
  23454. * Returns a point on the curve.
  23455. *
  23456. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23457. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23458. * @return {Vector2} The position on the curve.
  23459. */
  23460. getPoint( t, optionalTarget = new Vector2() ) {
  23461. const point = optionalTarget;
  23462. const twoPi = Math.PI * 2;
  23463. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23464. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23465. // ensures that deltaAngle is 0 .. 2 PI
  23466. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23467. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23468. if ( deltaAngle < Number.EPSILON ) {
  23469. if ( samePoints ) {
  23470. deltaAngle = 0;
  23471. } else {
  23472. deltaAngle = twoPi;
  23473. }
  23474. }
  23475. if ( this.aClockwise === true && ! samePoints ) {
  23476. if ( deltaAngle === twoPi ) {
  23477. deltaAngle = - twoPi;
  23478. } else {
  23479. deltaAngle = deltaAngle - twoPi;
  23480. }
  23481. }
  23482. const angle = this.aStartAngle + t * deltaAngle;
  23483. let x = this.aX + this.xRadius * Math.cos( angle );
  23484. let y = this.aY + this.yRadius * Math.sin( angle );
  23485. if ( this.aRotation !== 0 ) {
  23486. const cos = Math.cos( this.aRotation );
  23487. const sin = Math.sin( this.aRotation );
  23488. const tx = x - this.aX;
  23489. const ty = y - this.aY;
  23490. // Rotate the point about the center of the ellipse.
  23491. x = tx * cos - ty * sin + this.aX;
  23492. y = tx * sin + ty * cos + this.aY;
  23493. }
  23494. return point.set( x, y );
  23495. }
  23496. copy( source ) {
  23497. super.copy( source );
  23498. this.aX = source.aX;
  23499. this.aY = source.aY;
  23500. this.xRadius = source.xRadius;
  23501. this.yRadius = source.yRadius;
  23502. this.aStartAngle = source.aStartAngle;
  23503. this.aEndAngle = source.aEndAngle;
  23504. this.aClockwise = source.aClockwise;
  23505. this.aRotation = source.aRotation;
  23506. return this;
  23507. }
  23508. toJSON() {
  23509. const data = super.toJSON();
  23510. data.aX = this.aX;
  23511. data.aY = this.aY;
  23512. data.xRadius = this.xRadius;
  23513. data.yRadius = this.yRadius;
  23514. data.aStartAngle = this.aStartAngle;
  23515. data.aEndAngle = this.aEndAngle;
  23516. data.aClockwise = this.aClockwise;
  23517. data.aRotation = this.aRotation;
  23518. return data;
  23519. }
  23520. fromJSON( json ) {
  23521. super.fromJSON( json );
  23522. this.aX = json.aX;
  23523. this.aY = json.aY;
  23524. this.xRadius = json.xRadius;
  23525. this.yRadius = json.yRadius;
  23526. this.aStartAngle = json.aStartAngle;
  23527. this.aEndAngle = json.aEndAngle;
  23528. this.aClockwise = json.aClockwise;
  23529. this.aRotation = json.aRotation;
  23530. return this;
  23531. }
  23532. }
  23533. /**
  23534. * A curve representing an arc.
  23535. *
  23536. * @augments EllipseCurve
  23537. */
  23538. class ArcCurve extends EllipseCurve {
  23539. /**
  23540. * Constructs a new arc curve.
  23541. *
  23542. * @param {number} [aX=0] - The X center of the ellipse.
  23543. * @param {number} [aY=0] - The Y center of the ellipse.
  23544. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23545. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23546. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23547. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23548. */
  23549. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23550. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23551. /**
  23552. * This flag can be used for type testing.
  23553. *
  23554. * @type {boolean}
  23555. * @readonly
  23556. * @default true
  23557. */
  23558. this.isArcCurve = true;
  23559. this.type = 'ArcCurve';
  23560. }
  23561. }
  23562. function CubicPoly() {
  23563. /**
  23564. * Centripetal CatmullRom Curve - which is useful for avoiding
  23565. * cusps and self-intersections in non-uniform catmull rom curves.
  23566. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23567. *
  23568. * curve.type accepts centripetal(default), chordal and catmullrom
  23569. * curve.tension is used for catmullrom which defaults to 0.5
  23570. */
  23571. /*
  23572. Based on an optimized c++ solution in
  23573. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23574. - http://ideone.com/NoEbVM
  23575. This CubicPoly class could be used for reusing some variables and calculations,
  23576. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23577. which can be placed in CurveUtils.
  23578. */
  23579. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23580. /*
  23581. * Compute coefficients for a cubic polynomial
  23582. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23583. * such that
  23584. * p(0) = x0, p(1) = x1
  23585. * and
  23586. * p'(0) = t0, p'(1) = t1.
  23587. */
  23588. function init( x0, x1, t0, t1 ) {
  23589. c0 = x0;
  23590. c1 = t0;
  23591. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23592. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23593. }
  23594. return {
  23595. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23596. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23597. },
  23598. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23599. // compute tangents when parameterized in [t1,t2]
  23600. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23601. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23602. // rescale tangents for parametrization in [0,1]
  23603. t1 *= dt1;
  23604. t2 *= dt1;
  23605. init( x1, x2, t1, t2 );
  23606. },
  23607. calc: function ( t ) {
  23608. const t2 = t * t;
  23609. const t3 = t2 * t;
  23610. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23611. }
  23612. };
  23613. }
  23614. //
  23615. const tmp = /*@__PURE__*/ new Vector3();
  23616. const px = /*@__PURE__*/ new CubicPoly();
  23617. const py = /*@__PURE__*/ new CubicPoly();
  23618. const pz = /*@__PURE__*/ new CubicPoly();
  23619. /**
  23620. * A curve representing a Catmull-Rom spline.
  23621. *
  23622. * ```js
  23623. * //Create a closed wavey loop
  23624. * const curve = new THREE.CatmullRomCurve3( [
  23625. * new THREE.Vector3( -10, 0, 10 ),
  23626. * new THREE.Vector3( -5, 5, 5 ),
  23627. * new THREE.Vector3( 0, 0, 0 ),
  23628. * new THREE.Vector3( 5, -5, 5 ),
  23629. * new THREE.Vector3( 10, 0, 10 )
  23630. * ] );
  23631. *
  23632. * const points = curve.getPoints( 50 );
  23633. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23634. *
  23635. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23636. *
  23637. * // Create the final object to add to the scene
  23638. * const curveObject = new THREE.Line( geometry, material );
  23639. * ```
  23640. *
  23641. * @augments Curve
  23642. */
  23643. class CatmullRomCurve3 extends Curve {
  23644. /**
  23645. * Constructs a new Catmull-Rom curve.
  23646. *
  23647. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23648. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23649. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23650. * @param {number} [tension=0.5] - Tension of the curve.
  23651. */
  23652. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23653. super();
  23654. /**
  23655. * This flag can be used for type testing.
  23656. *
  23657. * @type {boolean}
  23658. * @readonly
  23659. * @default true
  23660. */
  23661. this.isCatmullRomCurve3 = true;
  23662. this.type = 'CatmullRomCurve3';
  23663. /**
  23664. * An array of 3D points defining the curve.
  23665. *
  23666. * @type {Array<Vector3>}
  23667. */
  23668. this.points = points;
  23669. /**
  23670. * Whether the curve is closed or not.
  23671. *
  23672. * @type {boolean}
  23673. * @default false
  23674. */
  23675. this.closed = closed;
  23676. /**
  23677. * The curve type.
  23678. *
  23679. * @type {('centripetal'|'chordal'|'catmullrom')}
  23680. * @default 'centripetal'
  23681. */
  23682. this.curveType = curveType;
  23683. /**
  23684. * Tension of the curve.
  23685. *
  23686. * @type {number}
  23687. * @default 0.5
  23688. */
  23689. this.tension = tension;
  23690. }
  23691. /**
  23692. * Returns a point on the curve.
  23693. *
  23694. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23695. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23696. * @return {Vector3} The position on the curve.
  23697. */
  23698. getPoint( t, optionalTarget = new Vector3() ) {
  23699. const point = optionalTarget;
  23700. const points = this.points;
  23701. const l = points.length;
  23702. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23703. let intPoint = Math.floor( p );
  23704. let weight = p - intPoint;
  23705. if ( this.closed ) {
  23706. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23707. } else if ( weight === 0 && intPoint === l - 1 ) {
  23708. intPoint = l - 2;
  23709. weight = 1;
  23710. }
  23711. let p0, p3; // 4 points (p1 & p2 defined below)
  23712. if ( this.closed || intPoint > 0 ) {
  23713. p0 = points[ ( intPoint - 1 ) % l ];
  23714. } else {
  23715. // extrapolate first point
  23716. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23717. p0 = tmp;
  23718. }
  23719. const p1 = points[ intPoint % l ];
  23720. const p2 = points[ ( intPoint + 1 ) % l ];
  23721. if ( this.closed || intPoint + 2 < l ) {
  23722. p3 = points[ ( intPoint + 2 ) % l ];
  23723. } else {
  23724. // extrapolate last point
  23725. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23726. p3 = tmp;
  23727. }
  23728. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23729. // init Centripetal / Chordal Catmull-Rom
  23730. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23731. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23732. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23733. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23734. // safety check for repeated points
  23735. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23736. if ( dt0 < 1e-4 ) dt0 = dt1;
  23737. if ( dt2 < 1e-4 ) dt2 = dt1;
  23738. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23739. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23740. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23741. } else if ( this.curveType === 'catmullrom' ) {
  23742. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23743. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23744. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23745. }
  23746. point.set(
  23747. px.calc( weight ),
  23748. py.calc( weight ),
  23749. pz.calc( weight )
  23750. );
  23751. return point;
  23752. }
  23753. copy( source ) {
  23754. super.copy( source );
  23755. this.points = [];
  23756. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23757. const point = source.points[ i ];
  23758. this.points.push( point.clone() );
  23759. }
  23760. this.closed = source.closed;
  23761. this.curveType = source.curveType;
  23762. this.tension = source.tension;
  23763. return this;
  23764. }
  23765. toJSON() {
  23766. const data = super.toJSON();
  23767. data.points = [];
  23768. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23769. const point = this.points[ i ];
  23770. data.points.push( point.toArray() );
  23771. }
  23772. data.closed = this.closed;
  23773. data.curveType = this.curveType;
  23774. data.tension = this.tension;
  23775. return data;
  23776. }
  23777. fromJSON( json ) {
  23778. super.fromJSON( json );
  23779. this.points = [];
  23780. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23781. const point = json.points[ i ];
  23782. this.points.push( new Vector3().fromArray( point ) );
  23783. }
  23784. this.closed = json.closed;
  23785. this.curveType = json.curveType;
  23786. this.tension = json.tension;
  23787. return this;
  23788. }
  23789. }
  23790. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23791. /**
  23792. * Computes a point on a Catmull-Rom spline.
  23793. *
  23794. * @param {number} t - The interpolation factor.
  23795. * @param {number} p0 - The first control point.
  23796. * @param {number} p1 - The second control point.
  23797. * @param {number} p2 - The third control point.
  23798. * @param {number} p3 - The fourth control point.
  23799. * @return {number} The calculated point on a Catmull-Rom spline.
  23800. */
  23801. function CatmullRom( t, p0, p1, p2, p3 ) {
  23802. const v0 = ( p2 - p0 ) * 0.5;
  23803. const v1 = ( p3 - p1 ) * 0.5;
  23804. const t2 = t * t;
  23805. const t3 = t * t2;
  23806. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23807. }
  23808. //
  23809. function QuadraticBezierP0( t, p ) {
  23810. const k = 1 - t;
  23811. return k * k * p;
  23812. }
  23813. function QuadraticBezierP1( t, p ) {
  23814. return 2 * ( 1 - t ) * t * p;
  23815. }
  23816. function QuadraticBezierP2( t, p ) {
  23817. return t * t * p;
  23818. }
  23819. /**
  23820. * Computes a point on a Quadratic Bezier curve.
  23821. *
  23822. * @param {number} t - The interpolation factor.
  23823. * @param {number} p0 - The first control point.
  23824. * @param {number} p1 - The second control point.
  23825. * @param {number} p2 - The third control point.
  23826. * @return {number} The calculated point on a Quadratic Bezier curve.
  23827. */
  23828. function QuadraticBezier( t, p0, p1, p2 ) {
  23829. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23830. QuadraticBezierP2( t, p2 );
  23831. }
  23832. //
  23833. function CubicBezierP0( t, p ) {
  23834. const k = 1 - t;
  23835. return k * k * k * p;
  23836. }
  23837. function CubicBezierP1( t, p ) {
  23838. const k = 1 - t;
  23839. return 3 * k * k * t * p;
  23840. }
  23841. function CubicBezierP2( t, p ) {
  23842. return 3 * ( 1 - t ) * t * t * p;
  23843. }
  23844. function CubicBezierP3( t, p ) {
  23845. return t * t * t * p;
  23846. }
  23847. /**
  23848. * Computes a point on a Cubic Bezier curve.
  23849. *
  23850. * @param {number} t - The interpolation factor.
  23851. * @param {number} p0 - The first control point.
  23852. * @param {number} p1 - The second control point.
  23853. * @param {number} p2 - The third control point.
  23854. * @param {number} p3 - The fourth control point.
  23855. * @return {number} The calculated point on a Cubic Bezier curve.
  23856. */
  23857. function CubicBezier( t, p0, p1, p2, p3 ) {
  23858. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23859. CubicBezierP3( t, p3 );
  23860. }
  23861. /**
  23862. * A curve representing a 2D Cubic Bezier curve.
  23863. *
  23864. * ```js
  23865. * const curve = new THREE.CubicBezierCurve(
  23866. * new THREE.Vector2( - 0, 0 ),
  23867. * new THREE.Vector2( - 5, 15 ),
  23868. * new THREE.Vector2( 20, 15 ),
  23869. * new THREE.Vector2( 10, 0 )
  23870. * );
  23871. *
  23872. * const points = curve.getPoints( 50 );
  23873. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23874. *
  23875. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23876. *
  23877. * // Create the final object to add to the scene
  23878. * const curveObject = new THREE.Line( geometry, material );
  23879. * ```
  23880. *
  23881. * @augments Curve
  23882. */
  23883. class CubicBezierCurve extends Curve {
  23884. /**
  23885. * Constructs a new Cubic Bezier curve.
  23886. *
  23887. * @param {Vector2} [v0] - The start point.
  23888. * @param {Vector2} [v1] - The first control point.
  23889. * @param {Vector2} [v2] - The second control point.
  23890. * @param {Vector2} [v3] - The end point.
  23891. */
  23892. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23893. super();
  23894. /**
  23895. * This flag can be used for type testing.
  23896. *
  23897. * @type {boolean}
  23898. * @readonly
  23899. * @default true
  23900. */
  23901. this.isCubicBezierCurve = true;
  23902. this.type = 'CubicBezierCurve';
  23903. /**
  23904. * The start point.
  23905. *
  23906. * @type {Vector2}
  23907. */
  23908. this.v0 = v0;
  23909. /**
  23910. * The first control point.
  23911. *
  23912. * @type {Vector2}
  23913. */
  23914. this.v1 = v1;
  23915. /**
  23916. * The second control point.
  23917. *
  23918. * @type {Vector2}
  23919. */
  23920. this.v2 = v2;
  23921. /**
  23922. * The end point.
  23923. *
  23924. * @type {Vector2}
  23925. */
  23926. this.v3 = v3;
  23927. }
  23928. /**
  23929. * Returns a point on the curve.
  23930. *
  23931. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23932. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23933. * @return {Vector2} The position on the curve.
  23934. */
  23935. getPoint( t, optionalTarget = new Vector2() ) {
  23936. const point = optionalTarget;
  23937. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23938. point.set(
  23939. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23940. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23941. );
  23942. return point;
  23943. }
  23944. copy( source ) {
  23945. super.copy( source );
  23946. this.v0.copy( source.v0 );
  23947. this.v1.copy( source.v1 );
  23948. this.v2.copy( source.v2 );
  23949. this.v3.copy( source.v3 );
  23950. return this;
  23951. }
  23952. toJSON() {
  23953. const data = super.toJSON();
  23954. data.v0 = this.v0.toArray();
  23955. data.v1 = this.v1.toArray();
  23956. data.v2 = this.v2.toArray();
  23957. data.v3 = this.v3.toArray();
  23958. return data;
  23959. }
  23960. fromJSON( json ) {
  23961. super.fromJSON( json );
  23962. this.v0.fromArray( json.v0 );
  23963. this.v1.fromArray( json.v1 );
  23964. this.v2.fromArray( json.v2 );
  23965. this.v3.fromArray( json.v3 );
  23966. return this;
  23967. }
  23968. }
  23969. /**
  23970. * A curve representing a 3D Cubic Bezier curve.
  23971. *
  23972. * @augments Curve
  23973. */
  23974. class CubicBezierCurve3 extends Curve {
  23975. /**
  23976. * Constructs a new Cubic Bezier curve.
  23977. *
  23978. * @param {Vector3} [v0] - The start point.
  23979. * @param {Vector3} [v1] - The first control point.
  23980. * @param {Vector3} [v2] - The second control point.
  23981. * @param {Vector3} [v3] - The end point.
  23982. */
  23983. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23984. super();
  23985. /**
  23986. * This flag can be used for type testing.
  23987. *
  23988. * @type {boolean}
  23989. * @readonly
  23990. * @default true
  23991. */
  23992. this.isCubicBezierCurve3 = true;
  23993. this.type = 'CubicBezierCurve3';
  23994. /**
  23995. * The start point.
  23996. *
  23997. * @type {Vector3}
  23998. */
  23999. this.v0 = v0;
  24000. /**
  24001. * The first control point.
  24002. *
  24003. * @type {Vector3}
  24004. */
  24005. this.v1 = v1;
  24006. /**
  24007. * The second control point.
  24008. *
  24009. * @type {Vector3}
  24010. */
  24011. this.v2 = v2;
  24012. /**
  24013. * The end point.
  24014. *
  24015. * @type {Vector3}
  24016. */
  24017. this.v3 = v3;
  24018. }
  24019. /**
  24020. * Returns a point on the curve.
  24021. *
  24022. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24023. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24024. * @return {Vector3} The position on the curve.
  24025. */
  24026. getPoint( t, optionalTarget = new Vector3() ) {
  24027. const point = optionalTarget;
  24028. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24029. point.set(
  24030. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24031. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24032. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24033. );
  24034. return point;
  24035. }
  24036. copy( source ) {
  24037. super.copy( source );
  24038. this.v0.copy( source.v0 );
  24039. this.v1.copy( source.v1 );
  24040. this.v2.copy( source.v2 );
  24041. this.v3.copy( source.v3 );
  24042. return this;
  24043. }
  24044. toJSON() {
  24045. const data = super.toJSON();
  24046. data.v0 = this.v0.toArray();
  24047. data.v1 = this.v1.toArray();
  24048. data.v2 = this.v2.toArray();
  24049. data.v3 = this.v3.toArray();
  24050. return data;
  24051. }
  24052. fromJSON( json ) {
  24053. super.fromJSON( json );
  24054. this.v0.fromArray( json.v0 );
  24055. this.v1.fromArray( json.v1 );
  24056. this.v2.fromArray( json.v2 );
  24057. this.v3.fromArray( json.v3 );
  24058. return this;
  24059. }
  24060. }
  24061. /**
  24062. * A curve representing a 2D line segment.
  24063. *
  24064. * @augments Curve
  24065. */
  24066. class LineCurve extends Curve {
  24067. /**
  24068. * Constructs a new line curve.
  24069. *
  24070. * @param {Vector2} [v1] - The start point.
  24071. * @param {Vector2} [v2] - The end point.
  24072. */
  24073. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24074. super();
  24075. /**
  24076. * This flag can be used for type testing.
  24077. *
  24078. * @type {boolean}
  24079. * @readonly
  24080. * @default true
  24081. */
  24082. this.isLineCurve = true;
  24083. this.type = 'LineCurve';
  24084. /**
  24085. * The start point.
  24086. *
  24087. * @type {Vector2}
  24088. */
  24089. this.v1 = v1;
  24090. /**
  24091. * The end point.
  24092. *
  24093. * @type {Vector2}
  24094. */
  24095. this.v2 = v2;
  24096. }
  24097. /**
  24098. * Returns a point on the line.
  24099. *
  24100. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24101. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24102. * @return {Vector2} The position on the line.
  24103. */
  24104. getPoint( t, optionalTarget = new Vector2() ) {
  24105. const point = optionalTarget;
  24106. if ( t === 1 ) {
  24107. point.copy( this.v2 );
  24108. } else {
  24109. point.copy( this.v2 ).sub( this.v1 );
  24110. point.multiplyScalar( t ).add( this.v1 );
  24111. }
  24112. return point;
  24113. }
  24114. // Line curve is linear, so we can overwrite default getPointAt
  24115. getPointAt( u, optionalTarget ) {
  24116. return this.getPoint( u, optionalTarget );
  24117. }
  24118. getTangent( t, optionalTarget = new Vector2() ) {
  24119. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24120. }
  24121. getTangentAt( u, optionalTarget ) {
  24122. return this.getTangent( u, optionalTarget );
  24123. }
  24124. copy( source ) {
  24125. super.copy( source );
  24126. this.v1.copy( source.v1 );
  24127. this.v2.copy( source.v2 );
  24128. return this;
  24129. }
  24130. toJSON() {
  24131. const data = super.toJSON();
  24132. data.v1 = this.v1.toArray();
  24133. data.v2 = this.v2.toArray();
  24134. return data;
  24135. }
  24136. fromJSON( json ) {
  24137. super.fromJSON( json );
  24138. this.v1.fromArray( json.v1 );
  24139. this.v2.fromArray( json.v2 );
  24140. return this;
  24141. }
  24142. }
  24143. /**
  24144. * A curve representing a 3D line segment.
  24145. *
  24146. * @augments Curve
  24147. */
  24148. class LineCurve3 extends Curve {
  24149. /**
  24150. * Constructs a new line curve.
  24151. *
  24152. * @param {Vector3} [v1] - The start point.
  24153. * @param {Vector3} [v2] - The end point.
  24154. */
  24155. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24156. super();
  24157. /**
  24158. * This flag can be used for type testing.
  24159. *
  24160. * @type {boolean}
  24161. * @readonly
  24162. * @default true
  24163. */
  24164. this.isLineCurve3 = true;
  24165. this.type = 'LineCurve3';
  24166. /**
  24167. * The start point.
  24168. *
  24169. * @type {Vector3}
  24170. */
  24171. this.v1 = v1;
  24172. /**
  24173. * The end point.
  24174. *
  24175. * @type {Vector2}
  24176. */
  24177. this.v2 = v2;
  24178. }
  24179. /**
  24180. * Returns a point on the line.
  24181. *
  24182. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24183. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24184. * @return {Vector3} The position on the line.
  24185. */
  24186. getPoint( t, optionalTarget = new Vector3() ) {
  24187. const point = optionalTarget;
  24188. if ( t === 1 ) {
  24189. point.copy( this.v2 );
  24190. } else {
  24191. point.copy( this.v2 ).sub( this.v1 );
  24192. point.multiplyScalar( t ).add( this.v1 );
  24193. }
  24194. return point;
  24195. }
  24196. // Line curve is linear, so we can overwrite default getPointAt
  24197. getPointAt( u, optionalTarget ) {
  24198. return this.getPoint( u, optionalTarget );
  24199. }
  24200. getTangent( t, optionalTarget = new Vector3() ) {
  24201. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24202. }
  24203. getTangentAt( u, optionalTarget ) {
  24204. return this.getTangent( u, optionalTarget );
  24205. }
  24206. copy( source ) {
  24207. super.copy( source );
  24208. this.v1.copy( source.v1 );
  24209. this.v2.copy( source.v2 );
  24210. return this;
  24211. }
  24212. toJSON() {
  24213. const data = super.toJSON();
  24214. data.v1 = this.v1.toArray();
  24215. data.v2 = this.v2.toArray();
  24216. return data;
  24217. }
  24218. fromJSON( json ) {
  24219. super.fromJSON( json );
  24220. this.v1.fromArray( json.v1 );
  24221. this.v2.fromArray( json.v2 );
  24222. return this;
  24223. }
  24224. }
  24225. /**
  24226. * A curve representing a 2D Quadratic Bezier curve.
  24227. *
  24228. * ```js
  24229. * const curve = new THREE.QuadraticBezierCurve(
  24230. * new THREE.Vector2( - 10, 0 ),
  24231. * new THREE.Vector2( 20, 15 ),
  24232. * new THREE.Vector2( 10, 0 )
  24233. * )
  24234. *
  24235. * const points = curve.getPoints( 50 );
  24236. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24237. *
  24238. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24239. *
  24240. * // Create the final object to add to the scene
  24241. * const curveObject = new THREE.Line( geometry, material );
  24242. * ```
  24243. *
  24244. * @augments Curve
  24245. */
  24246. class QuadraticBezierCurve extends Curve {
  24247. /**
  24248. * Constructs a new Quadratic Bezier curve.
  24249. *
  24250. * @param {Vector2} [v0] - The start point.
  24251. * @param {Vector2} [v1] - The control point.
  24252. * @param {Vector2} [v2] - The end point.
  24253. */
  24254. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24255. super();
  24256. /**
  24257. * This flag can be used for type testing.
  24258. *
  24259. * @type {boolean}
  24260. * @readonly
  24261. * @default true
  24262. */
  24263. this.isQuadraticBezierCurve = true;
  24264. this.type = 'QuadraticBezierCurve';
  24265. /**
  24266. * The start point.
  24267. *
  24268. * @type {Vector2}
  24269. */
  24270. this.v0 = v0;
  24271. /**
  24272. * The control point.
  24273. *
  24274. * @type {Vector2}
  24275. */
  24276. this.v1 = v1;
  24277. /**
  24278. * The end point.
  24279. *
  24280. * @type {Vector2}
  24281. */
  24282. this.v2 = v2;
  24283. }
  24284. /**
  24285. * Returns a point on the curve.
  24286. *
  24287. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24288. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24289. * @return {Vector2} The position on the curve.
  24290. */
  24291. getPoint( t, optionalTarget = new Vector2() ) {
  24292. const point = optionalTarget;
  24293. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24294. point.set(
  24295. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24296. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24297. );
  24298. return point;
  24299. }
  24300. copy( source ) {
  24301. super.copy( source );
  24302. this.v0.copy( source.v0 );
  24303. this.v1.copy( source.v1 );
  24304. this.v2.copy( source.v2 );
  24305. return this;
  24306. }
  24307. toJSON() {
  24308. const data = super.toJSON();
  24309. data.v0 = this.v0.toArray();
  24310. data.v1 = this.v1.toArray();
  24311. data.v2 = this.v2.toArray();
  24312. return data;
  24313. }
  24314. fromJSON( json ) {
  24315. super.fromJSON( json );
  24316. this.v0.fromArray( json.v0 );
  24317. this.v1.fromArray( json.v1 );
  24318. this.v2.fromArray( json.v2 );
  24319. return this;
  24320. }
  24321. }
  24322. /**
  24323. * A curve representing a 3D Quadratic Bezier curve.
  24324. *
  24325. * @augments Curve
  24326. */
  24327. class QuadraticBezierCurve3 extends Curve {
  24328. /**
  24329. * Constructs a new Quadratic Bezier curve.
  24330. *
  24331. * @param {Vector3} [v0] - The start point.
  24332. * @param {Vector3} [v1] - The control point.
  24333. * @param {Vector3} [v2] - The end point.
  24334. */
  24335. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24336. super();
  24337. /**
  24338. * This flag can be used for type testing.
  24339. *
  24340. * @type {boolean}
  24341. * @readonly
  24342. * @default true
  24343. */
  24344. this.isQuadraticBezierCurve3 = true;
  24345. this.type = 'QuadraticBezierCurve3';
  24346. /**
  24347. * The start point.
  24348. *
  24349. * @type {Vector3}
  24350. */
  24351. this.v0 = v0;
  24352. /**
  24353. * The control point.
  24354. *
  24355. * @type {Vector3}
  24356. */
  24357. this.v1 = v1;
  24358. /**
  24359. * The end point.
  24360. *
  24361. * @type {Vector3}
  24362. */
  24363. this.v2 = v2;
  24364. }
  24365. /**
  24366. * Returns a point on the curve.
  24367. *
  24368. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24369. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24370. * @return {Vector3} The position on the curve.
  24371. */
  24372. getPoint( t, optionalTarget = new Vector3() ) {
  24373. const point = optionalTarget;
  24374. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24375. point.set(
  24376. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24377. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24378. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24379. );
  24380. return point;
  24381. }
  24382. copy( source ) {
  24383. super.copy( source );
  24384. this.v0.copy( source.v0 );
  24385. this.v1.copy( source.v1 );
  24386. this.v2.copy( source.v2 );
  24387. return this;
  24388. }
  24389. toJSON() {
  24390. const data = super.toJSON();
  24391. data.v0 = this.v0.toArray();
  24392. data.v1 = this.v1.toArray();
  24393. data.v2 = this.v2.toArray();
  24394. return data;
  24395. }
  24396. fromJSON( json ) {
  24397. super.fromJSON( json );
  24398. this.v0.fromArray( json.v0 );
  24399. this.v1.fromArray( json.v1 );
  24400. this.v2.fromArray( json.v2 );
  24401. return this;
  24402. }
  24403. }
  24404. /**
  24405. * A curve representing a 2D spline curve.
  24406. *
  24407. * ```js
  24408. * // Create a sine-like wave
  24409. * const curve = new THREE.SplineCurve( [
  24410. * new THREE.Vector2( -10, 0 ),
  24411. * new THREE.Vector2( -5, 5 ),
  24412. * new THREE.Vector2( 0, 0 ),
  24413. * new THREE.Vector2( 5, -5 ),
  24414. * new THREE.Vector2( 10, 0 )
  24415. * ] );
  24416. *
  24417. * const points = curve.getPoints( 50 );
  24418. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24419. *
  24420. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24421. *
  24422. * // Create the final object to add to the scene
  24423. * const splineObject = new THREE.Line( geometry, material );
  24424. * ```
  24425. *
  24426. * @augments Curve
  24427. */
  24428. class SplineCurve extends Curve {
  24429. /**
  24430. * Constructs a new 2D spline curve.
  24431. *
  24432. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24433. */
  24434. constructor( points = [] ) {
  24435. super();
  24436. /**
  24437. * This flag can be used for type testing.
  24438. *
  24439. * @type {boolean}
  24440. * @readonly
  24441. * @default true
  24442. */
  24443. this.isSplineCurve = true;
  24444. this.type = 'SplineCurve';
  24445. /**
  24446. * An array of 2D points defining the curve.
  24447. *
  24448. * @type {Array<Vector2>}
  24449. */
  24450. this.points = points;
  24451. }
  24452. /**
  24453. * Returns a point on the curve.
  24454. *
  24455. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24456. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24457. * @return {Vector2} The position on the curve.
  24458. */
  24459. getPoint( t, optionalTarget = new Vector2() ) {
  24460. const point = optionalTarget;
  24461. const points = this.points;
  24462. const p = ( points.length - 1 ) * t;
  24463. const intPoint = Math.floor( p );
  24464. const weight = p - intPoint;
  24465. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24466. const p1 = points[ intPoint ];
  24467. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24468. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24469. point.set(
  24470. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24471. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24472. );
  24473. return point;
  24474. }
  24475. copy( source ) {
  24476. super.copy( source );
  24477. this.points = [];
  24478. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24479. const point = source.points[ i ];
  24480. this.points.push( point.clone() );
  24481. }
  24482. return this;
  24483. }
  24484. toJSON() {
  24485. const data = super.toJSON();
  24486. data.points = [];
  24487. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24488. const point = this.points[ i ];
  24489. data.points.push( point.toArray() );
  24490. }
  24491. return data;
  24492. }
  24493. fromJSON( json ) {
  24494. super.fromJSON( json );
  24495. this.points = [];
  24496. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24497. const point = json.points[ i ];
  24498. this.points.push( new Vector2().fromArray( point ) );
  24499. }
  24500. return this;
  24501. }
  24502. }
  24503. var Curves = /*#__PURE__*/Object.freeze({
  24504. __proto__: null,
  24505. ArcCurve: ArcCurve,
  24506. CatmullRomCurve3: CatmullRomCurve3,
  24507. CubicBezierCurve: CubicBezierCurve,
  24508. CubicBezierCurve3: CubicBezierCurve3,
  24509. EllipseCurve: EllipseCurve,
  24510. LineCurve: LineCurve,
  24511. LineCurve3: LineCurve3,
  24512. QuadraticBezierCurve: QuadraticBezierCurve,
  24513. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24514. SplineCurve: SplineCurve
  24515. });
  24516. /**
  24517. * A base class extending {@link Curve}. `CurvePath` is simply an
  24518. * array of connected curves, but retains the API of a curve.
  24519. *
  24520. * @augments Curve
  24521. */
  24522. class CurvePath extends Curve {
  24523. /**
  24524. * Constructs a new curve path.
  24525. */
  24526. constructor() {
  24527. super();
  24528. this.type = 'CurvePath';
  24529. /**
  24530. * An array of curves defining the
  24531. * path.
  24532. *
  24533. * @type {Array<Curve>}
  24534. */
  24535. this.curves = [];
  24536. /**
  24537. * Whether the path should automatically be closed
  24538. * by a line curve.
  24539. *
  24540. * @type {boolean}
  24541. * @default false
  24542. */
  24543. this.autoClose = false;
  24544. }
  24545. /**
  24546. * Adds a curve to this curve path.
  24547. *
  24548. * @param {Curve} curve - The curve to add.
  24549. */
  24550. add( curve ) {
  24551. this.curves.push( curve );
  24552. }
  24553. /**
  24554. * Adds a line curve to close the path.
  24555. *
  24556. * @return {CurvePath} A reference to this curve path.
  24557. */
  24558. closePath() {
  24559. // Add a line curve if start and end of lines are not connected
  24560. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24561. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24562. if ( ! startPoint.equals( endPoint ) ) {
  24563. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24564. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24565. }
  24566. return this;
  24567. }
  24568. /**
  24569. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24570. * for the given interpolation factor.
  24571. *
  24572. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24573. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24574. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24575. */
  24576. getPoint( t, optionalTarget ) {
  24577. // To get accurate point with reference to
  24578. // entire path distance at time t,
  24579. // following has to be done:
  24580. // 1. Length of each sub path have to be known
  24581. // 2. Locate and identify type of curve
  24582. // 3. Get t for the curve
  24583. // 4. Return curve.getPointAt(t')
  24584. const d = t * this.getLength();
  24585. const curveLengths = this.getCurveLengths();
  24586. let i = 0;
  24587. // To think about boundaries points.
  24588. while ( i < curveLengths.length ) {
  24589. if ( curveLengths[ i ] >= d ) {
  24590. const diff = curveLengths[ i ] - d;
  24591. const curve = this.curves[ i ];
  24592. const segmentLength = curve.getLength();
  24593. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24594. return curve.getPointAt( u, optionalTarget );
  24595. }
  24596. i ++;
  24597. }
  24598. return null;
  24599. // loop where sum != 0, sum > d , sum+1 <d
  24600. }
  24601. getLength() {
  24602. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24603. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24604. // getPoint() depends on getLength
  24605. const lens = this.getCurveLengths();
  24606. return lens[ lens.length - 1 ];
  24607. }
  24608. updateArcLengths() {
  24609. // cacheLengths must be recalculated.
  24610. this.needsUpdate = true;
  24611. this.cacheLengths = null;
  24612. this.getCurveLengths();
  24613. }
  24614. /**
  24615. * Returns list of cumulative curve lengths of the defined curves.
  24616. *
  24617. * @return {Array<number>} The curve lengths.
  24618. */
  24619. getCurveLengths() {
  24620. // Compute lengths and cache them
  24621. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24622. // We use cache values if curves and cache array are same length
  24623. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24624. return this.cacheLengths;
  24625. }
  24626. // Get length of sub-curve
  24627. // Push sums into cached array
  24628. const lengths = [];
  24629. let sums = 0;
  24630. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24631. sums += this.curves[ i ].getLength();
  24632. lengths.push( sums );
  24633. }
  24634. this.cacheLengths = lengths;
  24635. return lengths;
  24636. }
  24637. getSpacedPoints( divisions = 40 ) {
  24638. const points = [];
  24639. for ( let i = 0; i <= divisions; i ++ ) {
  24640. points.push( this.getPoint( i / divisions ) );
  24641. }
  24642. if ( this.autoClose ) {
  24643. points.push( points[ 0 ] );
  24644. }
  24645. return points;
  24646. }
  24647. getPoints( divisions = 12 ) {
  24648. const points = [];
  24649. let last;
  24650. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24651. const curve = curves[ i ];
  24652. const resolution = curve.isEllipseCurve ? divisions * 2
  24653. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24654. : curve.isSplineCurve ? divisions * curve.points.length
  24655. : divisions;
  24656. const pts = curve.getPoints( resolution );
  24657. for ( let j = 0; j < pts.length; j ++ ) {
  24658. const point = pts[ j ];
  24659. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24660. points.push( point );
  24661. last = point;
  24662. }
  24663. }
  24664. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24665. points.push( points[ 0 ] );
  24666. }
  24667. return points;
  24668. }
  24669. copy( source ) {
  24670. super.copy( source );
  24671. this.curves = [];
  24672. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24673. const curve = source.curves[ i ];
  24674. this.curves.push( curve.clone() );
  24675. }
  24676. this.autoClose = source.autoClose;
  24677. return this;
  24678. }
  24679. toJSON() {
  24680. const data = super.toJSON();
  24681. data.autoClose = this.autoClose;
  24682. data.curves = [];
  24683. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24684. const curve = this.curves[ i ];
  24685. data.curves.push( curve.toJSON() );
  24686. }
  24687. return data;
  24688. }
  24689. fromJSON( json ) {
  24690. super.fromJSON( json );
  24691. this.autoClose = json.autoClose;
  24692. this.curves = [];
  24693. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24694. const curve = json.curves[ i ];
  24695. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24696. }
  24697. return this;
  24698. }
  24699. }
  24700. /**
  24701. * A 2D path representation. The class provides methods for creating paths
  24702. * and contours of 2D shapes similar to the 2D Canvas API.
  24703. *
  24704. * ```js
  24705. * const path = new THREE.Path();
  24706. *
  24707. * path.lineTo( 0, 0.8 );
  24708. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24709. * path.lineTo( 1, 1 );
  24710. *
  24711. * const points = path.getPoints();
  24712. *
  24713. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24714. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24715. *
  24716. * const line = new THREE.Line( geometry, material );
  24717. * scene.add( line );
  24718. * ```
  24719. *
  24720. * @augments CurvePath
  24721. */
  24722. class Path extends CurvePath {
  24723. /**
  24724. * Constructs a new path.
  24725. *
  24726. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24727. */
  24728. constructor( points ) {
  24729. super();
  24730. this.type = 'Path';
  24731. /**
  24732. * The current offset of the path. Any new curve added will start here.
  24733. *
  24734. * @type {Vector2}
  24735. */
  24736. this.currentPoint = new Vector2();
  24737. if ( points ) {
  24738. this.setFromPoints( points );
  24739. }
  24740. }
  24741. /**
  24742. * Creates a path from the given list of points. The points are added
  24743. * to the path as instances of {@link LineCurve}.
  24744. *
  24745. * @param {Array<Vector2>} points - An array of 2D points.
  24746. * @return {Path} A reference to this path.
  24747. */
  24748. setFromPoints( points ) {
  24749. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24750. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24751. this.lineTo( points[ i ].x, points[ i ].y );
  24752. }
  24753. return this;
  24754. }
  24755. /**
  24756. * Moves {@link Path#currentPoint} to the given point.
  24757. *
  24758. * @param {number} x - The x coordinate.
  24759. * @param {number} y - The y coordinate.
  24760. * @return {Path} A reference to this path.
  24761. */
  24762. moveTo( x, y ) {
  24763. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24764. return this;
  24765. }
  24766. /**
  24767. * Adds an instance of {@link LineCurve} to the path by connecting
  24768. * the current point with the given one.
  24769. *
  24770. * @param {number} x - The x coordinate of the end point.
  24771. * @param {number} y - The y coordinate of the end point.
  24772. * @return {Path} A reference to this path.
  24773. */
  24774. lineTo( x, y ) {
  24775. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24776. this.curves.push( curve );
  24777. this.currentPoint.set( x, y );
  24778. return this;
  24779. }
  24780. /**
  24781. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24782. * the current point with the given one.
  24783. *
  24784. * @param {number} aCPx - The x coordinate of the control point.
  24785. * @param {number} aCPy - The y coordinate of the control point.
  24786. * @param {number} aX - The x coordinate of the end point.
  24787. * @param {number} aY - The y coordinate of the end point.
  24788. * @return {Path} A reference to this path.
  24789. */
  24790. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24791. const curve = new QuadraticBezierCurve(
  24792. this.currentPoint.clone(),
  24793. new Vector2( aCPx, aCPy ),
  24794. new Vector2( aX, aY )
  24795. );
  24796. this.curves.push( curve );
  24797. this.currentPoint.set( aX, aY );
  24798. return this;
  24799. }
  24800. /**
  24801. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24802. * the current point with the given one.
  24803. *
  24804. * @param {number} aCP1x - The x coordinate of the first control point.
  24805. * @param {number} aCP1y - The y coordinate of the first control point.
  24806. * @param {number} aCP2x - The x coordinate of the second control point.
  24807. * @param {number} aCP2y - The y coordinate of the second control point.
  24808. * @param {number} aX - The x coordinate of the end point.
  24809. * @param {number} aY - The y coordinate of the end point.
  24810. * @return {Path} A reference to this path.
  24811. */
  24812. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24813. const curve = new CubicBezierCurve(
  24814. this.currentPoint.clone(),
  24815. new Vector2( aCP1x, aCP1y ),
  24816. new Vector2( aCP2x, aCP2y ),
  24817. new Vector2( aX, aY )
  24818. );
  24819. this.curves.push( curve );
  24820. this.currentPoint.set( aX, aY );
  24821. return this;
  24822. }
  24823. /**
  24824. * Adds an instance of {@link SplineCurve} to the path by connecting
  24825. * the current point with the given list of points.
  24826. *
  24827. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24828. * @return {Path} A reference to this path.
  24829. */
  24830. splineThru( pts ) {
  24831. const npts = [ this.currentPoint.clone() ].concat( pts );
  24832. const curve = new SplineCurve( npts );
  24833. this.curves.push( curve );
  24834. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24835. return this;
  24836. }
  24837. /**
  24838. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24839. * to the current point.
  24840. *
  24841. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24842. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24843. * @param {number} [aRadius=1] - The radius of the arc.
  24844. * @param {number} [aStartAngle=0] - The start angle in radians.
  24845. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24846. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24847. * @return {Path} A reference to this path.
  24848. */
  24849. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24850. const x0 = this.currentPoint.x;
  24851. const y0 = this.currentPoint.y;
  24852. this.absarc( aX + x0, aY + y0, aRadius,
  24853. aStartAngle, aEndAngle, aClockwise );
  24854. return this;
  24855. }
  24856. /**
  24857. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24858. *
  24859. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24860. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24861. * @param {number} [aRadius=1] - The radius of the arc.
  24862. * @param {number} [aStartAngle=0] - The start angle in radians.
  24863. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24864. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24865. * @return {Path} A reference to this path.
  24866. */
  24867. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24868. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24869. return this;
  24870. }
  24871. /**
  24872. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24873. * to the current point
  24874. *
  24875. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24876. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24877. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24878. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24879. * @param {number} [aStartAngle=0] - The start angle in radians.
  24880. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24881. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24882. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24883. * @return {Path} A reference to this path.
  24884. */
  24885. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24886. const x0 = this.currentPoint.x;
  24887. const y0 = this.currentPoint.y;
  24888. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24889. return this;
  24890. }
  24891. /**
  24892. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24893. *
  24894. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24895. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  24896. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24897. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24898. * @param {number} [aStartAngle=0] - The start angle in radians.
  24899. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24900. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24901. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24902. * @return {Path} A reference to this path.
  24903. */
  24904. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24905. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24906. if ( this.curves.length > 0 ) {
  24907. // if a previous curve is present, attempt to join
  24908. const firstPoint = curve.getPoint( 0 );
  24909. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24910. this.lineTo( firstPoint.x, firstPoint.y );
  24911. }
  24912. }
  24913. this.curves.push( curve );
  24914. const lastPoint = curve.getPoint( 1 );
  24915. this.currentPoint.copy( lastPoint );
  24916. return this;
  24917. }
  24918. copy( source ) {
  24919. super.copy( source );
  24920. this.currentPoint.copy( source.currentPoint );
  24921. return this;
  24922. }
  24923. toJSON() {
  24924. const data = super.toJSON();
  24925. data.currentPoint = this.currentPoint.toArray();
  24926. return data;
  24927. }
  24928. fromJSON( json ) {
  24929. super.fromJSON( json );
  24930. this.currentPoint.fromArray( json.currentPoint );
  24931. return this;
  24932. }
  24933. }
  24934. /**
  24935. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  24936. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  24937. * points, or to get triangulated faces.
  24938. *
  24939. * ```js
  24940. * const heartShape = new THREE.Shape();
  24941. *
  24942. * heartShape.moveTo( 25, 25 );
  24943. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  24944. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  24945. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  24946. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  24947. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  24948. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  24949. *
  24950. * const extrudeSettings = {
  24951. * depth: 8,
  24952. * bevelEnabled: true,
  24953. * bevelSegments: 2,
  24954. * steps: 2,
  24955. * bevelSize: 1,
  24956. * bevelThickness: 1
  24957. * };
  24958. *
  24959. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  24960. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  24961. * ```
  24962. *
  24963. * @augments Path
  24964. */
  24965. class Shape extends Path {
  24966. /**
  24967. * Constructs a new shape.
  24968. *
  24969. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  24970. */
  24971. constructor( points ) {
  24972. super( points );
  24973. /**
  24974. * The UUID of the shape.
  24975. *
  24976. * @type {string}
  24977. * @readonly
  24978. */
  24979. this.uuid = generateUUID();
  24980. this.type = 'Shape';
  24981. /**
  24982. * Defines the holes in the shape. Hole definitions must use the
  24983. * opposite winding order (CW/CCW) than the outer shape.
  24984. *
  24985. * @type {Array<Path>}
  24986. * @readonly
  24987. */
  24988. this.holes = [];
  24989. }
  24990. /**
  24991. * Returns an array representing each contour of the holes
  24992. * as a list of 2D points.
  24993. *
  24994. * @param {number} divisions - The fineness of the result.
  24995. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  24996. */
  24997. getPointsHoles( divisions ) {
  24998. const holesPts = [];
  24999. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25000. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25001. }
  25002. return holesPts;
  25003. }
  25004. // get points of shape and holes (keypoints based on segments parameter)
  25005. /**
  25006. * Returns an object that holds contour data for the shape and its holes as
  25007. * arrays of 2D points.
  25008. *
  25009. * @param {number} divisions - The fineness of the result.
  25010. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25011. */
  25012. extractPoints( divisions ) {
  25013. return {
  25014. shape: this.getPoints( divisions ),
  25015. holes: this.getPointsHoles( divisions )
  25016. };
  25017. }
  25018. copy( source ) {
  25019. super.copy( source );
  25020. this.holes = [];
  25021. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25022. const hole = source.holes[ i ];
  25023. this.holes.push( hole.clone() );
  25024. }
  25025. return this;
  25026. }
  25027. toJSON() {
  25028. const data = super.toJSON();
  25029. data.uuid = this.uuid;
  25030. data.holes = [];
  25031. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25032. const hole = this.holes[ i ];
  25033. data.holes.push( hole.toJSON() );
  25034. }
  25035. return data;
  25036. }
  25037. fromJSON( json ) {
  25038. super.fromJSON( json );
  25039. this.uuid = json.uuid;
  25040. this.holes = [];
  25041. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25042. const hole = json.holes[ i ];
  25043. this.holes.push( new Path().fromJSON( hole ) );
  25044. }
  25045. return this;
  25046. }
  25047. }
  25048. /* eslint-disable */
  25049. // copy of mapbox/earcut version 3.0.1
  25050. // https://github.com/mapbox/earcut/tree/v3.0.1
  25051. function earcut(data, holeIndices, dim = 2) {
  25052. const hasHoles = holeIndices && holeIndices.length;
  25053. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25054. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25055. const triangles = [];
  25056. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25057. let minX, minY, invSize;
  25058. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25059. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25060. if (data.length > 80 * dim) {
  25061. minX = Infinity;
  25062. minY = Infinity;
  25063. let maxX = -Infinity;
  25064. let maxY = -Infinity;
  25065. for (let i = dim; i < outerLen; i += dim) {
  25066. const x = data[i];
  25067. const y = data[i + 1];
  25068. if (x < minX) minX = x;
  25069. if (y < minY) minY = y;
  25070. if (x > maxX) maxX = x;
  25071. if (y > maxY) maxY = y;
  25072. }
  25073. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25074. invSize = Math.max(maxX - minX, maxY - minY);
  25075. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25076. }
  25077. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25078. return triangles;
  25079. }
  25080. // create a circular doubly linked list from polygon points in the specified winding order
  25081. function linkedList(data, start, end, dim, clockwise) {
  25082. let last;
  25083. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25084. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25085. } else {
  25086. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25087. }
  25088. if (last && equals(last, last.next)) {
  25089. removeNode(last);
  25090. last = last.next;
  25091. }
  25092. return last;
  25093. }
  25094. // eliminate colinear or duplicate points
  25095. function filterPoints(start, end) {
  25096. if (!start) return start;
  25097. if (!end) end = start;
  25098. let p = start,
  25099. again;
  25100. do {
  25101. again = false;
  25102. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25103. removeNode(p);
  25104. p = end = p.prev;
  25105. if (p === p.next) break;
  25106. again = true;
  25107. } else {
  25108. p = p.next;
  25109. }
  25110. } while (again || p !== end);
  25111. return end;
  25112. }
  25113. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25114. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25115. if (!ear) return;
  25116. // interlink polygon nodes in z-order
  25117. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25118. let stop = ear;
  25119. // iterate through ears, slicing them one by one
  25120. while (ear.prev !== ear.next) {
  25121. const prev = ear.prev;
  25122. const next = ear.next;
  25123. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25124. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25125. removeNode(ear);
  25126. // skipping the next vertex leads to less sliver triangles
  25127. ear = next.next;
  25128. stop = next.next;
  25129. continue;
  25130. }
  25131. ear = next;
  25132. // if we looped through the whole remaining polygon and can't find any more ears
  25133. if (ear === stop) {
  25134. // try filtering points and slicing again
  25135. if (!pass) {
  25136. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25137. // if this didn't work, try curing all small self-intersections locally
  25138. } else if (pass === 1) {
  25139. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25140. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25141. // as a last resort, try splitting the remaining polygon into two
  25142. } else if (pass === 2) {
  25143. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25144. }
  25145. break;
  25146. }
  25147. }
  25148. }
  25149. // check whether a polygon node forms a valid ear with adjacent nodes
  25150. function isEar(ear) {
  25151. const a = ear.prev,
  25152. b = ear,
  25153. c = ear.next;
  25154. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25155. // now make sure we don't have other points inside the potential ear
  25156. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25157. // triangle bbox
  25158. const x0 = Math.min(ax, bx, cx),
  25159. y0 = Math.min(ay, by, cy),
  25160. x1 = Math.max(ax, bx, cx),
  25161. y1 = Math.max(ay, by, cy);
  25162. let p = c.next;
  25163. while (p !== a) {
  25164. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25165. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25166. area(p.prev, p, p.next) >= 0) return false;
  25167. p = p.next;
  25168. }
  25169. return true;
  25170. }
  25171. function isEarHashed(ear, minX, minY, invSize) {
  25172. const a = ear.prev,
  25173. b = ear,
  25174. c = ear.next;
  25175. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25176. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25177. // triangle bbox
  25178. const x0 = Math.min(ax, bx, cx),
  25179. y0 = Math.min(ay, by, cy),
  25180. x1 = Math.max(ax, bx, cx),
  25181. y1 = Math.max(ay, by, cy);
  25182. // z-order range for the current triangle bbox;
  25183. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25184. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25185. let p = ear.prevZ,
  25186. n = ear.nextZ;
  25187. // look for points inside the triangle in both directions
  25188. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25189. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25190. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25191. p = p.prevZ;
  25192. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25193. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25194. n = n.nextZ;
  25195. }
  25196. // look for remaining points in decreasing z-order
  25197. while (p && p.z >= minZ) {
  25198. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25199. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25200. p = p.prevZ;
  25201. }
  25202. // look for remaining points in increasing z-order
  25203. while (n && n.z <= maxZ) {
  25204. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25205. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25206. n = n.nextZ;
  25207. }
  25208. return true;
  25209. }
  25210. // go through all polygon nodes and cure small local self-intersections
  25211. function cureLocalIntersections(start, triangles) {
  25212. let p = start;
  25213. do {
  25214. const a = p.prev,
  25215. b = p.next.next;
  25216. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25217. triangles.push(a.i, p.i, b.i);
  25218. // remove two nodes involved
  25219. removeNode(p);
  25220. removeNode(p.next);
  25221. p = start = b;
  25222. }
  25223. p = p.next;
  25224. } while (p !== start);
  25225. return filterPoints(p);
  25226. }
  25227. // try splitting polygon into two and triangulate them independently
  25228. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25229. // look for a valid diagonal that divides the polygon into two
  25230. let a = start;
  25231. do {
  25232. let b = a.next.next;
  25233. while (b !== a.prev) {
  25234. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25235. // split the polygon in two by the diagonal
  25236. let c = splitPolygon(a, b);
  25237. // filter colinear points around the cuts
  25238. a = filterPoints(a, a.next);
  25239. c = filterPoints(c, c.next);
  25240. // run earcut on each half
  25241. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25242. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25243. return;
  25244. }
  25245. b = b.next;
  25246. }
  25247. a = a.next;
  25248. } while (a !== start);
  25249. }
  25250. // link every hole into the outer loop, producing a single-ring polygon without holes
  25251. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25252. const queue = [];
  25253. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25254. const start = holeIndices[i] * dim;
  25255. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25256. const list = linkedList(data, start, end, dim, false);
  25257. if (list === list.next) list.steiner = true;
  25258. queue.push(getLeftmost(list));
  25259. }
  25260. queue.sort(compareXYSlope);
  25261. // process holes from left to right
  25262. for (let i = 0; i < queue.length; i++) {
  25263. outerNode = eliminateHole(queue[i], outerNode);
  25264. }
  25265. return outerNode;
  25266. }
  25267. function compareXYSlope(a, b) {
  25268. let result = a.x - b.x;
  25269. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25270. // the bridge to the outer shell is always the point that they meet at.
  25271. if (result === 0) {
  25272. result = a.y - b.y;
  25273. if (result === 0) {
  25274. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25275. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25276. result = aSlope - bSlope;
  25277. }
  25278. }
  25279. return result;
  25280. }
  25281. // find a bridge between vertices that connects hole with an outer ring and and link it
  25282. function eliminateHole(hole, outerNode) {
  25283. const bridge = findHoleBridge(hole, outerNode);
  25284. if (!bridge) {
  25285. return outerNode;
  25286. }
  25287. const bridgeReverse = splitPolygon(bridge, hole);
  25288. // filter collinear points around the cuts
  25289. filterPoints(bridgeReverse, bridgeReverse.next);
  25290. return filterPoints(bridge, bridge.next);
  25291. }
  25292. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25293. function findHoleBridge(hole, outerNode) {
  25294. let p = outerNode;
  25295. const hx = hole.x;
  25296. const hy = hole.y;
  25297. let qx = -Infinity;
  25298. let m;
  25299. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25300. // segment's endpoint with lesser x will be potential connection point
  25301. // unless they intersect at a vertex, then choose the vertex
  25302. if (equals(hole, p)) return p;
  25303. do {
  25304. if (equals(hole, p.next)) return p.next;
  25305. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25306. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25307. if (x <= hx && x > qx) {
  25308. qx = x;
  25309. m = p.x < p.next.x ? p : p.next;
  25310. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25311. }
  25312. }
  25313. p = p.next;
  25314. } while (p !== outerNode);
  25315. if (!m) return null;
  25316. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25317. // if there are no points found, we have a valid connection;
  25318. // otherwise choose the point of the minimum angle with the ray as connection point
  25319. const stop = m;
  25320. const mx = m.x;
  25321. const my = m.y;
  25322. let tanMin = Infinity;
  25323. p = m;
  25324. do {
  25325. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25326. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25327. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25328. if (locallyInside(p, hole) &&
  25329. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25330. m = p;
  25331. tanMin = tan;
  25332. }
  25333. }
  25334. p = p.next;
  25335. } while (p !== stop);
  25336. return m;
  25337. }
  25338. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25339. function sectorContainsSector(m, p) {
  25340. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25341. }
  25342. // interlink polygon nodes in z-order
  25343. function indexCurve(start, minX, minY, invSize) {
  25344. let p = start;
  25345. do {
  25346. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25347. p.prevZ = p.prev;
  25348. p.nextZ = p.next;
  25349. p = p.next;
  25350. } while (p !== start);
  25351. p.prevZ.nextZ = null;
  25352. p.prevZ = null;
  25353. sortLinked(p);
  25354. }
  25355. // Simon Tatham's linked list merge sort algorithm
  25356. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25357. function sortLinked(list) {
  25358. let numMerges;
  25359. let inSize = 1;
  25360. do {
  25361. let p = list;
  25362. let e;
  25363. list = null;
  25364. let tail = null;
  25365. numMerges = 0;
  25366. while (p) {
  25367. numMerges++;
  25368. let q = p;
  25369. let pSize = 0;
  25370. for (let i = 0; i < inSize; i++) {
  25371. pSize++;
  25372. q = q.nextZ;
  25373. if (!q) break;
  25374. }
  25375. let qSize = inSize;
  25376. while (pSize > 0 || (qSize > 0 && q)) {
  25377. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25378. e = p;
  25379. p = p.nextZ;
  25380. pSize--;
  25381. } else {
  25382. e = q;
  25383. q = q.nextZ;
  25384. qSize--;
  25385. }
  25386. if (tail) tail.nextZ = e;
  25387. else list = e;
  25388. e.prevZ = tail;
  25389. tail = e;
  25390. }
  25391. p = q;
  25392. }
  25393. tail.nextZ = null;
  25394. inSize *= 2;
  25395. } while (numMerges > 1);
  25396. return list;
  25397. }
  25398. // z-order of a point given coords and inverse of the longer side of data bbox
  25399. function zOrder(x, y, minX, minY, invSize) {
  25400. // coords are transformed into non-negative 15-bit integer range
  25401. x = (x - minX) * invSize | 0;
  25402. y = (y - minY) * invSize | 0;
  25403. x = (x | (x << 8)) & 0x00FF00FF;
  25404. x = (x | (x << 4)) & 0x0F0F0F0F;
  25405. x = (x | (x << 2)) & 0x33333333;
  25406. x = (x | (x << 1)) & 0x55555555;
  25407. y = (y | (y << 8)) & 0x00FF00FF;
  25408. y = (y | (y << 4)) & 0x0F0F0F0F;
  25409. y = (y | (y << 2)) & 0x33333333;
  25410. y = (y | (y << 1)) & 0x55555555;
  25411. return x | (y << 1);
  25412. }
  25413. // find the leftmost node of a polygon ring
  25414. function getLeftmost(start) {
  25415. let p = start,
  25416. leftmost = start;
  25417. do {
  25418. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25419. p = p.next;
  25420. } while (p !== start);
  25421. return leftmost;
  25422. }
  25423. // check if a point lies within a convex triangle
  25424. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25425. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25426. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25427. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25428. }
  25429. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25430. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25431. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25432. }
  25433. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25434. function isValidDiagonal(a, b) {
  25435. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  25436. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25437. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25438. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25439. }
  25440. // signed area of a triangle
  25441. function area(p, q, r) {
  25442. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25443. }
  25444. // check if two points are equal
  25445. function equals(p1, p2) {
  25446. return p1.x === p2.x && p1.y === p2.y;
  25447. }
  25448. // check if two segments intersect
  25449. function intersects(p1, q1, p2, q2) {
  25450. const o1 = sign(area(p1, q1, p2));
  25451. const o2 = sign(area(p1, q1, q2));
  25452. const o3 = sign(area(p2, q2, p1));
  25453. const o4 = sign(area(p2, q2, q1));
  25454. if (o1 !== o2 && o3 !== o4) return true; // general case
  25455. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25456. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25457. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25458. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25459. return false;
  25460. }
  25461. // for collinear points p, q, r, check if point q lies on segment pr
  25462. function onSegment(p, q, r) {
  25463. 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);
  25464. }
  25465. function sign(num) {
  25466. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25467. }
  25468. // check if a polygon diagonal intersects any polygon segments
  25469. function intersectsPolygon(a, b) {
  25470. let p = a;
  25471. do {
  25472. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25473. intersects(p, p.next, a, b)) return true;
  25474. p = p.next;
  25475. } while (p !== a);
  25476. return false;
  25477. }
  25478. // check if a polygon diagonal is locally inside the polygon
  25479. function locallyInside(a, b) {
  25480. return area(a.prev, a, a.next) < 0 ?
  25481. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25482. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25483. }
  25484. // check if the middle point of a polygon diagonal is inside the polygon
  25485. function middleInside(a, b) {
  25486. let p = a;
  25487. let inside = false;
  25488. const px = (a.x + b.x) / 2;
  25489. const py = (a.y + b.y) / 2;
  25490. do {
  25491. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25492. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25493. inside = !inside;
  25494. p = p.next;
  25495. } while (p !== a);
  25496. return inside;
  25497. }
  25498. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25499. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25500. function splitPolygon(a, b) {
  25501. const a2 = createNode(a.i, a.x, a.y),
  25502. b2 = createNode(b.i, b.x, b.y),
  25503. an = a.next,
  25504. bp = b.prev;
  25505. a.next = b;
  25506. b.prev = a;
  25507. a2.next = an;
  25508. an.prev = a2;
  25509. b2.next = a2;
  25510. a2.prev = b2;
  25511. bp.next = b2;
  25512. b2.prev = bp;
  25513. return b2;
  25514. }
  25515. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25516. function insertNode(i, x, y, last) {
  25517. const p = createNode(i, x, y);
  25518. if (!last) {
  25519. p.prev = p;
  25520. p.next = p;
  25521. } else {
  25522. p.next = last.next;
  25523. p.prev = last;
  25524. last.next.prev = p;
  25525. last.next = p;
  25526. }
  25527. return p;
  25528. }
  25529. function removeNode(p) {
  25530. p.next.prev = p.prev;
  25531. p.prev.next = p.next;
  25532. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25533. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25534. }
  25535. function createNode(i, x, y) {
  25536. return {
  25537. i, // vertex index in coordinates array
  25538. x, y, // vertex coordinates
  25539. prev: null, // previous and next vertex nodes in a polygon ring
  25540. next: null,
  25541. z: 0, // z-order curve value
  25542. prevZ: null, // previous and next nodes in z-order
  25543. nextZ: null,
  25544. steiner: false // indicates whether this is a steiner point
  25545. };
  25546. }
  25547. function signedArea(data, start, end, dim) {
  25548. let sum = 0;
  25549. for (let i = start, j = end - dim; i < end; i += dim) {
  25550. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25551. j = i;
  25552. }
  25553. return sum;
  25554. }
  25555. class Earcut {
  25556. /**
  25557. * Triangulates the given shape definition by returning an array of triangles.
  25558. *
  25559. * @param {Array<number>} data - An array with 2D points.
  25560. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25561. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25562. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25563. * representing vertex indices.
  25564. */
  25565. static triangulate( data, holeIndices, dim = 2 ) {
  25566. return earcut( data, holeIndices, dim );
  25567. }
  25568. }
  25569. /**
  25570. * A class containing utility functions for shapes.
  25571. *
  25572. * @hideconstructor
  25573. */
  25574. class ShapeUtils {
  25575. /**
  25576. * Calculate area of a ( 2D ) contour polygon.
  25577. *
  25578. * @param {Array<Vector2>} contour - An array of 2D points.
  25579. * @return {number} The area.
  25580. */
  25581. static area( contour ) {
  25582. const n = contour.length;
  25583. let a = 0.0;
  25584. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25585. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25586. }
  25587. return a * 0.5;
  25588. }
  25589. /**
  25590. * Returns `true` if the given contour uses a clockwise winding order.
  25591. *
  25592. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25593. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25594. */
  25595. static isClockWise( pts ) {
  25596. return ShapeUtils.area( pts ) < 0;
  25597. }
  25598. /**
  25599. * Triangulates the given shape definition.
  25600. *
  25601. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25602. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25603. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25604. */
  25605. static triangulateShape( contour, holes ) {
  25606. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25607. const holeIndices = []; // array of hole indices
  25608. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25609. removeDupEndPts( contour );
  25610. addContour( vertices, contour );
  25611. //
  25612. let holeIndex = contour.length;
  25613. holes.forEach( removeDupEndPts );
  25614. for ( let i = 0; i < holes.length; i ++ ) {
  25615. holeIndices.push( holeIndex );
  25616. holeIndex += holes[ i ].length;
  25617. addContour( vertices, holes[ i ] );
  25618. }
  25619. //
  25620. const triangles = Earcut.triangulate( vertices, holeIndices );
  25621. //
  25622. for ( let i = 0; i < triangles.length; i += 3 ) {
  25623. faces.push( triangles.slice( i, i + 3 ) );
  25624. }
  25625. return faces;
  25626. }
  25627. }
  25628. function removeDupEndPts( points ) {
  25629. const l = points.length;
  25630. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25631. points.pop();
  25632. }
  25633. }
  25634. function addContour( vertices, contour ) {
  25635. for ( let i = 0; i < contour.length; i ++ ) {
  25636. vertices.push( contour[ i ].x );
  25637. vertices.push( contour[ i ].y );
  25638. }
  25639. }
  25640. /**
  25641. * Creates extruded geometry from a path shape.
  25642. *
  25643. * ```js
  25644. * const length = 12, width = 8;
  25645. *
  25646. * const shape = new THREE.Shape();
  25647. * shape.moveTo( 0,0 );
  25648. * shape.lineTo( 0, width );
  25649. * shape.lineTo( length, width );
  25650. * shape.lineTo( length, 0 );
  25651. * shape.lineTo( 0, 0 );
  25652. *
  25653. * const geometry = new THREE.ExtrudeGeometry( shape );
  25654. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25655. * const mesh = new THREE.Mesh( geometry, material ) ;
  25656. * scene.add( mesh );
  25657. * ```
  25658. *
  25659. * @augments BufferGeometry
  25660. */
  25661. class ExtrudeGeometry extends BufferGeometry {
  25662. /**
  25663. * Constructs a new extrude geometry.
  25664. *
  25665. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25666. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25667. */
  25668. 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 = {} ) {
  25669. super();
  25670. this.type = 'ExtrudeGeometry';
  25671. /**
  25672. * Holds the constructor parameters that have been
  25673. * used to generate the geometry. Any modification
  25674. * after instantiation does not change the geometry.
  25675. *
  25676. * @type {Object}
  25677. */
  25678. this.parameters = {
  25679. shapes: shapes,
  25680. options: options
  25681. };
  25682. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25683. const scope = this;
  25684. const verticesArray = [];
  25685. const uvArray = [];
  25686. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25687. const shape = shapes[ i ];
  25688. addShape( shape );
  25689. }
  25690. // build geometry
  25691. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25692. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25693. this.computeVertexNormals();
  25694. // functions
  25695. function addShape( shape ) {
  25696. const placeholder = [];
  25697. // options
  25698. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25699. const steps = options.steps !== undefined ? options.steps : 1;
  25700. const depth = options.depth !== undefined ? options.depth : 1;
  25701. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25702. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25703. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25704. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25705. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25706. const extrudePath = options.extrudePath;
  25707. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25708. //
  25709. let extrudePts, extrudeByPath = false;
  25710. let splineTube, binormal, normal, position2;
  25711. if ( extrudePath ) {
  25712. extrudePts = extrudePath.getSpacedPoints( steps );
  25713. extrudeByPath = true;
  25714. bevelEnabled = false; // bevels not supported for path extrusion
  25715. // SETUP TNB variables
  25716. // TODO1 - have a .isClosed in spline?
  25717. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25718. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25719. binormal = new Vector3();
  25720. normal = new Vector3();
  25721. position2 = new Vector3();
  25722. }
  25723. // Safeguards if bevels are not enabled
  25724. if ( ! bevelEnabled ) {
  25725. bevelSegments = 0;
  25726. bevelThickness = 0;
  25727. bevelSize = 0;
  25728. bevelOffset = 0;
  25729. }
  25730. // Variables initialization
  25731. const shapePoints = shape.extractPoints( curveSegments );
  25732. let vertices = shapePoints.shape;
  25733. const holes = shapePoints.holes;
  25734. const reverse = ! ShapeUtils.isClockWise( vertices );
  25735. if ( reverse ) {
  25736. vertices = vertices.reverse();
  25737. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25738. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25739. const ahole = holes[ h ];
  25740. if ( ShapeUtils.isClockWise( ahole ) ) {
  25741. holes[ h ] = ahole.reverse();
  25742. }
  25743. }
  25744. }
  25745. /**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.
  25746. * @param {Array<Vector2>} points
  25747. */
  25748. function mergeOverlappingPoints( points ) {
  25749. const THRESHOLD = 1e-10;
  25750. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25751. let prevPos = points[ 0 ];
  25752. for ( let i = 1; i <= points.length; i ++ ) {
  25753. const currentIndex = i % points.length;
  25754. const currentPos = points[ currentIndex ];
  25755. const dx = currentPos.x - prevPos.x;
  25756. const dy = currentPos.y - prevPos.y;
  25757. const distSq = dx * dx + dy * dy;
  25758. const scalingFactorSqrt = Math.max(
  25759. Math.abs( currentPos.x ),
  25760. Math.abs( currentPos.y ),
  25761. Math.abs( prevPos.x ),
  25762. Math.abs( prevPos.y )
  25763. );
  25764. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25765. if ( distSq <= thresholdSqScaled ) {
  25766. points.splice( currentIndex, 1 );
  25767. i --;
  25768. continue;
  25769. }
  25770. prevPos = currentPos;
  25771. }
  25772. }
  25773. mergeOverlappingPoints( vertices );
  25774. holes.forEach( mergeOverlappingPoints );
  25775. const numHoles = holes.length;
  25776. /* Vertices */
  25777. const contour = vertices; // vertices has all points but contour has only points of circumference
  25778. for ( let h = 0; h < numHoles; h ++ ) {
  25779. const ahole = holes[ h ];
  25780. vertices = vertices.concat( ahole );
  25781. }
  25782. function scalePt2( pt, vec, size ) {
  25783. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  25784. return pt.clone().addScaledVector( vec, size );
  25785. }
  25786. const vlen = vertices.length;
  25787. // Find directions for point movement
  25788. function getBevelVec( inPt, inPrev, inNext ) {
  25789. // computes for inPt the corresponding point inPt' on a new contour
  25790. // shifted by 1 unit (length of normalized vector) to the left
  25791. // if we walk along contour clockwise, this new contour is outside the old one
  25792. //
  25793. // inPt' is the intersection of the two lines parallel to the two
  25794. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25795. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25796. // good reading for geometry algorithms (here: line-line intersection)
  25797. // http://geomalgorithms.com/a05-_intersect-1.html
  25798. const v_prev_x = inPt.x - inPrev.x,
  25799. v_prev_y = inPt.y - inPrev.y;
  25800. const v_next_x = inNext.x - inPt.x,
  25801. v_next_y = inNext.y - inPt.y;
  25802. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25803. // check for collinear edges
  25804. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25805. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25806. // not collinear
  25807. // length of vectors for normalizing
  25808. const v_prev_len = Math.sqrt( v_prev_lensq );
  25809. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25810. // shift adjacent points by unit vectors to the left
  25811. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25812. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25813. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25814. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25815. // scaling factor for v_prev to intersection point
  25816. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25817. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25818. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25819. // vector from inPt to intersection point
  25820. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25821. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25822. // Don't normalize!, otherwise sharp corners become ugly
  25823. // but prevent crazy spikes
  25824. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25825. if ( v_trans_lensq <= 2 ) {
  25826. return new Vector2( v_trans_x, v_trans_y );
  25827. } else {
  25828. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25829. }
  25830. } else {
  25831. // handle special case of collinear edges
  25832. let direction_eq = false; // assumes: opposite
  25833. if ( v_prev_x > Number.EPSILON ) {
  25834. if ( v_next_x > Number.EPSILON ) {
  25835. direction_eq = true;
  25836. }
  25837. } else {
  25838. if ( v_prev_x < - Number.EPSILON ) {
  25839. if ( v_next_x < - Number.EPSILON ) {
  25840. direction_eq = true;
  25841. }
  25842. } else {
  25843. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25844. direction_eq = true;
  25845. }
  25846. }
  25847. }
  25848. if ( direction_eq ) {
  25849. // console.log("Warning: lines are a straight sequence");
  25850. v_trans_x = - v_prev_y;
  25851. v_trans_y = v_prev_x;
  25852. shrink_by = Math.sqrt( v_prev_lensq );
  25853. } else {
  25854. // console.log("Warning: lines are a straight spike");
  25855. v_trans_x = v_prev_x;
  25856. v_trans_y = v_prev_y;
  25857. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25858. }
  25859. }
  25860. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25861. }
  25862. const contourMovements = [];
  25863. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25864. if ( j === il ) j = 0;
  25865. if ( k === il ) k = 0;
  25866. // (j)---(i)---(k)
  25867. // console.log('i,j,k', i, j , k)
  25868. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25869. }
  25870. const holesMovements = [];
  25871. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25872. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25873. const ahole = holes[ h ];
  25874. oneHoleMovements = [];
  25875. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25876. if ( j === il ) j = 0;
  25877. if ( k === il ) k = 0;
  25878. // (j)---(i)---(k)
  25879. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25880. }
  25881. holesMovements.push( oneHoleMovements );
  25882. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25883. }
  25884. let faces;
  25885. if ( bevelSegments === 0 ) {
  25886. faces = ShapeUtils.triangulateShape( contour, holes );
  25887. } else {
  25888. const contractedContourVertices = [];
  25889. const expandedHoleVertices = [];
  25890. // Loop bevelSegments, 1 for the front, 1 for the back
  25891. for ( let b = 0; b < bevelSegments; b ++ ) {
  25892. //for ( b = bevelSegments; b > 0; b -- ) {
  25893. const t = b / bevelSegments;
  25894. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25895. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25896. // contract shape
  25897. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25898. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25899. v( vert.x, vert.y, - z );
  25900. if ( t === 0 ) contractedContourVertices.push( vert );
  25901. }
  25902. // expand holes
  25903. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25904. const ahole = holes[ h ];
  25905. oneHoleMovements = holesMovements[ h ];
  25906. const oneHoleVertices = [];
  25907. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25908. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25909. v( vert.x, vert.y, - z );
  25910. if ( t === 0 ) oneHoleVertices.push( vert );
  25911. }
  25912. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  25913. }
  25914. }
  25915. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  25916. }
  25917. const flen = faces.length;
  25918. const bs = bevelSize + bevelOffset;
  25919. // Back facing vertices
  25920. for ( let i = 0; i < vlen; i ++ ) {
  25921. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25922. if ( ! extrudeByPath ) {
  25923. v( vert.x, vert.y, 0 );
  25924. } else {
  25925. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  25926. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  25927. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  25928. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  25929. v( position2.x, position2.y, position2.z );
  25930. }
  25931. }
  25932. // Add stepped vertices...
  25933. // Including front facing vertices
  25934. for ( let s = 1; s <= steps; s ++ ) {
  25935. for ( let i = 0; i < vlen; i ++ ) {
  25936. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  25937. if ( ! extrudeByPath ) {
  25938. v( vert.x, vert.y, depth / steps * s );
  25939. } else {
  25940. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  25941. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  25942. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  25943. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  25944. v( position2.x, position2.y, position2.z );
  25945. }
  25946. }
  25947. }
  25948. // Add bevel segments planes
  25949. //for ( b = 1; b <= bevelSegments; b ++ ) {
  25950. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  25951. const t = b / bevelSegments;
  25952. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25953. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  25954. // contract shape
  25955. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  25956. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  25957. v( vert.x, vert.y, depth + z );
  25958. }
  25959. // expand holes
  25960. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25961. const ahole = holes[ h ];
  25962. oneHoleMovements = holesMovements[ h ];
  25963. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  25964. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  25965. if ( ! extrudeByPath ) {
  25966. v( vert.x, vert.y, depth + z );
  25967. } else {
  25968. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  25969. }
  25970. }
  25971. }
  25972. }
  25973. /* Faces */
  25974. // Top and bottom faces
  25975. buildLidFaces();
  25976. // Sides faces
  25977. buildSideFaces();
  25978. ///// Internal functions
  25979. function buildLidFaces() {
  25980. const start = verticesArray.length / 3;
  25981. if ( bevelEnabled ) {
  25982. let layer = 0; // steps + 1
  25983. let offset = vlen * layer;
  25984. // Bottom faces
  25985. for ( let i = 0; i < flen; i ++ ) {
  25986. const face = faces[ i ];
  25987. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  25988. }
  25989. layer = steps + bevelSegments * 2;
  25990. offset = vlen * layer;
  25991. // Top faces
  25992. for ( let i = 0; i < flen; i ++ ) {
  25993. const face = faces[ i ];
  25994. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  25995. }
  25996. } else {
  25997. // Bottom faces
  25998. for ( let i = 0; i < flen; i ++ ) {
  25999. const face = faces[ i ];
  26000. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26001. }
  26002. // Top faces
  26003. for ( let i = 0; i < flen; i ++ ) {
  26004. const face = faces[ i ];
  26005. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26006. }
  26007. }
  26008. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26009. }
  26010. // Create faces for the z-sides of the shape
  26011. function buildSideFaces() {
  26012. const start = verticesArray.length / 3;
  26013. let layeroffset = 0;
  26014. sidewalls( contour, layeroffset );
  26015. layeroffset += contour.length;
  26016. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26017. const ahole = holes[ h ];
  26018. sidewalls( ahole, layeroffset );
  26019. //, true
  26020. layeroffset += ahole.length;
  26021. }
  26022. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26023. }
  26024. function sidewalls( contour, layeroffset ) {
  26025. let i = contour.length;
  26026. while ( -- i >= 0 ) {
  26027. const j = i;
  26028. let k = i - 1;
  26029. if ( k < 0 ) k = contour.length - 1;
  26030. //console.log('b', i,j, i-1, k,vertices.length);
  26031. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26032. const slen1 = vlen * s;
  26033. const slen2 = vlen * ( s + 1 );
  26034. const a = layeroffset + j + slen1,
  26035. b = layeroffset + k + slen1,
  26036. c = layeroffset + k + slen2,
  26037. d = layeroffset + j + slen2;
  26038. f4( a, b, c, d );
  26039. }
  26040. }
  26041. }
  26042. function v( x, y, z ) {
  26043. placeholder.push( x );
  26044. placeholder.push( y );
  26045. placeholder.push( z );
  26046. }
  26047. function f3( a, b, c ) {
  26048. addVertex( a );
  26049. addVertex( b );
  26050. addVertex( c );
  26051. const nextIndex = verticesArray.length / 3;
  26052. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26053. addUV( uvs[ 0 ] );
  26054. addUV( uvs[ 1 ] );
  26055. addUV( uvs[ 2 ] );
  26056. }
  26057. function f4( a, b, c, d ) {
  26058. addVertex( a );
  26059. addVertex( b );
  26060. addVertex( d );
  26061. addVertex( b );
  26062. addVertex( c );
  26063. addVertex( d );
  26064. const nextIndex = verticesArray.length / 3;
  26065. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26066. addUV( uvs[ 0 ] );
  26067. addUV( uvs[ 1 ] );
  26068. addUV( uvs[ 3 ] );
  26069. addUV( uvs[ 1 ] );
  26070. addUV( uvs[ 2 ] );
  26071. addUV( uvs[ 3 ] );
  26072. }
  26073. function addVertex( index ) {
  26074. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26075. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26076. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26077. }
  26078. function addUV( vector2 ) {
  26079. uvArray.push( vector2.x );
  26080. uvArray.push( vector2.y );
  26081. }
  26082. }
  26083. }
  26084. copy( source ) {
  26085. super.copy( source );
  26086. this.parameters = Object.assign( {}, source.parameters );
  26087. return this;
  26088. }
  26089. toJSON() {
  26090. const data = super.toJSON();
  26091. const shapes = this.parameters.shapes;
  26092. const options = this.parameters.options;
  26093. return toJSON$1( shapes, options, data );
  26094. }
  26095. /**
  26096. * Factory method for creating an instance of this class from the given
  26097. * JSON object.
  26098. *
  26099. * @param {Object} data - A JSON object representing the serialized geometry.
  26100. * @param {Array<Shape>} shapes - An array of shapes.
  26101. * @return {ExtrudeGeometry} A new instance.
  26102. */
  26103. static fromJSON( data, shapes ) {
  26104. const geometryShapes = [];
  26105. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26106. const shape = shapes[ data.shapes[ j ] ];
  26107. geometryShapes.push( shape );
  26108. }
  26109. const extrudePath = data.options.extrudePath;
  26110. if ( extrudePath !== undefined ) {
  26111. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26112. }
  26113. return new ExtrudeGeometry( geometryShapes, data.options );
  26114. }
  26115. }
  26116. const WorldUVGenerator = {
  26117. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26118. const a_x = vertices[ indexA * 3 ];
  26119. const a_y = vertices[ indexA * 3 + 1 ];
  26120. const b_x = vertices[ indexB * 3 ];
  26121. const b_y = vertices[ indexB * 3 + 1 ];
  26122. const c_x = vertices[ indexC * 3 ];
  26123. const c_y = vertices[ indexC * 3 + 1 ];
  26124. return [
  26125. new Vector2( a_x, a_y ),
  26126. new Vector2( b_x, b_y ),
  26127. new Vector2( c_x, c_y )
  26128. ];
  26129. },
  26130. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26131. const a_x = vertices[ indexA * 3 ];
  26132. const a_y = vertices[ indexA * 3 + 1 ];
  26133. const a_z = vertices[ indexA * 3 + 2 ];
  26134. const b_x = vertices[ indexB * 3 ];
  26135. const b_y = vertices[ indexB * 3 + 1 ];
  26136. const b_z = vertices[ indexB * 3 + 2 ];
  26137. const c_x = vertices[ indexC * 3 ];
  26138. const c_y = vertices[ indexC * 3 + 1 ];
  26139. const c_z = vertices[ indexC * 3 + 2 ];
  26140. const d_x = vertices[ indexD * 3 ];
  26141. const d_y = vertices[ indexD * 3 + 1 ];
  26142. const d_z = vertices[ indexD * 3 + 2 ];
  26143. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26144. return [
  26145. new Vector2( a_x, 1 - a_z ),
  26146. new Vector2( b_x, 1 - b_z ),
  26147. new Vector2( c_x, 1 - c_z ),
  26148. new Vector2( d_x, 1 - d_z )
  26149. ];
  26150. } else {
  26151. return [
  26152. new Vector2( a_y, 1 - a_z ),
  26153. new Vector2( b_y, 1 - b_z ),
  26154. new Vector2( c_y, 1 - c_z ),
  26155. new Vector2( d_y, 1 - d_z )
  26156. ];
  26157. }
  26158. }
  26159. };
  26160. function toJSON$1( shapes, options, data ) {
  26161. data.shapes = [];
  26162. if ( Array.isArray( shapes ) ) {
  26163. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26164. const shape = shapes[ i ];
  26165. data.shapes.push( shape.uuid );
  26166. }
  26167. } else {
  26168. data.shapes.push( shapes.uuid );
  26169. }
  26170. data.options = Object.assign( {}, options );
  26171. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26172. return data;
  26173. }
  26174. /**
  26175. * A geometry class for representing an icosahedron.
  26176. *
  26177. * ```js
  26178. * const geometry = new THREE.IcosahedronGeometry();
  26179. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26180. * const icosahedron = new THREE.Mesh( geometry, material );
  26181. * scene.add( icosahedron );
  26182. * ```
  26183. *
  26184. * @augments PolyhedronGeometry
  26185. */
  26186. class IcosahedronGeometry extends PolyhedronGeometry {
  26187. /**
  26188. * Constructs a new icosahedron geometry.
  26189. *
  26190. * @param {number} [radius=1] - Radius of the icosahedron.
  26191. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26192. */
  26193. constructor( radius = 1, detail = 0 ) {
  26194. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26195. const vertices = [
  26196. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26197. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26198. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26199. ];
  26200. const indices = [
  26201. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26202. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26203. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26204. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26205. ];
  26206. super( vertices, indices, radius, detail );
  26207. this.type = 'IcosahedronGeometry';
  26208. /**
  26209. * Holds the constructor parameters that have been
  26210. * used to generate the geometry. Any modification
  26211. * after instantiation does not change the geometry.
  26212. *
  26213. * @type {Object}
  26214. */
  26215. this.parameters = {
  26216. radius: radius,
  26217. detail: detail
  26218. };
  26219. }
  26220. /**
  26221. * Factory method for creating an instance of this class from the given
  26222. * JSON object.
  26223. *
  26224. * @param {Object} data - A JSON object representing the serialized geometry.
  26225. * @return {IcosahedronGeometry} A new instance.
  26226. */
  26227. static fromJSON( data ) {
  26228. return new IcosahedronGeometry( data.radius, data.detail );
  26229. }
  26230. }
  26231. /**
  26232. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26233. *
  26234. * ```js
  26235. * const points = [];
  26236. * for ( let i = 0; i < 10; i ++ ) {
  26237. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26238. * }
  26239. * const geometry = new THREE.LatheGeometry( points );
  26240. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26241. * const lathe = new THREE.Mesh( geometry, material );
  26242. * scene.add( lathe );
  26243. * ```
  26244. *
  26245. * @augments BufferGeometry
  26246. */
  26247. class LatheGeometry extends BufferGeometry {
  26248. /**
  26249. * Constructs a new lathe geometry.
  26250. *
  26251. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26252. * must be greater than zero.
  26253. * @param {number} [segments=12] - The number of circumference segments to generate.
  26254. * @param {number} [phiStart=0] - The starting angle in radians.
  26255. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26256. * closed lathe, less than 2PI is a portion.
  26257. */
  26258. 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 ) {
  26259. super();
  26260. this.type = 'LatheGeometry';
  26261. /**
  26262. * Holds the constructor parameters that have been
  26263. * used to generate the geometry. Any modification
  26264. * after instantiation does not change the geometry.
  26265. *
  26266. * @type {Object}
  26267. */
  26268. this.parameters = {
  26269. points: points,
  26270. segments: segments,
  26271. phiStart: phiStart,
  26272. phiLength: phiLength
  26273. };
  26274. segments = Math.floor( segments );
  26275. // clamp phiLength so it's in range of [ 0, 2PI ]
  26276. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26277. // buffers
  26278. const indices = [];
  26279. const vertices = [];
  26280. const uvs = [];
  26281. const initNormals = [];
  26282. const normals = [];
  26283. // helper variables
  26284. const inverseSegments = 1.0 / segments;
  26285. const vertex = new Vector3();
  26286. const uv = new Vector2();
  26287. const normal = new Vector3();
  26288. const curNormal = new Vector3();
  26289. const prevNormal = new Vector3();
  26290. let dx = 0;
  26291. let dy = 0;
  26292. // pre-compute normals for initial "meridian"
  26293. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26294. switch ( j ) {
  26295. case 0: // special handling for 1st vertex on path
  26296. dx = points[ j + 1 ].x - points[ j ].x;
  26297. dy = points[ j + 1 ].y - points[ j ].y;
  26298. normal.x = dy * 1.0;
  26299. normal.y = - dx;
  26300. normal.z = dy * 0.0;
  26301. prevNormal.copy( normal );
  26302. normal.normalize();
  26303. initNormals.push( normal.x, normal.y, normal.z );
  26304. break;
  26305. case ( points.length - 1 ): // special handling for last Vertex on path
  26306. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26307. break;
  26308. default: // default handling for all vertices in between
  26309. dx = points[ j + 1 ].x - points[ j ].x;
  26310. dy = points[ j + 1 ].y - points[ j ].y;
  26311. normal.x = dy * 1.0;
  26312. normal.y = - dx;
  26313. normal.z = dy * 0.0;
  26314. curNormal.copy( normal );
  26315. normal.x += prevNormal.x;
  26316. normal.y += prevNormal.y;
  26317. normal.z += prevNormal.z;
  26318. normal.normalize();
  26319. initNormals.push( normal.x, normal.y, normal.z );
  26320. prevNormal.copy( curNormal );
  26321. }
  26322. }
  26323. // generate vertices, uvs and normals
  26324. for ( let i = 0; i <= segments; i ++ ) {
  26325. const phi = phiStart + i * inverseSegments * phiLength;
  26326. const sin = Math.sin( phi );
  26327. const cos = Math.cos( phi );
  26328. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26329. // vertex
  26330. vertex.x = points[ j ].x * sin;
  26331. vertex.y = points[ j ].y;
  26332. vertex.z = points[ j ].x * cos;
  26333. vertices.push( vertex.x, vertex.y, vertex.z );
  26334. // uv
  26335. uv.x = i / segments;
  26336. uv.y = j / ( points.length - 1 );
  26337. uvs.push( uv.x, uv.y );
  26338. // normal
  26339. const x = initNormals[ 3 * j + 0 ] * sin;
  26340. const y = initNormals[ 3 * j + 1 ];
  26341. const z = initNormals[ 3 * j + 0 ] * cos;
  26342. normals.push( x, y, z );
  26343. }
  26344. }
  26345. // indices
  26346. for ( let i = 0; i < segments; i ++ ) {
  26347. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26348. const base = j + i * points.length;
  26349. const a = base;
  26350. const b = base + points.length;
  26351. const c = base + points.length + 1;
  26352. const d = base + 1;
  26353. // faces
  26354. indices.push( a, b, d );
  26355. indices.push( c, d, b );
  26356. }
  26357. }
  26358. // build geometry
  26359. this.setIndex( indices );
  26360. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26361. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26362. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26363. }
  26364. copy( source ) {
  26365. super.copy( source );
  26366. this.parameters = Object.assign( {}, source.parameters );
  26367. return this;
  26368. }
  26369. /**
  26370. * Factory method for creating an instance of this class from the given
  26371. * JSON object.
  26372. *
  26373. * @param {Object} data - A JSON object representing the serialized geometry.
  26374. * @return {LatheGeometry} A new instance.
  26375. */
  26376. static fromJSON( data ) {
  26377. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26378. }
  26379. }
  26380. /**
  26381. * A geometry class for representing an octahedron.
  26382. *
  26383. * ```js
  26384. * const geometry = new THREE.OctahedronGeometry();
  26385. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26386. * const octahedron = new THREE.Mesh( geometry, material );
  26387. * scene.add( octahedron );
  26388. * ```
  26389. *
  26390. * @augments PolyhedronGeometry
  26391. */
  26392. class OctahedronGeometry extends PolyhedronGeometry {
  26393. /**
  26394. * Constructs a new octahedron geometry.
  26395. *
  26396. * @param {number} [radius=1] - Radius of the octahedron.
  26397. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26398. */
  26399. constructor( radius = 1, detail = 0 ) {
  26400. const vertices = [
  26401. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26402. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26403. ];
  26404. const indices = [
  26405. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26406. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26407. 1, 3, 4, 1, 4, 2
  26408. ];
  26409. super( vertices, indices, radius, detail );
  26410. this.type = 'OctahedronGeometry';
  26411. /**
  26412. * Holds the constructor parameters that have been
  26413. * used to generate the geometry. Any modification
  26414. * after instantiation does not change the geometry.
  26415. *
  26416. * @type {Object}
  26417. */
  26418. this.parameters = {
  26419. radius: radius,
  26420. detail: detail
  26421. };
  26422. }
  26423. /**
  26424. * Factory method for creating an instance of this class from the given
  26425. * JSON object.
  26426. *
  26427. * @param {Object} data - A JSON object representing the serialized geometry.
  26428. * @return {OctahedronGeometry} A new instance.
  26429. */
  26430. static fromJSON( data ) {
  26431. return new OctahedronGeometry( data.radius, data.detail );
  26432. }
  26433. }
  26434. /**
  26435. * A geometry class for representing a plane.
  26436. *
  26437. * ```js
  26438. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26439. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26440. * const plane = new THREE.Mesh( geometry, material );
  26441. * scene.add( plane );
  26442. * ```
  26443. *
  26444. * @augments BufferGeometry
  26445. */
  26446. class PlaneGeometry extends BufferGeometry {
  26447. /**
  26448. * Constructs a new plane geometry.
  26449. *
  26450. * @param {number} [width=1] - The width along the X axis.
  26451. * @param {number} [height=1] - The height along the Y axis
  26452. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26453. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26454. */
  26455. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26456. super();
  26457. this.type = 'PlaneGeometry';
  26458. /**
  26459. * Holds the constructor parameters that have been
  26460. * used to generate the geometry. Any modification
  26461. * after instantiation does not change the geometry.
  26462. *
  26463. * @type {Object}
  26464. */
  26465. this.parameters = {
  26466. width: width,
  26467. height: height,
  26468. widthSegments: widthSegments,
  26469. heightSegments: heightSegments
  26470. };
  26471. const width_half = width / 2;
  26472. const height_half = height / 2;
  26473. const gridX = Math.floor( widthSegments );
  26474. const gridY = Math.floor( heightSegments );
  26475. const gridX1 = gridX + 1;
  26476. const gridY1 = gridY + 1;
  26477. const segment_width = width / gridX;
  26478. const segment_height = height / gridY;
  26479. //
  26480. const indices = [];
  26481. const vertices = [];
  26482. const normals = [];
  26483. const uvs = [];
  26484. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26485. const y = iy * segment_height - height_half;
  26486. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26487. const x = ix * segment_width - width_half;
  26488. vertices.push( x, - y, 0 );
  26489. normals.push( 0, 0, 1 );
  26490. uvs.push( ix / gridX );
  26491. uvs.push( 1 - ( iy / gridY ) );
  26492. }
  26493. }
  26494. for ( let iy = 0; iy < gridY; iy ++ ) {
  26495. for ( let ix = 0; ix < gridX; ix ++ ) {
  26496. const a = ix + gridX1 * iy;
  26497. const b = ix + gridX1 * ( iy + 1 );
  26498. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26499. const d = ( ix + 1 ) + gridX1 * iy;
  26500. indices.push( a, b, d );
  26501. indices.push( b, c, d );
  26502. }
  26503. }
  26504. this.setIndex( indices );
  26505. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26506. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26507. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26508. }
  26509. copy( source ) {
  26510. super.copy( source );
  26511. this.parameters = Object.assign( {}, source.parameters );
  26512. return this;
  26513. }
  26514. /**
  26515. * Factory method for creating an instance of this class from the given
  26516. * JSON object.
  26517. *
  26518. * @param {Object} data - A JSON object representing the serialized geometry.
  26519. * @return {PlaneGeometry} A new instance.
  26520. */
  26521. static fromJSON( data ) {
  26522. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26523. }
  26524. }
  26525. /**
  26526. * A class for generating a two-dimensional ring geometry.
  26527. *
  26528. * ```js
  26529. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26530. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26531. * const mesh = new THREE.Mesh( geometry, material );
  26532. * scene.add( mesh );
  26533. * ```
  26534. *
  26535. * @augments BufferGeometry
  26536. */
  26537. class RingGeometry extends BufferGeometry {
  26538. /**
  26539. * Constructs a new ring geometry.
  26540. *
  26541. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26542. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26543. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26544. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26545. * @param {number} [thetaStart=0] - Starting angle in radians.
  26546. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26547. */
  26548. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26549. super();
  26550. this.type = 'RingGeometry';
  26551. /**
  26552. * Holds the constructor parameters that have been
  26553. * used to generate the geometry. Any modification
  26554. * after instantiation does not change the geometry.
  26555. *
  26556. * @type {Object}
  26557. */
  26558. this.parameters = {
  26559. innerRadius: innerRadius,
  26560. outerRadius: outerRadius,
  26561. thetaSegments: thetaSegments,
  26562. phiSegments: phiSegments,
  26563. thetaStart: thetaStart,
  26564. thetaLength: thetaLength
  26565. };
  26566. thetaSegments = Math.max( 3, thetaSegments );
  26567. phiSegments = Math.max( 1, phiSegments );
  26568. // buffers
  26569. const indices = [];
  26570. const vertices = [];
  26571. const normals = [];
  26572. const uvs = [];
  26573. // some helper variables
  26574. let radius = innerRadius;
  26575. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26576. const vertex = new Vector3();
  26577. const uv = new Vector2();
  26578. // generate vertices, normals and uvs
  26579. for ( let j = 0; j <= phiSegments; j ++ ) {
  26580. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26581. // values are generate from the inside of the ring to the outside
  26582. const segment = thetaStart + i / thetaSegments * thetaLength;
  26583. // vertex
  26584. vertex.x = radius * Math.cos( segment );
  26585. vertex.y = radius * Math.sin( segment );
  26586. vertices.push( vertex.x, vertex.y, vertex.z );
  26587. // normal
  26588. normals.push( 0, 0, 1 );
  26589. // uv
  26590. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26591. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26592. uvs.push( uv.x, uv.y );
  26593. }
  26594. // increase the radius for next row of vertices
  26595. radius += radiusStep;
  26596. }
  26597. // indices
  26598. for ( let j = 0; j < phiSegments; j ++ ) {
  26599. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26600. for ( let i = 0; i < thetaSegments; i ++ ) {
  26601. const segment = i + thetaSegmentLevel;
  26602. const a = segment;
  26603. const b = segment + thetaSegments + 1;
  26604. const c = segment + thetaSegments + 2;
  26605. const d = segment + 1;
  26606. // faces
  26607. indices.push( a, b, d );
  26608. indices.push( b, c, d );
  26609. }
  26610. }
  26611. // build geometry
  26612. this.setIndex( indices );
  26613. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26614. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26615. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26616. }
  26617. copy( source ) {
  26618. super.copy( source );
  26619. this.parameters = Object.assign( {}, source.parameters );
  26620. return this;
  26621. }
  26622. /**
  26623. * Factory method for creating an instance of this class from the given
  26624. * JSON object.
  26625. *
  26626. * @param {Object} data - A JSON object representing the serialized geometry.
  26627. * @return {RingGeometry} A new instance.
  26628. */
  26629. static fromJSON( data ) {
  26630. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26631. }
  26632. }
  26633. /**
  26634. * Creates an one-sided polygonal geometry from one or more path shapes.
  26635. *
  26636. * ```js
  26637. * const arcShape = new THREE.Shape()
  26638. * .moveTo( 5, 1 )
  26639. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26640. *
  26641. * const geometry = new THREE.ShapeGeometry( arcShape );
  26642. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26643. * const mesh = new THREE.Mesh( geometry, material ) ;
  26644. * scene.add( mesh );
  26645. * ```
  26646. *
  26647. * @augments BufferGeometry
  26648. */
  26649. class ShapeGeometry extends BufferGeometry {
  26650. /**
  26651. * Constructs a new shape geometry.
  26652. *
  26653. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26654. * @param {number} [curveSegments=12] - Number of segments per shape.
  26655. */
  26656. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26657. super();
  26658. this.type = 'ShapeGeometry';
  26659. /**
  26660. * Holds the constructor parameters that have been
  26661. * used to generate the geometry. Any modification
  26662. * after instantiation does not change the geometry.
  26663. *
  26664. * @type {Object}
  26665. */
  26666. this.parameters = {
  26667. shapes: shapes,
  26668. curveSegments: curveSegments
  26669. };
  26670. // buffers
  26671. const indices = [];
  26672. const vertices = [];
  26673. const normals = [];
  26674. const uvs = [];
  26675. // helper variables
  26676. let groupStart = 0;
  26677. let groupCount = 0;
  26678. // allow single and array values for "shapes" parameter
  26679. if ( Array.isArray( shapes ) === false ) {
  26680. addShape( shapes );
  26681. } else {
  26682. for ( let i = 0; i < shapes.length; i ++ ) {
  26683. addShape( shapes[ i ] );
  26684. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26685. groupStart += groupCount;
  26686. groupCount = 0;
  26687. }
  26688. }
  26689. // build geometry
  26690. this.setIndex( indices );
  26691. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26692. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26693. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26694. // helper functions
  26695. function addShape( shape ) {
  26696. const indexOffset = vertices.length / 3;
  26697. const points = shape.extractPoints( curveSegments );
  26698. let shapeVertices = points.shape;
  26699. const shapeHoles = points.holes;
  26700. // check direction of vertices
  26701. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26702. shapeVertices = shapeVertices.reverse();
  26703. }
  26704. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26705. const shapeHole = shapeHoles[ i ];
  26706. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26707. shapeHoles[ i ] = shapeHole.reverse();
  26708. }
  26709. }
  26710. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26711. // join vertices of inner and outer paths to a single array
  26712. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26713. const shapeHole = shapeHoles[ i ];
  26714. shapeVertices = shapeVertices.concat( shapeHole );
  26715. }
  26716. // vertices, normals, uvs
  26717. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26718. const vertex = shapeVertices[ i ];
  26719. vertices.push( vertex.x, vertex.y, 0 );
  26720. normals.push( 0, 0, 1 );
  26721. uvs.push( vertex.x, vertex.y ); // world uvs
  26722. }
  26723. // indices
  26724. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26725. const face = faces[ i ];
  26726. const a = face[ 0 ] + indexOffset;
  26727. const b = face[ 1 ] + indexOffset;
  26728. const c = face[ 2 ] + indexOffset;
  26729. indices.push( a, b, c );
  26730. groupCount += 3;
  26731. }
  26732. }
  26733. }
  26734. copy( source ) {
  26735. super.copy( source );
  26736. this.parameters = Object.assign( {}, source.parameters );
  26737. return this;
  26738. }
  26739. toJSON() {
  26740. const data = super.toJSON();
  26741. const shapes = this.parameters.shapes;
  26742. return toJSON( shapes, data );
  26743. }
  26744. /**
  26745. * Factory method for creating an instance of this class from the given
  26746. * JSON object.
  26747. *
  26748. * @param {Object} data - A JSON object representing the serialized geometry.
  26749. * @param {Array<Shape>} shapes - An array of shapes.
  26750. * @return {ShapeGeometry} A new instance.
  26751. */
  26752. static fromJSON( data, shapes ) {
  26753. const geometryShapes = [];
  26754. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26755. const shape = shapes[ data.shapes[ j ] ];
  26756. geometryShapes.push( shape );
  26757. }
  26758. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26759. }
  26760. }
  26761. function toJSON( shapes, data ) {
  26762. data.shapes = [];
  26763. if ( Array.isArray( shapes ) ) {
  26764. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26765. const shape = shapes[ i ];
  26766. data.shapes.push( shape.uuid );
  26767. }
  26768. } else {
  26769. data.shapes.push( shapes.uuid );
  26770. }
  26771. return data;
  26772. }
  26773. /**
  26774. * A class for generating a sphere geometry.
  26775. *
  26776. * ```js
  26777. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26778. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26779. * const sphere = new THREE.Mesh( geometry, material );
  26780. * scene.add( sphere );
  26781. * ```
  26782. *
  26783. * @augments BufferGeometry
  26784. */
  26785. class SphereGeometry extends BufferGeometry {
  26786. /**
  26787. * Constructs a new sphere geometry.
  26788. *
  26789. * @param {number} [radius=1] - The sphere radius.
  26790. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26791. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26792. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26793. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26794. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26795. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26796. */
  26797. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26798. super();
  26799. this.type = 'SphereGeometry';
  26800. /**
  26801. * Holds the constructor parameters that have been
  26802. * used to generate the geometry. Any modification
  26803. * after instantiation does not change the geometry.
  26804. *
  26805. * @type {Object}
  26806. */
  26807. this.parameters = {
  26808. radius: radius,
  26809. widthSegments: widthSegments,
  26810. heightSegments: heightSegments,
  26811. phiStart: phiStart,
  26812. phiLength: phiLength,
  26813. thetaStart: thetaStart,
  26814. thetaLength: thetaLength
  26815. };
  26816. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26817. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26818. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26819. let index = 0;
  26820. const grid = [];
  26821. const vertex = new Vector3();
  26822. const normal = new Vector3();
  26823. // buffers
  26824. const indices = [];
  26825. const vertices = [];
  26826. const normals = [];
  26827. const uvs = [];
  26828. // generate vertices, normals and uvs
  26829. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26830. const verticesRow = [];
  26831. const v = iy / heightSegments;
  26832. // special case for the poles
  26833. let uOffset = 0;
  26834. if ( iy === 0 && thetaStart === 0 ) {
  26835. uOffset = 0.5 / widthSegments;
  26836. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26837. uOffset = -0.5 / widthSegments;
  26838. }
  26839. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26840. const u = ix / widthSegments;
  26841. // vertex
  26842. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26843. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26844. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26845. vertices.push( vertex.x, vertex.y, vertex.z );
  26846. // normal
  26847. normal.copy( vertex ).normalize();
  26848. normals.push( normal.x, normal.y, normal.z );
  26849. // uv
  26850. uvs.push( u + uOffset, 1 - v );
  26851. verticesRow.push( index ++ );
  26852. }
  26853. grid.push( verticesRow );
  26854. }
  26855. // indices
  26856. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26857. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26858. const a = grid[ iy ][ ix + 1 ];
  26859. const b = grid[ iy ][ ix ];
  26860. const c = grid[ iy + 1 ][ ix ];
  26861. const d = grid[ iy + 1 ][ ix + 1 ];
  26862. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26863. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26864. }
  26865. }
  26866. // build geometry
  26867. this.setIndex( indices );
  26868. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26869. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26870. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26871. }
  26872. copy( source ) {
  26873. super.copy( source );
  26874. this.parameters = Object.assign( {}, source.parameters );
  26875. return this;
  26876. }
  26877. /**
  26878. * Factory method for creating an instance of this class from the given
  26879. * JSON object.
  26880. *
  26881. * @param {Object} data - A JSON object representing the serialized geometry.
  26882. * @return {SphereGeometry} A new instance.
  26883. */
  26884. static fromJSON( data ) {
  26885. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26886. }
  26887. }
  26888. /**
  26889. * A geometry class for representing an tetrahedron.
  26890. *
  26891. * ```js
  26892. * const geometry = new THREE.TetrahedronGeometry();
  26893. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26894. * const tetrahedron = new THREE.Mesh( geometry, material );
  26895. * scene.add( tetrahedron );
  26896. * ```
  26897. *
  26898. * @augments PolyhedronGeometry
  26899. */
  26900. class TetrahedronGeometry extends PolyhedronGeometry {
  26901. /**
  26902. * Constructs a new tetrahedron geometry.
  26903. *
  26904. * @param {number} [radius=1] - Radius of the tetrahedron.
  26905. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  26906. */
  26907. constructor( radius = 1, detail = 0 ) {
  26908. const vertices = [
  26909. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  26910. ];
  26911. const indices = [
  26912. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  26913. ];
  26914. super( vertices, indices, radius, detail );
  26915. this.type = 'TetrahedronGeometry';
  26916. /**
  26917. * Holds the constructor parameters that have been
  26918. * used to generate the geometry. Any modification
  26919. * after instantiation does not change the geometry.
  26920. *
  26921. * @type {Object}
  26922. */
  26923. this.parameters = {
  26924. radius: radius,
  26925. detail: detail
  26926. };
  26927. }
  26928. /**
  26929. * Factory method for creating an instance of this class from the given
  26930. * JSON object.
  26931. *
  26932. * @param {Object} data - A JSON object representing the serialized geometry.
  26933. * @return {TetrahedronGeometry} A new instance.
  26934. */
  26935. static fromJSON( data ) {
  26936. return new TetrahedronGeometry( data.radius, data.detail );
  26937. }
  26938. }
  26939. /**
  26940. * A geometry class for representing an torus.
  26941. *
  26942. * ```js
  26943. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  26944. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26945. * const torus = new THREE.Mesh( geometry, material );
  26946. * scene.add( torus );
  26947. * ```
  26948. *
  26949. * @augments BufferGeometry
  26950. */
  26951. class TorusGeometry extends BufferGeometry {
  26952. /**
  26953. * Constructs a new torus geometry.
  26954. *
  26955. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  26956. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  26957. * @param {number} [radialSegments=12] - The number of radial segments.
  26958. * @param {number} [tubularSegments=48] - The number of tubular segments.
  26959. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  26960. */
  26961. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  26962. super();
  26963. this.type = 'TorusGeometry';
  26964. /**
  26965. * Holds the constructor parameters that have been
  26966. * used to generate the geometry. Any modification
  26967. * after instantiation does not change the geometry.
  26968. *
  26969. * @type {Object}
  26970. */
  26971. this.parameters = {
  26972. radius: radius,
  26973. tube: tube,
  26974. radialSegments: radialSegments,
  26975. tubularSegments: tubularSegments,
  26976. arc: arc
  26977. };
  26978. radialSegments = Math.floor( radialSegments );
  26979. tubularSegments = Math.floor( tubularSegments );
  26980. // buffers
  26981. const indices = [];
  26982. const vertices = [];
  26983. const normals = [];
  26984. const uvs = [];
  26985. // helper variables
  26986. const center = new Vector3();
  26987. const vertex = new Vector3();
  26988. const normal = new Vector3();
  26989. // generate vertices, normals and uvs
  26990. for ( let j = 0; j <= radialSegments; j ++ ) {
  26991. for ( let i = 0; i <= tubularSegments; i ++ ) {
  26992. const u = i / tubularSegments * arc;
  26993. const v = j / radialSegments * Math.PI * 2;
  26994. // vertex
  26995. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  26996. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  26997. vertex.z = tube * Math.sin( v );
  26998. vertices.push( vertex.x, vertex.y, vertex.z );
  26999. // normal
  27000. center.x = radius * Math.cos( u );
  27001. center.y = radius * Math.sin( u );
  27002. normal.subVectors( vertex, center ).normalize();
  27003. normals.push( normal.x, normal.y, normal.z );
  27004. // uv
  27005. uvs.push( i / tubularSegments );
  27006. uvs.push( j / radialSegments );
  27007. }
  27008. }
  27009. // generate indices
  27010. for ( let j = 1; j <= radialSegments; j ++ ) {
  27011. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27012. // indices
  27013. const a = ( tubularSegments + 1 ) * j + i - 1;
  27014. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27015. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27016. const d = ( tubularSegments + 1 ) * j + i;
  27017. // faces
  27018. indices.push( a, b, d );
  27019. indices.push( b, c, d );
  27020. }
  27021. }
  27022. // build geometry
  27023. this.setIndex( indices );
  27024. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27025. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27026. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27027. }
  27028. copy( source ) {
  27029. super.copy( source );
  27030. this.parameters = Object.assign( {}, source.parameters );
  27031. return this;
  27032. }
  27033. /**
  27034. * Factory method for creating an instance of this class from the given
  27035. * JSON object.
  27036. *
  27037. * @param {Object} data - A JSON object representing the serialized geometry.
  27038. * @return {TorusGeometry} A new instance.
  27039. */
  27040. static fromJSON( data ) {
  27041. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27042. }
  27043. }
  27044. /**
  27045. * Creates a torus knot, the particular shape of which is defined by a pair
  27046. * of coprime integers, p and q. If p and q are not coprime, the result will
  27047. * be a torus link.
  27048. *
  27049. * ```js
  27050. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27051. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27052. * const torusKnot = new THREE.Mesh( geometry, material );
  27053. * scene.add( torusKnot );
  27054. * ```
  27055. *
  27056. * @augments BufferGeometry
  27057. */
  27058. class TorusKnotGeometry extends BufferGeometry {
  27059. /**
  27060. * Constructs a new torus knot geometry.
  27061. *
  27062. * @param {number} [radius=1] - Radius of the torus knot.
  27063. * @param {number} [tube=0.4] - Radius of the tube.
  27064. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27065. * @param {number} [radialSegments=8] - The number of radial segments.
  27066. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27067. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27068. */
  27069. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27070. super();
  27071. this.type = 'TorusKnotGeometry';
  27072. /**
  27073. * Holds the constructor parameters that have been
  27074. * used to generate the geometry. Any modification
  27075. * after instantiation does not change the geometry.
  27076. *
  27077. * @type {Object}
  27078. */
  27079. this.parameters = {
  27080. radius: radius,
  27081. tube: tube,
  27082. tubularSegments: tubularSegments,
  27083. radialSegments: radialSegments,
  27084. p: p,
  27085. q: q
  27086. };
  27087. tubularSegments = Math.floor( tubularSegments );
  27088. radialSegments = Math.floor( radialSegments );
  27089. // buffers
  27090. const indices = [];
  27091. const vertices = [];
  27092. const normals = [];
  27093. const uvs = [];
  27094. // helper variables
  27095. const vertex = new Vector3();
  27096. const normal = new Vector3();
  27097. const P1 = new Vector3();
  27098. const P2 = new Vector3();
  27099. const B = new Vector3();
  27100. const T = new Vector3();
  27101. const N = new Vector3();
  27102. // generate vertices, normals and uvs
  27103. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27104. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27105. const u = i / tubularSegments * p * Math.PI * 2;
  27106. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27107. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27108. calculatePositionOnCurve( u, p, q, radius, P1 );
  27109. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27110. // calculate orthonormal basis
  27111. T.subVectors( P2, P1 );
  27112. N.addVectors( P2, P1 );
  27113. B.crossVectors( T, N );
  27114. N.crossVectors( B, T );
  27115. // normalize B, N. T can be ignored, we don't use it
  27116. B.normalize();
  27117. N.normalize();
  27118. for ( let j = 0; j <= radialSegments; ++ j ) {
  27119. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27120. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27121. const v = j / radialSegments * Math.PI * 2;
  27122. const cx = - tube * Math.cos( v );
  27123. const cy = tube * Math.sin( v );
  27124. // now calculate the final vertex position.
  27125. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27126. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27127. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27128. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27129. vertices.push( vertex.x, vertex.y, vertex.z );
  27130. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27131. normal.subVectors( vertex, P1 ).normalize();
  27132. normals.push( normal.x, normal.y, normal.z );
  27133. // uv
  27134. uvs.push( i / tubularSegments );
  27135. uvs.push( j / radialSegments );
  27136. }
  27137. }
  27138. // generate indices
  27139. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27140. for ( let i = 1; i <= radialSegments; i ++ ) {
  27141. // indices
  27142. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27143. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27144. const c = ( radialSegments + 1 ) * j + i;
  27145. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27146. // faces
  27147. indices.push( a, b, d );
  27148. indices.push( b, c, d );
  27149. }
  27150. }
  27151. // build geometry
  27152. this.setIndex( indices );
  27153. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27154. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27155. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27156. // this function calculates the current position on the torus curve
  27157. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27158. const cu = Math.cos( u );
  27159. const su = Math.sin( u );
  27160. const quOverP = q / p * u;
  27161. const cs = Math.cos( quOverP );
  27162. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27163. position.y = radius * ( 2 + cs ) * su * 0.5;
  27164. position.z = radius * Math.sin( quOverP ) * 0.5;
  27165. }
  27166. }
  27167. copy( source ) {
  27168. super.copy( source );
  27169. this.parameters = Object.assign( {}, source.parameters );
  27170. return this;
  27171. }
  27172. /**
  27173. * Factory method for creating an instance of this class from the given
  27174. * JSON object.
  27175. *
  27176. * @param {Object} data - A JSON object representing the serialized geometry.
  27177. * @return {TorusKnotGeometry} A new instance.
  27178. */
  27179. static fromJSON( data ) {
  27180. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27181. }
  27182. }
  27183. /**
  27184. * Creates a tube that extrudes along a 3D curve.
  27185. *
  27186. * ```js
  27187. * class CustomSinCurve extends THREE.Curve {
  27188. *
  27189. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27190. *
  27191. * const tx = t * 3 - 1.5;
  27192. * const ty = Math.sin( 2 * Math.PI * t );
  27193. * const tz = 0;
  27194. *
  27195. * return optionalTarget.set( tx, ty, tz );
  27196. * }
  27197. *
  27198. * }
  27199. *
  27200. * const path = new CustomSinCurve( 10 );
  27201. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27202. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27203. * const mesh = new THREE.Mesh( geometry, material );
  27204. * scene.add( mesh );
  27205. * ```
  27206. *
  27207. * @augments BufferGeometry
  27208. */
  27209. class TubeGeometry extends BufferGeometry {
  27210. /**
  27211. * Constructs a new tube geometry.
  27212. *
  27213. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27214. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27215. * @param {number} [radius=1] -The radius of the tube.
  27216. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27217. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27218. */
  27219. 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 ) {
  27220. super();
  27221. this.type = 'TubeGeometry';
  27222. /**
  27223. * Holds the constructor parameters that have been
  27224. * used to generate the geometry. Any modification
  27225. * after instantiation does not change the geometry.
  27226. *
  27227. * @type {Object}
  27228. */
  27229. this.parameters = {
  27230. path: path,
  27231. tubularSegments: tubularSegments,
  27232. radius: radius,
  27233. radialSegments: radialSegments,
  27234. closed: closed
  27235. };
  27236. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27237. // expose internals
  27238. this.tangents = frames.tangents;
  27239. this.normals = frames.normals;
  27240. this.binormals = frames.binormals;
  27241. // helper variables
  27242. const vertex = new Vector3();
  27243. const normal = new Vector3();
  27244. const uv = new Vector2();
  27245. let P = new Vector3();
  27246. // buffer
  27247. const vertices = [];
  27248. const normals = [];
  27249. const uvs = [];
  27250. const indices = [];
  27251. // create buffer data
  27252. generateBufferData();
  27253. // build geometry
  27254. this.setIndex( indices );
  27255. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27256. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27257. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27258. // functions
  27259. function generateBufferData() {
  27260. for ( let i = 0; i < tubularSegments; i ++ ) {
  27261. generateSegment( i );
  27262. }
  27263. // if the geometry is not closed, generate the last row of vertices and normals
  27264. // at the regular position on the given path
  27265. //
  27266. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27267. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27268. // uvs are generated in a separate function.
  27269. // this makes it easy compute correct values for closed geometries
  27270. generateUVs();
  27271. // finally create faces
  27272. generateIndices();
  27273. }
  27274. function generateSegment( i ) {
  27275. // we use getPointAt to sample evenly distributed points from the given path
  27276. P = path.getPointAt( i / tubularSegments, P );
  27277. // retrieve corresponding normal and binormal
  27278. const N = frames.normals[ i ];
  27279. const B = frames.binormals[ i ];
  27280. // generate normals and vertices for the current segment
  27281. for ( let j = 0; j <= radialSegments; j ++ ) {
  27282. const v = j / radialSegments * Math.PI * 2;
  27283. const sin = Math.sin( v );
  27284. const cos = - Math.cos( v );
  27285. // normal
  27286. normal.x = ( cos * N.x + sin * B.x );
  27287. normal.y = ( cos * N.y + sin * B.y );
  27288. normal.z = ( cos * N.z + sin * B.z );
  27289. normal.normalize();
  27290. normals.push( normal.x, normal.y, normal.z );
  27291. // vertex
  27292. vertex.x = P.x + radius * normal.x;
  27293. vertex.y = P.y + radius * normal.y;
  27294. vertex.z = P.z + radius * normal.z;
  27295. vertices.push( vertex.x, vertex.y, vertex.z );
  27296. }
  27297. }
  27298. function generateIndices() {
  27299. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27300. for ( let i = 1; i <= radialSegments; i ++ ) {
  27301. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27302. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27303. const c = ( radialSegments + 1 ) * j + i;
  27304. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27305. // faces
  27306. indices.push( a, b, d );
  27307. indices.push( b, c, d );
  27308. }
  27309. }
  27310. }
  27311. function generateUVs() {
  27312. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27313. for ( let j = 0; j <= radialSegments; j ++ ) {
  27314. uv.x = i / tubularSegments;
  27315. uv.y = j / radialSegments;
  27316. uvs.push( uv.x, uv.y );
  27317. }
  27318. }
  27319. }
  27320. }
  27321. copy( source ) {
  27322. super.copy( source );
  27323. this.parameters = Object.assign( {}, source.parameters );
  27324. return this;
  27325. }
  27326. toJSON() {
  27327. const data = super.toJSON();
  27328. data.path = this.parameters.path.toJSON();
  27329. return data;
  27330. }
  27331. /**
  27332. * Factory method for creating an instance of this class from the given
  27333. * JSON object.
  27334. *
  27335. * @param {Object} data - A JSON object representing the serialized geometry.
  27336. * @return {TubeGeometry} A new instance.
  27337. */
  27338. static fromJSON( data ) {
  27339. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27340. // User defined curves or instances of CurvePath will not be deserialized.
  27341. return new TubeGeometry(
  27342. new Curves[ data.path.type ]().fromJSON( data.path ),
  27343. data.tubularSegments,
  27344. data.radius,
  27345. data.radialSegments,
  27346. data.closed
  27347. );
  27348. }
  27349. }
  27350. /**
  27351. * Can be used as a helper object to visualize a geometry as a wireframe.
  27352. *
  27353. * ```js
  27354. * const geometry = new THREE.SphereGeometry();
  27355. *
  27356. * const wireframe = new THREE.WireframeGeometry( geometry );
  27357. *
  27358. * const line = new THREE.LineSegments( wireframe );
  27359. * line.material.depthWrite = false;
  27360. * line.material.opacity = 0.25;
  27361. * line.material.transparent = true;
  27362. *
  27363. * scene.add( line );
  27364. * ```
  27365. *
  27366. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27367. *
  27368. * @augments BufferGeometry
  27369. */
  27370. class WireframeGeometry extends BufferGeometry {
  27371. /**
  27372. * Constructs a new wireframe geometry.
  27373. *
  27374. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27375. */
  27376. constructor( geometry = null ) {
  27377. super();
  27378. this.type = 'WireframeGeometry';
  27379. /**
  27380. * Holds the constructor parameters that have been
  27381. * used to generate the geometry. Any modification
  27382. * after instantiation does not change the geometry.
  27383. *
  27384. * @type {Object}
  27385. */
  27386. this.parameters = {
  27387. geometry: geometry
  27388. };
  27389. if ( geometry !== null ) {
  27390. // buffer
  27391. const vertices = [];
  27392. const edges = new Set();
  27393. // helper variables
  27394. const start = new Vector3();
  27395. const end = new Vector3();
  27396. if ( geometry.index !== null ) {
  27397. // indexed BufferGeometry
  27398. const position = geometry.attributes.position;
  27399. const indices = geometry.index;
  27400. let groups = geometry.groups;
  27401. if ( groups.length === 0 ) {
  27402. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27403. }
  27404. // create a data structure that contains all edges without duplicates
  27405. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27406. const group = groups[ o ];
  27407. const groupStart = group.start;
  27408. const groupCount = group.count;
  27409. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27410. for ( let j = 0; j < 3; j ++ ) {
  27411. const index1 = indices.getX( i + j );
  27412. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27413. start.fromBufferAttribute( position, index1 );
  27414. end.fromBufferAttribute( position, index2 );
  27415. if ( isUniqueEdge( start, end, edges ) === true ) {
  27416. vertices.push( start.x, start.y, start.z );
  27417. vertices.push( end.x, end.y, end.z );
  27418. }
  27419. }
  27420. }
  27421. }
  27422. } else {
  27423. // non-indexed BufferGeometry
  27424. const position = geometry.attributes.position;
  27425. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27426. for ( let j = 0; j < 3; j ++ ) {
  27427. // three edges per triangle, an edge is represented as (index1, index2)
  27428. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27429. const index1 = 3 * i + j;
  27430. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27431. start.fromBufferAttribute( position, index1 );
  27432. end.fromBufferAttribute( position, index2 );
  27433. if ( isUniqueEdge( start, end, edges ) === true ) {
  27434. vertices.push( start.x, start.y, start.z );
  27435. vertices.push( end.x, end.y, end.z );
  27436. }
  27437. }
  27438. }
  27439. }
  27440. // build geometry
  27441. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27442. }
  27443. }
  27444. copy( source ) {
  27445. super.copy( source );
  27446. this.parameters = Object.assign( {}, source.parameters );
  27447. return this;
  27448. }
  27449. }
  27450. function isUniqueEdge( start, end, edges ) {
  27451. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27452. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27453. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27454. return false;
  27455. } else {
  27456. edges.add( hash1 );
  27457. edges.add( hash2 );
  27458. return true;
  27459. }
  27460. }
  27461. var Geometries = /*#__PURE__*/Object.freeze({
  27462. __proto__: null,
  27463. BoxGeometry: BoxGeometry,
  27464. CapsuleGeometry: CapsuleGeometry,
  27465. CircleGeometry: CircleGeometry,
  27466. ConeGeometry: ConeGeometry,
  27467. CylinderGeometry: CylinderGeometry,
  27468. DodecahedronGeometry: DodecahedronGeometry,
  27469. EdgesGeometry: EdgesGeometry,
  27470. ExtrudeGeometry: ExtrudeGeometry,
  27471. IcosahedronGeometry: IcosahedronGeometry,
  27472. LatheGeometry: LatheGeometry,
  27473. OctahedronGeometry: OctahedronGeometry,
  27474. PlaneGeometry: PlaneGeometry,
  27475. PolyhedronGeometry: PolyhedronGeometry,
  27476. RingGeometry: RingGeometry,
  27477. ShapeGeometry: ShapeGeometry,
  27478. SphereGeometry: SphereGeometry,
  27479. TetrahedronGeometry: TetrahedronGeometry,
  27480. TorusGeometry: TorusGeometry,
  27481. TorusKnotGeometry: TorusKnotGeometry,
  27482. TubeGeometry: TubeGeometry,
  27483. WireframeGeometry: WireframeGeometry
  27484. });
  27485. /**
  27486. * This material can receive shadows, but otherwise is completely transparent.
  27487. *
  27488. * ```js
  27489. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27490. * geometry.rotateX( - Math.PI / 2 );
  27491. *
  27492. * const material = new THREE.ShadowMaterial();
  27493. * material.opacity = 0.2;
  27494. *
  27495. * const plane = new THREE.Mesh( geometry, material );
  27496. * plane.position.y = -200;
  27497. * plane.receiveShadow = true;
  27498. * scene.add( plane );
  27499. * ```
  27500. *
  27501. * @augments Material
  27502. */
  27503. class ShadowMaterial extends Material {
  27504. /**
  27505. * Constructs a new shadow material.
  27506. *
  27507. * @param {Object} [parameters] - An object with one or more properties
  27508. * defining the material's appearance. Any property of the material
  27509. * (including any property from inherited materials) can be passed
  27510. * in here. Color values can be passed any type of value accepted
  27511. * by {@link Color#set}.
  27512. */
  27513. constructor( parameters ) {
  27514. super();
  27515. /**
  27516. * This flag can be used for type testing.
  27517. *
  27518. * @type {boolean}
  27519. * @readonly
  27520. * @default true
  27521. */
  27522. this.isShadowMaterial = true;
  27523. this.type = 'ShadowMaterial';
  27524. /**
  27525. * Color of the material.
  27526. *
  27527. * @type {Color}
  27528. * @default (0,0,0)
  27529. */
  27530. this.color = new Color( 0x000000 );
  27531. /**
  27532. * Overwritten since shadow materials are transparent
  27533. * by default.
  27534. *
  27535. * @type {boolean}
  27536. * @default true
  27537. */
  27538. this.transparent = true;
  27539. /**
  27540. * Whether the material is affected by fog or not.
  27541. *
  27542. * @type {boolean}
  27543. * @default true
  27544. */
  27545. this.fog = true;
  27546. this.setValues( parameters );
  27547. }
  27548. copy( source ) {
  27549. super.copy( source );
  27550. this.color.copy( source.color );
  27551. this.fog = source.fog;
  27552. return this;
  27553. }
  27554. }
  27555. /**
  27556. * This class works just like {@link ShaderMaterial}, except that definitions
  27557. * of built-in uniforms and attributes are not automatically prepended to the
  27558. * GLSL shader code.
  27559. *
  27560. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27561. *
  27562. * @augments ShaderMaterial
  27563. */
  27564. class RawShaderMaterial extends ShaderMaterial {
  27565. /**
  27566. * Constructs a new raw shader material.
  27567. *
  27568. * @param {Object} [parameters] - An object with one or more properties
  27569. * defining the material's appearance. Any property of the material
  27570. * (including any property from inherited materials) can be passed
  27571. * in here. Color values can be passed any type of value accepted
  27572. * by {@link Color#set}.
  27573. */
  27574. constructor( parameters ) {
  27575. super( parameters );
  27576. /**
  27577. * This flag can be used for type testing.
  27578. *
  27579. * @type {boolean}
  27580. * @readonly
  27581. * @default true
  27582. */
  27583. this.isRawShaderMaterial = true;
  27584. this.type = 'RawShaderMaterial';
  27585. }
  27586. }
  27587. /**
  27588. * A standard physically based material, using Metallic-Roughness workflow.
  27589. *
  27590. * Physically based rendering (PBR) has recently become the standard in many
  27591. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27592. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27593. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27594. *
  27595. * This approach differs from older approaches in that instead of using
  27596. * approximations for the way in which light interacts with a surface, a
  27597. * physically correct model is used. The idea is that, instead of tweaking
  27598. * materials to look good under specific lighting, a material can be created
  27599. * that will react 'correctly' under all lighting scenarios.
  27600. *
  27601. * In practice this gives a more accurate and realistic looking result than
  27602. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27603. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27604. * shading.
  27605. *
  27606. * Note that for best results you should always specify an environment map when using this material.
  27607. *
  27608. * For a non-technical introduction to the concept of PBR and how to set up a
  27609. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27610. *
  27611. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27612. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27613. *
  27614. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27615. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27616. * (pdf), by Brent Burley.
  27617. *
  27618. * @augments Material
  27619. */
  27620. class MeshStandardMaterial extends Material {
  27621. /**
  27622. * Constructs a new mesh standard material.
  27623. *
  27624. * @param {Object} [parameters] - An object with one or more properties
  27625. * defining the material's appearance. Any property of the material
  27626. * (including any property from inherited materials) can be passed
  27627. * in here. Color values can be passed any type of value accepted
  27628. * by {@link Color#set}.
  27629. */
  27630. constructor( parameters ) {
  27631. super();
  27632. /**
  27633. * This flag can be used for type testing.
  27634. *
  27635. * @type {boolean}
  27636. * @readonly
  27637. * @default true
  27638. */
  27639. this.isMeshStandardMaterial = true;
  27640. this.type = 'MeshStandardMaterial';
  27641. this.defines = { 'STANDARD': '' };
  27642. /**
  27643. * Color of the material.
  27644. *
  27645. * @type {Color}
  27646. * @default (1,1,1)
  27647. */
  27648. this.color = new Color( 0xffffff ); // diffuse
  27649. /**
  27650. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27651. * means fully diffuse. If `roughnessMap` is also provided,
  27652. * both values are multiplied.
  27653. *
  27654. * @type {number}
  27655. * @default 1
  27656. */
  27657. this.roughness = 1.0;
  27658. /**
  27659. * How much the material is like a metal. Non-metallic materials such as wood
  27660. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27661. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27662. * If `metalnessMap` is also provided, both values are multiplied.
  27663. *
  27664. * @type {number}
  27665. * @default 0
  27666. */
  27667. this.metalness = 0.0;
  27668. /**
  27669. * The color map. May optionally include an alpha channel, typically combined
  27670. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27671. * color is modulated by the diffuse `color`.
  27672. *
  27673. * @type {?Texture}
  27674. * @default null
  27675. */
  27676. this.map = null;
  27677. /**
  27678. * The light map. Requires a second set of UVs.
  27679. *
  27680. * @type {?Texture}
  27681. * @default null
  27682. */
  27683. this.lightMap = null;
  27684. /**
  27685. * Intensity of the baked light.
  27686. *
  27687. * @type {number}
  27688. * @default 1
  27689. */
  27690. this.lightMapIntensity = 1.0;
  27691. /**
  27692. * The red channel of this texture is used as the ambient occlusion map.
  27693. * Requires a second set of UVs.
  27694. *
  27695. * @type {?Texture}
  27696. * @default null
  27697. */
  27698. this.aoMap = null;
  27699. /**
  27700. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27701. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27702. * red channel is also `1`, ambient light is fully occluded on a surface.
  27703. *
  27704. * @type {number}
  27705. * @default 1
  27706. */
  27707. this.aoMapIntensity = 1.0;
  27708. /**
  27709. * Emissive (light) color of the material, essentially a solid color
  27710. * unaffected by other lighting.
  27711. *
  27712. * @type {Color}
  27713. * @default (0,0,0)
  27714. */
  27715. this.emissive = new Color( 0x000000 );
  27716. /**
  27717. * Intensity of the emissive light. Modulates the emissive color.
  27718. *
  27719. * @type {number}
  27720. * @default 1
  27721. */
  27722. this.emissiveIntensity = 1.0;
  27723. /**
  27724. * Set emissive (glow) map. The emissive map color is modulated by the
  27725. * emissive color and the emissive intensity. If you have an emissive map,
  27726. * be sure to set the emissive color to something other than black.
  27727. *
  27728. * @type {?Texture}
  27729. * @default null
  27730. */
  27731. this.emissiveMap = null;
  27732. /**
  27733. * The texture to create a bump map. The black and white values map to the
  27734. * perceived depth in relation to the lights. Bump doesn't actually affect
  27735. * the geometry of the object, only the lighting. If a normal map is defined
  27736. * this will be ignored.
  27737. *
  27738. * @type {?Texture}
  27739. * @default null
  27740. */
  27741. this.bumpMap = null;
  27742. /**
  27743. * How much the bump map affects the material. Typical range is `[0,1]`.
  27744. *
  27745. * @type {number}
  27746. * @default 1
  27747. */
  27748. this.bumpScale = 1;
  27749. /**
  27750. * The texture to create a normal map. The RGB values affect the surface
  27751. * normal for each pixel fragment and change the way the color is lit. Normal
  27752. * maps do not change the actual shape of the surface, only the lighting. In
  27753. * case the material has a normal map authored using the left handed
  27754. * convention, the `y` component of `normalScale` should be negated to compensate
  27755. * for the different handedness.
  27756. *
  27757. * @type {?Texture}
  27758. * @default null
  27759. */
  27760. this.normalMap = null;
  27761. /**
  27762. * The type of normal map.
  27763. *
  27764. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27765. * @default TangentSpaceNormalMap
  27766. */
  27767. this.normalMapType = TangentSpaceNormalMap;
  27768. /**
  27769. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27770. *
  27771. * @type {Vector2}
  27772. * @default (1,1)
  27773. */
  27774. this.normalScale = new Vector2( 1, 1 );
  27775. /**
  27776. * The displacement map affects the position of the mesh's vertices. Unlike
  27777. * other maps which only affect the light and shade of the material the
  27778. * displaced vertices can cast shadows, block other objects, and otherwise
  27779. * act as real geometry. The displacement texture is an image where the value
  27780. * of each pixel (white being the highest) is mapped against, and
  27781. * repositions, the vertices of the mesh.
  27782. *
  27783. * @type {?Texture}
  27784. * @default null
  27785. */
  27786. this.displacementMap = null;
  27787. /**
  27788. * How much the displacement map affects the mesh (where black is no
  27789. * displacement, and white is maximum displacement). Without a displacement
  27790. * map set, this value is not applied.
  27791. *
  27792. * @type {number}
  27793. * @default 0
  27794. */
  27795. this.displacementScale = 1;
  27796. /**
  27797. * The offset of the displacement map's values on the mesh's vertices.
  27798. * The bias is added to the scaled sample of the displacement map.
  27799. * Without a displacement map set, this value is not applied.
  27800. *
  27801. * @type {number}
  27802. * @default 0
  27803. */
  27804. this.displacementBias = 0;
  27805. /**
  27806. * The green channel of this texture is used to alter the roughness of the
  27807. * material.
  27808. *
  27809. * @type {?Texture}
  27810. * @default null
  27811. */
  27812. this.roughnessMap = null;
  27813. /**
  27814. * The blue channel of this texture is used to alter the metalness of the
  27815. * material.
  27816. *
  27817. * @type {?Texture}
  27818. * @default null
  27819. */
  27820. this.metalnessMap = null;
  27821. /**
  27822. * The alpha map is a grayscale texture that controls the opacity across the
  27823. * surface (black: fully transparent; white: fully opaque).
  27824. *
  27825. * Only the color of the texture is used, ignoring the alpha channel if one
  27826. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27827. * when sampling this texture due to the extra bit of precision provided for
  27828. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27829. * luminance/alpha textures will also still work as expected.
  27830. *
  27831. * @type {?Texture}
  27832. * @default null
  27833. */
  27834. this.alphaMap = null;
  27835. /**
  27836. * The environment map. To ensure a physically correct rendering, environment maps
  27837. * are internally pre-processed with {@link PMREMGenerator}.
  27838. *
  27839. * @type {?Texture}
  27840. * @default null
  27841. */
  27842. this.envMap = null;
  27843. /**
  27844. * The rotation of the environment map in radians.
  27845. *
  27846. * @type {Euler}
  27847. * @default (0,0,0)
  27848. */
  27849. this.envMapRotation = new Euler();
  27850. /**
  27851. * Scales the effect of the environment map by multiplying its color.
  27852. *
  27853. * @type {number}
  27854. * @default 1
  27855. */
  27856. this.envMapIntensity = 1.0;
  27857. /**
  27858. * Renders the geometry as a wireframe.
  27859. *
  27860. * @type {boolean}
  27861. * @default false
  27862. */
  27863. this.wireframe = false;
  27864. /**
  27865. * Controls the thickness of the wireframe.
  27866. *
  27867. * Can only be used with {@link SVGRenderer}.
  27868. *
  27869. * @type {number}
  27870. * @default 1
  27871. */
  27872. this.wireframeLinewidth = 1;
  27873. /**
  27874. * Defines appearance of wireframe ends.
  27875. *
  27876. * Can only be used with {@link SVGRenderer}.
  27877. *
  27878. * @type {('round'|'bevel'|'miter')}
  27879. * @default 'round'
  27880. */
  27881. this.wireframeLinecap = 'round';
  27882. /**
  27883. * Defines appearance of wireframe joints.
  27884. *
  27885. * Can only be used with {@link SVGRenderer}.
  27886. *
  27887. * @type {('round'|'bevel'|'miter')}
  27888. * @default 'round'
  27889. */
  27890. this.wireframeLinejoin = 'round';
  27891. /**
  27892. * Whether the material is rendered with flat shading or not.
  27893. *
  27894. * @type {boolean}
  27895. * @default false
  27896. */
  27897. this.flatShading = false;
  27898. /**
  27899. * Whether the material is affected by fog or not.
  27900. *
  27901. * @type {boolean}
  27902. * @default true
  27903. */
  27904. this.fog = true;
  27905. this.setValues( parameters );
  27906. }
  27907. copy( source ) {
  27908. super.copy( source );
  27909. this.defines = { 'STANDARD': '' };
  27910. this.color.copy( source.color );
  27911. this.roughness = source.roughness;
  27912. this.metalness = source.metalness;
  27913. this.map = source.map;
  27914. this.lightMap = source.lightMap;
  27915. this.lightMapIntensity = source.lightMapIntensity;
  27916. this.aoMap = source.aoMap;
  27917. this.aoMapIntensity = source.aoMapIntensity;
  27918. this.emissive.copy( source.emissive );
  27919. this.emissiveMap = source.emissiveMap;
  27920. this.emissiveIntensity = source.emissiveIntensity;
  27921. this.bumpMap = source.bumpMap;
  27922. this.bumpScale = source.bumpScale;
  27923. this.normalMap = source.normalMap;
  27924. this.normalMapType = source.normalMapType;
  27925. this.normalScale.copy( source.normalScale );
  27926. this.displacementMap = source.displacementMap;
  27927. this.displacementScale = source.displacementScale;
  27928. this.displacementBias = source.displacementBias;
  27929. this.roughnessMap = source.roughnessMap;
  27930. this.metalnessMap = source.metalnessMap;
  27931. this.alphaMap = source.alphaMap;
  27932. this.envMap = source.envMap;
  27933. this.envMapRotation.copy( source.envMapRotation );
  27934. this.envMapIntensity = source.envMapIntensity;
  27935. this.wireframe = source.wireframe;
  27936. this.wireframeLinewidth = source.wireframeLinewidth;
  27937. this.wireframeLinecap = source.wireframeLinecap;
  27938. this.wireframeLinejoin = source.wireframeLinejoin;
  27939. this.flatShading = source.flatShading;
  27940. this.fog = source.fog;
  27941. return this;
  27942. }
  27943. }
  27944. /**
  27945. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  27946. * physically-based rendering properties:
  27947. *
  27948. * - Anisotropy: Ability to represent the anisotropic property of materials
  27949. * as observable with brushed metals.
  27950. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  27951. * a clear, reflective layer on top of another layer that may be irregular or rough.
  27952. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  27953. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  27954. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  27955. * wings of many insects.
  27956. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  27957. * transparent materials are less reflective. Physically-based transmission provides a more
  27958. * realistic option for thin, transparent surfaces like glass.
  27959. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  27960. * - Sheen: Can be used for representing cloth and fabric materials.
  27961. *
  27962. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  27963. * higher performance cost, per pixel, than other three.js materials. Most
  27964. * effects are disabled by default, and add cost as they are enabled. For
  27965. * best results, always specify an environment map when using this material.
  27966. *
  27967. * @augments MeshStandardMaterial
  27968. */
  27969. class MeshPhysicalMaterial extends MeshStandardMaterial {
  27970. /**
  27971. * Constructs a new mesh physical material.
  27972. *
  27973. * @param {Object} [parameters] - An object with one or more properties
  27974. * defining the material's appearance. Any property of the material
  27975. * (including any property from inherited materials) can be passed
  27976. * in here. Color values can be passed any type of value accepted
  27977. * by {@link Color#set}.
  27978. */
  27979. constructor( parameters ) {
  27980. super();
  27981. /**
  27982. * This flag can be used for type testing.
  27983. *
  27984. * @type {boolean}
  27985. * @readonly
  27986. * @default true
  27987. */
  27988. this.isMeshPhysicalMaterial = true;
  27989. this.defines = {
  27990. 'STANDARD': '',
  27991. 'PHYSICAL': ''
  27992. };
  27993. this.type = 'MeshPhysicalMaterial';
  27994. /**
  27995. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  27996. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  27997. * property provides additional rotation to the vectors in the texture.
  27998. *
  27999. * @type {number}
  28000. * @default 1
  28001. */
  28002. this.anisotropyRotation = 0;
  28003. /**
  28004. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28005. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28006. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28007. *
  28008. * @type {?Texture}
  28009. * @default null
  28010. */
  28011. this.anisotropyMap = null;
  28012. /**
  28013. * The red channel of this texture is multiplied against `clearcoat`,
  28014. * for per-pixel control over a coating's intensity.
  28015. *
  28016. * @type {?Texture}
  28017. * @default null
  28018. */
  28019. this.clearcoatMap = null;
  28020. /**
  28021. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28022. *
  28023. * @type {number}
  28024. * @default 0
  28025. */
  28026. this.clearcoatRoughness = 0.0;
  28027. /**
  28028. * The green channel of this texture is multiplied against
  28029. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28030. *
  28031. * @type {?Texture}
  28032. * @default null
  28033. */
  28034. this.clearcoatRoughnessMap = null;
  28035. /**
  28036. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28037. * `(0,0)` to `(1,1)`.
  28038. *
  28039. * @type {Vector2}
  28040. * @default (1,1)
  28041. */
  28042. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28043. /**
  28044. * Can be used to enable independent normals for the clear coat layer.
  28045. *
  28046. * @type {?Texture}
  28047. * @default null
  28048. */
  28049. this.clearcoatNormalMap = null;
  28050. /**
  28051. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28052. *
  28053. * @type {number}
  28054. * @default 1.5
  28055. */
  28056. this.ior = 1.5;
  28057. /**
  28058. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28059. * corresponds to an index-of-refraction of `1.5`.
  28060. *
  28061. * This models the reflectivity of non-metallic materials. It has no effect
  28062. * when `metalness` is `1.0`
  28063. *
  28064. * @name MeshPhysicalMaterial#reflectivity
  28065. * @type {number}
  28066. * @default 0.5
  28067. */
  28068. Object.defineProperty( this, 'reflectivity', {
  28069. get: function () {
  28070. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28071. },
  28072. set: function ( reflectivity ) {
  28073. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28074. }
  28075. } );
  28076. /**
  28077. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28078. * control over iridescence.
  28079. *
  28080. * @type {?Texture}
  28081. * @default null
  28082. */
  28083. this.iridescenceMap = null;
  28084. /**
  28085. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28086. * Between `1.0` to `2.333`.
  28087. *
  28088. * @type {number}
  28089. * @default 1.3
  28090. */
  28091. this.iridescenceIOR = 1.3;
  28092. /**
  28093. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28094. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28095. *
  28096. * @type {Array<number,number>}
  28097. * @default [100,400]
  28098. */
  28099. this.iridescenceThicknessRange = [ 100, 400 ];
  28100. /**
  28101. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28102. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28103. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28104. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28105. * - Values in-between will linearly interpolate between the elements of the array.
  28106. *
  28107. * @type {?Texture}
  28108. * @default null
  28109. */
  28110. this.iridescenceThicknessMap = null;
  28111. /**
  28112. * The sheen tint.
  28113. *
  28114. * @type {Color}
  28115. * @default (0,0,0)
  28116. */
  28117. this.sheenColor = new Color( 0x000000 );
  28118. /**
  28119. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28120. * over sheen tint.
  28121. *
  28122. * @type {?Texture}
  28123. * @default null
  28124. */
  28125. this.sheenColorMap = null;
  28126. /**
  28127. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28128. *
  28129. * @type {number}
  28130. * @default 1
  28131. */
  28132. this.sheenRoughness = 1.0;
  28133. /**
  28134. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28135. * over sheen roughness.
  28136. *
  28137. * @type {?Texture}
  28138. * @default null
  28139. */
  28140. this.sheenRoughnessMap = null;
  28141. /**
  28142. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28143. * optical transparency.
  28144. *
  28145. * @type {?Texture}
  28146. * @default null
  28147. */
  28148. this.transmissionMap = null;
  28149. /**
  28150. * The thickness of the volume beneath the surface. The value is given in the
  28151. * coordinate space of the mesh. If the value is `0` the material is
  28152. * thin-walled. Otherwise the material is a volume boundary.
  28153. *
  28154. * @type {number}
  28155. * @default 0
  28156. */
  28157. this.thickness = 0;
  28158. /**
  28159. * A texture that defines the thickness, stored in the green channel. This will
  28160. * be multiplied by `thickness`.
  28161. *
  28162. * @type {?Texture}
  28163. * @default null
  28164. */
  28165. this.thicknessMap = null;
  28166. /**
  28167. * Density of the medium given as the average distance that light travels in
  28168. * the medium before interacting with a particle. The value is given in world
  28169. * space units, and must be greater than zero.
  28170. *
  28171. * @type {number}
  28172. * @default Infinity
  28173. */
  28174. this.attenuationDistance = Infinity;
  28175. /**
  28176. * The color that white light turns into due to absorption when reaching the
  28177. * attenuation distance.
  28178. *
  28179. * @type {Color}
  28180. * @default (1,1,1)
  28181. */
  28182. this.attenuationColor = new Color( 1, 1, 1 );
  28183. /**
  28184. * A float that scales the amount of specular reflection for non-metals only.
  28185. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28186. *
  28187. * @type {number}
  28188. * @default 1
  28189. */
  28190. this.specularIntensity = 1.0;
  28191. /**
  28192. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28193. * for per-pixel control over specular intensity.
  28194. *
  28195. * @type {?Texture}
  28196. * @default null
  28197. */
  28198. this.specularIntensityMap = null;
  28199. /**
  28200. * Tints the specular reflection at normal incidence for non-metals only.
  28201. *
  28202. * @type {Color}
  28203. * @default (1,1,1)
  28204. */
  28205. this.specularColor = new Color( 1, 1, 1 );
  28206. /**
  28207. * The RGB channels of this texture are multiplied against `specularColor`,
  28208. * for per-pixel control over specular color.
  28209. *
  28210. * @type {?Texture}
  28211. * @default null
  28212. */
  28213. this.specularColorMap = null;
  28214. this._anisotropy = 0;
  28215. this._clearcoat = 0;
  28216. this._dispersion = 0;
  28217. this._iridescence = 0;
  28218. this._sheen = 0.0;
  28219. this._transmission = 0;
  28220. this.setValues( parameters );
  28221. }
  28222. /**
  28223. * The anisotropy strength.
  28224. *
  28225. * @type {number}
  28226. * @default 0
  28227. */
  28228. get anisotropy() {
  28229. return this._anisotropy;
  28230. }
  28231. set anisotropy( value ) {
  28232. if ( this._anisotropy > 0 !== value > 0 ) {
  28233. this.version ++;
  28234. }
  28235. this._anisotropy = value;
  28236. }
  28237. /**
  28238. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28239. * clear coat related properties to enable multilayer materials that have a
  28240. * thin translucent layer over the base layer.
  28241. *
  28242. * @type {number}
  28243. * @default 0
  28244. */
  28245. get clearcoat() {
  28246. return this._clearcoat;
  28247. }
  28248. set clearcoat( value ) {
  28249. if ( this._clearcoat > 0 !== value > 0 ) {
  28250. this.version ++;
  28251. }
  28252. this._clearcoat = value;
  28253. }
  28254. /**
  28255. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28256. * the surface and the viewer, from `0.0` to `1.0`.
  28257. *
  28258. * @type {number}
  28259. * @default 0
  28260. */
  28261. get iridescence() {
  28262. return this._iridescence;
  28263. }
  28264. set iridescence( value ) {
  28265. if ( this._iridescence > 0 !== value > 0 ) {
  28266. this.version ++;
  28267. }
  28268. this._iridescence = value;
  28269. }
  28270. /**
  28271. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28272. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28273. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28274. *
  28275. * @type {number}
  28276. * @default 0
  28277. */
  28278. get dispersion() {
  28279. return this._dispersion;
  28280. }
  28281. set dispersion( value ) {
  28282. if ( this._dispersion > 0 !== value > 0 ) {
  28283. this.version ++;
  28284. }
  28285. this._dispersion = value;
  28286. }
  28287. /**
  28288. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28289. *
  28290. * @type {number}
  28291. * @default 0
  28292. */
  28293. get sheen() {
  28294. return this._sheen;
  28295. }
  28296. set sheen( value ) {
  28297. if ( this._sheen > 0 !== value > 0 ) {
  28298. this.version ++;
  28299. }
  28300. this._sheen = value;
  28301. }
  28302. /**
  28303. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28304. *
  28305. * Thin, transparent or semitransparent, plastic or glass materials remain
  28306. * largely reflective even if they are fully transmissive. The transmission
  28307. * property can be used to model these materials.
  28308. *
  28309. * When transmission is non-zero, `opacity` should be set to `1`.
  28310. *
  28311. * @type {number}
  28312. * @default 0
  28313. */
  28314. get transmission() {
  28315. return this._transmission;
  28316. }
  28317. set transmission( value ) {
  28318. if ( this._transmission > 0 !== value > 0 ) {
  28319. this.version ++;
  28320. }
  28321. this._transmission = value;
  28322. }
  28323. copy( source ) {
  28324. super.copy( source );
  28325. this.defines = {
  28326. 'STANDARD': '',
  28327. 'PHYSICAL': ''
  28328. };
  28329. this.anisotropy = source.anisotropy;
  28330. this.anisotropyRotation = source.anisotropyRotation;
  28331. this.anisotropyMap = source.anisotropyMap;
  28332. this.clearcoat = source.clearcoat;
  28333. this.clearcoatMap = source.clearcoatMap;
  28334. this.clearcoatRoughness = source.clearcoatRoughness;
  28335. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28336. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28337. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28338. this.dispersion = source.dispersion;
  28339. this.ior = source.ior;
  28340. this.iridescence = source.iridescence;
  28341. this.iridescenceMap = source.iridescenceMap;
  28342. this.iridescenceIOR = source.iridescenceIOR;
  28343. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28344. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28345. this.sheen = source.sheen;
  28346. this.sheenColor.copy( source.sheenColor );
  28347. this.sheenColorMap = source.sheenColorMap;
  28348. this.sheenRoughness = source.sheenRoughness;
  28349. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28350. this.transmission = source.transmission;
  28351. this.transmissionMap = source.transmissionMap;
  28352. this.thickness = source.thickness;
  28353. this.thicknessMap = source.thicknessMap;
  28354. this.attenuationDistance = source.attenuationDistance;
  28355. this.attenuationColor.copy( source.attenuationColor );
  28356. this.specularIntensity = source.specularIntensity;
  28357. this.specularIntensityMap = source.specularIntensityMap;
  28358. this.specularColor.copy( source.specularColor );
  28359. this.specularColorMap = source.specularColorMap;
  28360. return this;
  28361. }
  28362. }
  28363. /**
  28364. * A material for shiny surfaces with specular highlights.
  28365. *
  28366. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28367. * model for calculating reflectance. Unlike the Lambertian model used in the
  28368. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28369. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28370. *
  28371. * Performance will generally be greater when using this material over the
  28372. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28373. * some graphical accuracy.
  28374. *
  28375. * @augments Material
  28376. */
  28377. class MeshPhongMaterial extends Material {
  28378. /**
  28379. * Constructs a new mesh phong material.
  28380. *
  28381. * @param {Object} [parameters] - An object with one or more properties
  28382. * defining the material's appearance. Any property of the material
  28383. * (including any property from inherited materials) can be passed
  28384. * in here. Color values can be passed any type of value accepted
  28385. * by {@link Color#set}.
  28386. */
  28387. constructor( parameters ) {
  28388. super();
  28389. /**
  28390. * This flag can be used for type testing.
  28391. *
  28392. * @type {boolean}
  28393. * @readonly
  28394. * @default true
  28395. */
  28396. this.isMeshPhongMaterial = true;
  28397. this.type = 'MeshPhongMaterial';
  28398. /**
  28399. * Color of the material.
  28400. *
  28401. * @type {Color}
  28402. * @default (1,1,1)
  28403. */
  28404. this.color = new Color( 0xffffff ); // diffuse
  28405. /**
  28406. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28407. *
  28408. * This defines how shiny the material is and the color of its shine.
  28409. *
  28410. * @type {Color}
  28411. */
  28412. this.specular = new Color( 0x111111 );
  28413. /**
  28414. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28415. *
  28416. * @type {number}
  28417. * @default 30
  28418. */
  28419. this.shininess = 30;
  28420. /**
  28421. * The color map. May optionally include an alpha channel, typically combined
  28422. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28423. * color is modulated by the diffuse `color`.
  28424. *
  28425. * @type {?Texture}
  28426. * @default null
  28427. */
  28428. this.map = null;
  28429. /**
  28430. * The light map. Requires a second set of UVs.
  28431. *
  28432. * @type {?Texture}
  28433. * @default null
  28434. */
  28435. this.lightMap = null;
  28436. /**
  28437. * Intensity of the baked light.
  28438. *
  28439. * @type {number}
  28440. * @default 1
  28441. */
  28442. this.lightMapIntensity = 1.0;
  28443. /**
  28444. * The red channel of this texture is used as the ambient occlusion map.
  28445. * Requires a second set of UVs.
  28446. *
  28447. * @type {?Texture}
  28448. * @default null
  28449. */
  28450. this.aoMap = null;
  28451. /**
  28452. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28453. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28454. * red channel is also `1`, ambient light is fully occluded on a surface.
  28455. *
  28456. * @type {number}
  28457. * @default 1
  28458. */
  28459. this.aoMapIntensity = 1.0;
  28460. /**
  28461. * Emissive (light) color of the material, essentially a solid color
  28462. * unaffected by other lighting.
  28463. *
  28464. * @type {Color}
  28465. * @default (0,0,0)
  28466. */
  28467. this.emissive = new Color( 0x000000 );
  28468. /**
  28469. * Intensity of the emissive light. Modulates the emissive color.
  28470. *
  28471. * @type {number}
  28472. * @default 1
  28473. */
  28474. this.emissiveIntensity = 1.0;
  28475. /**
  28476. * Set emissive (glow) map. The emissive map color is modulated by the
  28477. * emissive color and the emissive intensity. If you have an emissive map,
  28478. * be sure to set the emissive color to something other than black.
  28479. *
  28480. * @type {?Texture}
  28481. * @default null
  28482. */
  28483. this.emissiveMap = null;
  28484. /**
  28485. * The texture to create a bump map. The black and white values map to the
  28486. * perceived depth in relation to the lights. Bump doesn't actually affect
  28487. * the geometry of the object, only the lighting. If a normal map is defined
  28488. * this will be ignored.
  28489. *
  28490. * @type {?Texture}
  28491. * @default null
  28492. */
  28493. this.bumpMap = null;
  28494. /**
  28495. * How much the bump map affects the material. Typical range is `[0,1]`.
  28496. *
  28497. * @type {number}
  28498. * @default 1
  28499. */
  28500. this.bumpScale = 1;
  28501. /**
  28502. * The texture to create a normal map. The RGB values affect the surface
  28503. * normal for each pixel fragment and change the way the color is lit. Normal
  28504. * maps do not change the actual shape of the surface, only the lighting. In
  28505. * case the material has a normal map authored using the left handed
  28506. * convention, the `y` component of `normalScale` should be negated to compensate
  28507. * for the different handedness.
  28508. *
  28509. * @type {?Texture}
  28510. * @default null
  28511. */
  28512. this.normalMap = null;
  28513. /**
  28514. * The type of normal map.
  28515. *
  28516. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28517. * @default TangentSpaceNormalMap
  28518. */
  28519. this.normalMapType = TangentSpaceNormalMap;
  28520. /**
  28521. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28522. *
  28523. * @type {Vector2}
  28524. * @default (1,1)
  28525. */
  28526. this.normalScale = new Vector2( 1, 1 );
  28527. /**
  28528. * The displacement map affects the position of the mesh's vertices. Unlike
  28529. * other maps which only affect the light and shade of the material the
  28530. * displaced vertices can cast shadows, block other objects, and otherwise
  28531. * act as real geometry. The displacement texture is an image where the value
  28532. * of each pixel (white being the highest) is mapped against, and
  28533. * repositions, the vertices of the mesh.
  28534. *
  28535. * @type {?Texture}
  28536. * @default null
  28537. */
  28538. this.displacementMap = null;
  28539. /**
  28540. * How much the displacement map affects the mesh (where black is no
  28541. * displacement, and white is maximum displacement). Without a displacement
  28542. * map set, this value is not applied.
  28543. *
  28544. * @type {number}
  28545. * @default 0
  28546. */
  28547. this.displacementScale = 1;
  28548. /**
  28549. * The offset of the displacement map's values on the mesh's vertices.
  28550. * The bias is added to the scaled sample of the displacement map.
  28551. * Without a displacement map set, this value is not applied.
  28552. *
  28553. * @type {number}
  28554. * @default 0
  28555. */
  28556. this.displacementBias = 0;
  28557. /**
  28558. * The specular map value affects both how much the specular surface
  28559. * highlight contributes and how much of the environment map affects the
  28560. * surface.
  28561. *
  28562. * @type {?Texture}
  28563. * @default null
  28564. */
  28565. this.specularMap = null;
  28566. /**
  28567. * The alpha map is a grayscale texture that controls the opacity across the
  28568. * surface (black: fully transparent; white: fully opaque).
  28569. *
  28570. * Only the color of the texture is used, ignoring the alpha channel if one
  28571. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28572. * when sampling this texture due to the extra bit of precision provided for
  28573. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28574. * luminance/alpha textures will also still work as expected.
  28575. *
  28576. * @type {?Texture}
  28577. * @default null
  28578. */
  28579. this.alphaMap = null;
  28580. /**
  28581. * The environment map.
  28582. *
  28583. * @type {?Texture}
  28584. * @default null
  28585. */
  28586. this.envMap = null;
  28587. /**
  28588. * The rotation of the environment map in radians.
  28589. *
  28590. * @type {Euler}
  28591. * @default (0,0,0)
  28592. */
  28593. this.envMapRotation = new Euler();
  28594. /**
  28595. * How to combine the result of the surface's color with the environment map, if any.
  28596. *
  28597. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28598. * blend between the two colors.
  28599. *
  28600. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28601. * @default MultiplyOperation
  28602. */
  28603. this.combine = MultiplyOperation;
  28604. /**
  28605. * How much the environment map affects the surface.
  28606. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28607. *
  28608. * @type {number}
  28609. * @default 1
  28610. */
  28611. this.reflectivity = 1;
  28612. /**
  28613. * The index of refraction (IOR) of air (approximately 1) divided by the
  28614. * index of refraction of the material. It is used with environment mapping
  28615. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28616. * The refraction ratio should not exceed `1`.
  28617. *
  28618. * @type {number}
  28619. * @default 0.98
  28620. */
  28621. this.refractionRatio = 0.98;
  28622. /**
  28623. * Renders the geometry as a wireframe.
  28624. *
  28625. * @type {boolean}
  28626. * @default false
  28627. */
  28628. this.wireframe = false;
  28629. /**
  28630. * Controls the thickness of the wireframe.
  28631. *
  28632. * Can only be used with {@link SVGRenderer}.
  28633. *
  28634. * @type {number}
  28635. * @default 1
  28636. */
  28637. this.wireframeLinewidth = 1;
  28638. /**
  28639. * Defines appearance of wireframe ends.
  28640. *
  28641. * Can only be used with {@link SVGRenderer}.
  28642. *
  28643. * @type {('round'|'bevel'|'miter')}
  28644. * @default 'round'
  28645. */
  28646. this.wireframeLinecap = 'round';
  28647. /**
  28648. * Defines appearance of wireframe joints.
  28649. *
  28650. * Can only be used with {@link SVGRenderer}.
  28651. *
  28652. * @type {('round'|'bevel'|'miter')}
  28653. * @default 'round'
  28654. */
  28655. this.wireframeLinejoin = 'round';
  28656. /**
  28657. * Whether the material is rendered with flat shading or not.
  28658. *
  28659. * @type {boolean}
  28660. * @default false
  28661. */
  28662. this.flatShading = false;
  28663. /**
  28664. * Whether the material is affected by fog or not.
  28665. *
  28666. * @type {boolean}
  28667. * @default true
  28668. */
  28669. this.fog = true;
  28670. this.setValues( parameters );
  28671. }
  28672. copy( source ) {
  28673. super.copy( source );
  28674. this.color.copy( source.color );
  28675. this.specular.copy( source.specular );
  28676. this.shininess = source.shininess;
  28677. this.map = source.map;
  28678. this.lightMap = source.lightMap;
  28679. this.lightMapIntensity = source.lightMapIntensity;
  28680. this.aoMap = source.aoMap;
  28681. this.aoMapIntensity = source.aoMapIntensity;
  28682. this.emissive.copy( source.emissive );
  28683. this.emissiveMap = source.emissiveMap;
  28684. this.emissiveIntensity = source.emissiveIntensity;
  28685. this.bumpMap = source.bumpMap;
  28686. this.bumpScale = source.bumpScale;
  28687. this.normalMap = source.normalMap;
  28688. this.normalMapType = source.normalMapType;
  28689. this.normalScale.copy( source.normalScale );
  28690. this.displacementMap = source.displacementMap;
  28691. this.displacementScale = source.displacementScale;
  28692. this.displacementBias = source.displacementBias;
  28693. this.specularMap = source.specularMap;
  28694. this.alphaMap = source.alphaMap;
  28695. this.envMap = source.envMap;
  28696. this.envMapRotation.copy( source.envMapRotation );
  28697. this.combine = source.combine;
  28698. this.reflectivity = source.reflectivity;
  28699. this.refractionRatio = source.refractionRatio;
  28700. this.wireframe = source.wireframe;
  28701. this.wireframeLinewidth = source.wireframeLinewidth;
  28702. this.wireframeLinecap = source.wireframeLinecap;
  28703. this.wireframeLinejoin = source.wireframeLinejoin;
  28704. this.flatShading = source.flatShading;
  28705. this.fog = source.fog;
  28706. return this;
  28707. }
  28708. }
  28709. /**
  28710. * A material implementing toon shading.
  28711. *
  28712. * @augments Material
  28713. */
  28714. class MeshToonMaterial extends Material {
  28715. /**
  28716. * Constructs a new mesh toon material.
  28717. *
  28718. * @param {Object} [parameters] - An object with one or more properties
  28719. * defining the material's appearance. Any property of the material
  28720. * (including any property from inherited materials) can be passed
  28721. * in here. Color values can be passed any type of value accepted
  28722. * by {@link Color#set}.
  28723. */
  28724. constructor( parameters ) {
  28725. super();
  28726. /**
  28727. * This flag can be used for type testing.
  28728. *
  28729. * @type {boolean}
  28730. * @readonly
  28731. * @default true
  28732. */
  28733. this.isMeshToonMaterial = true;
  28734. this.defines = { 'TOON': '' };
  28735. this.type = 'MeshToonMaterial';
  28736. /**
  28737. * Color of the material.
  28738. *
  28739. * @type {Color}
  28740. * @default (1,1,1)
  28741. */
  28742. this.color = new Color( 0xffffff );
  28743. /**
  28744. * The color map. May optionally include an alpha channel, typically combined
  28745. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28746. * color is modulated by the diffuse `color`.
  28747. *
  28748. * @type {?Texture}
  28749. * @default null
  28750. */
  28751. this.map = null;
  28752. /**
  28753. * Gradient map for toon shading. It's required to set
  28754. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28755. * when using this type of texture.
  28756. *
  28757. * @type {?Texture}
  28758. * @default null
  28759. */
  28760. this.gradientMap = null;
  28761. /**
  28762. * The light map. Requires a second set of UVs.
  28763. *
  28764. * @type {?Texture}
  28765. * @default null
  28766. */
  28767. this.lightMap = null;
  28768. /**
  28769. * Intensity of the baked light.
  28770. *
  28771. * @type {number}
  28772. * @default 1
  28773. */
  28774. this.lightMapIntensity = 1.0;
  28775. /**
  28776. * The red channel of this texture is used as the ambient occlusion map.
  28777. * Requires a second set of UVs.
  28778. *
  28779. * @type {?Texture}
  28780. * @default null
  28781. */
  28782. this.aoMap = null;
  28783. /**
  28784. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28785. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28786. * red channel is also `1`, ambient light is fully occluded on a surface.
  28787. *
  28788. * @type {number}
  28789. * @default 1
  28790. */
  28791. this.aoMapIntensity = 1.0;
  28792. /**
  28793. * Emissive (light) color of the material, essentially a solid color
  28794. * unaffected by other lighting.
  28795. *
  28796. * @type {Color}
  28797. * @default (0,0,0)
  28798. */
  28799. this.emissive = new Color( 0x000000 );
  28800. /**
  28801. * Intensity of the emissive light. Modulates the emissive color.
  28802. *
  28803. * @type {number}
  28804. * @default 1
  28805. */
  28806. this.emissiveIntensity = 1.0;
  28807. /**
  28808. * Set emissive (glow) map. The emissive map color is modulated by the
  28809. * emissive color and the emissive intensity. If you have an emissive map,
  28810. * be sure to set the emissive color to something other than black.
  28811. *
  28812. * @type {?Texture}
  28813. * @default null
  28814. */
  28815. this.emissiveMap = null;
  28816. /**
  28817. * The texture to create a bump map. The black and white values map to the
  28818. * perceived depth in relation to the lights. Bump doesn't actually affect
  28819. * the geometry of the object, only the lighting. If a normal map is defined
  28820. * this will be ignored.
  28821. *
  28822. * @type {?Texture}
  28823. * @default null
  28824. */
  28825. this.bumpMap = null;
  28826. /**
  28827. * How much the bump map affects the material. Typical range is `[0,1]`.
  28828. *
  28829. * @type {number}
  28830. * @default 1
  28831. */
  28832. this.bumpScale = 1;
  28833. /**
  28834. * The texture to create a normal map. The RGB values affect the surface
  28835. * normal for each pixel fragment and change the way the color is lit. Normal
  28836. * maps do not change the actual shape of the surface, only the lighting. In
  28837. * case the material has a normal map authored using the left handed
  28838. * convention, the `y` component of `normalScale` should be negated to compensate
  28839. * for the different handedness.
  28840. *
  28841. * @type {?Texture}
  28842. * @default null
  28843. */
  28844. this.normalMap = null;
  28845. /**
  28846. * The type of normal map.
  28847. *
  28848. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28849. * @default TangentSpaceNormalMap
  28850. */
  28851. this.normalMapType = TangentSpaceNormalMap;
  28852. /**
  28853. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28854. *
  28855. * @type {Vector2}
  28856. * @default (1,1)
  28857. */
  28858. this.normalScale = new Vector2( 1, 1 );
  28859. /**
  28860. * The displacement map affects the position of the mesh's vertices. Unlike
  28861. * other maps which only affect the light and shade of the material the
  28862. * displaced vertices can cast shadows, block other objects, and otherwise
  28863. * act as real geometry. The displacement texture is an image where the value
  28864. * of each pixel (white being the highest) is mapped against, and
  28865. * repositions, the vertices of the mesh.
  28866. *
  28867. * @type {?Texture}
  28868. * @default null
  28869. */
  28870. this.displacementMap = null;
  28871. /**
  28872. * How much the displacement map affects the mesh (where black is no
  28873. * displacement, and white is maximum displacement). Without a displacement
  28874. * map set, this value is not applied.
  28875. *
  28876. * @type {number}
  28877. * @default 0
  28878. */
  28879. this.displacementScale = 1;
  28880. /**
  28881. * The offset of the displacement map's values on the mesh's vertices.
  28882. * The bias is added to the scaled sample of the displacement map.
  28883. * Without a displacement map set, this value is not applied.
  28884. *
  28885. * @type {number}
  28886. * @default 0
  28887. */
  28888. this.displacementBias = 0;
  28889. /**
  28890. * The alpha map is a grayscale texture that controls the opacity across the
  28891. * surface (black: fully transparent; white: fully opaque).
  28892. *
  28893. * Only the color of the texture is used, ignoring the alpha channel if one
  28894. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28895. * when sampling this texture due to the extra bit of precision provided for
  28896. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28897. * luminance/alpha textures will also still work as expected.
  28898. *
  28899. * @type {?Texture}
  28900. * @default null
  28901. */
  28902. this.alphaMap = null;
  28903. /**
  28904. * Renders the geometry as a wireframe.
  28905. *
  28906. * @type {boolean}
  28907. * @default false
  28908. */
  28909. this.wireframe = false;
  28910. /**
  28911. * Controls the thickness of the wireframe.
  28912. *
  28913. * Can only be used with {@link SVGRenderer}.
  28914. *
  28915. * @type {number}
  28916. * @default 1
  28917. */
  28918. this.wireframeLinewidth = 1;
  28919. /**
  28920. * Defines appearance of wireframe ends.
  28921. *
  28922. * Can only be used with {@link SVGRenderer}.
  28923. *
  28924. * @type {('round'|'bevel'|'miter')}
  28925. * @default 'round'
  28926. */
  28927. this.wireframeLinecap = 'round';
  28928. /**
  28929. * Defines appearance of wireframe joints.
  28930. *
  28931. * Can only be used with {@link SVGRenderer}.
  28932. *
  28933. * @type {('round'|'bevel'|'miter')}
  28934. * @default 'round'
  28935. */
  28936. this.wireframeLinejoin = 'round';
  28937. /**
  28938. * Whether the material is affected by fog or not.
  28939. *
  28940. * @type {boolean}
  28941. * @default true
  28942. */
  28943. this.fog = true;
  28944. this.setValues( parameters );
  28945. }
  28946. copy( source ) {
  28947. super.copy( source );
  28948. this.color.copy( source.color );
  28949. this.map = source.map;
  28950. this.gradientMap = source.gradientMap;
  28951. this.lightMap = source.lightMap;
  28952. this.lightMapIntensity = source.lightMapIntensity;
  28953. this.aoMap = source.aoMap;
  28954. this.aoMapIntensity = source.aoMapIntensity;
  28955. this.emissive.copy( source.emissive );
  28956. this.emissiveMap = source.emissiveMap;
  28957. this.emissiveIntensity = source.emissiveIntensity;
  28958. this.bumpMap = source.bumpMap;
  28959. this.bumpScale = source.bumpScale;
  28960. this.normalMap = source.normalMap;
  28961. this.normalMapType = source.normalMapType;
  28962. this.normalScale.copy( source.normalScale );
  28963. this.displacementMap = source.displacementMap;
  28964. this.displacementScale = source.displacementScale;
  28965. this.displacementBias = source.displacementBias;
  28966. this.alphaMap = source.alphaMap;
  28967. this.wireframe = source.wireframe;
  28968. this.wireframeLinewidth = source.wireframeLinewidth;
  28969. this.wireframeLinecap = source.wireframeLinecap;
  28970. this.wireframeLinejoin = source.wireframeLinejoin;
  28971. this.fog = source.fog;
  28972. return this;
  28973. }
  28974. }
  28975. /**
  28976. * A material that maps the normal vectors to RGB colors.
  28977. *
  28978. * @augments Material
  28979. */
  28980. class MeshNormalMaterial extends Material {
  28981. /**
  28982. * Constructs a new mesh normal material.
  28983. *
  28984. * @param {Object} [parameters] - An object with one or more properties
  28985. * defining the material's appearance. Any property of the material
  28986. * (including any property from inherited materials) can be passed
  28987. * in here. Color values can be passed any type of value accepted
  28988. * by {@link Color#set}.
  28989. */
  28990. constructor( parameters ) {
  28991. super();
  28992. /**
  28993. * This flag can be used for type testing.
  28994. *
  28995. * @type {boolean}
  28996. * @readonly
  28997. * @default true
  28998. */
  28999. this.isMeshNormalMaterial = true;
  29000. this.type = 'MeshNormalMaterial';
  29001. /**
  29002. * The texture to create a bump map. The black and white values map to the
  29003. * perceived depth in relation to the lights. Bump doesn't actually affect
  29004. * the geometry of the object, only the lighting. If a normal map is defined
  29005. * this will be ignored.
  29006. *
  29007. * @type {?Texture}
  29008. * @default null
  29009. */
  29010. this.bumpMap = null;
  29011. /**
  29012. * How much the bump map affects the material. Typical range is `[0,1]`.
  29013. *
  29014. * @type {number}
  29015. * @default 1
  29016. */
  29017. this.bumpScale = 1;
  29018. /**
  29019. * The texture to create a normal map. The RGB values affect the surface
  29020. * normal for each pixel fragment and change the way the color is lit. Normal
  29021. * maps do not change the actual shape of the surface, only the lighting. In
  29022. * case the material has a normal map authored using the left handed
  29023. * convention, the `y` component of `normalScale` should be negated to compensate
  29024. * for the different handedness.
  29025. *
  29026. * @type {?Texture}
  29027. * @default null
  29028. */
  29029. this.normalMap = null;
  29030. /**
  29031. * The type of normal map.
  29032. *
  29033. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29034. * @default TangentSpaceNormalMap
  29035. */
  29036. this.normalMapType = TangentSpaceNormalMap;
  29037. /**
  29038. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29039. *
  29040. * @type {Vector2}
  29041. * @default (1,1)
  29042. */
  29043. this.normalScale = new Vector2( 1, 1 );
  29044. /**
  29045. * The displacement map affects the position of the mesh's vertices. Unlike
  29046. * other maps which only affect the light and shade of the material the
  29047. * displaced vertices can cast shadows, block other objects, and otherwise
  29048. * act as real geometry. The displacement texture is an image where the value
  29049. * of each pixel (white being the highest) is mapped against, and
  29050. * repositions, the vertices of the mesh.
  29051. *
  29052. * @type {?Texture}
  29053. * @default null
  29054. */
  29055. this.displacementMap = null;
  29056. /**
  29057. * How much the displacement map affects the mesh (where black is no
  29058. * displacement, and white is maximum displacement). Without a displacement
  29059. * map set, this value is not applied.
  29060. *
  29061. * @type {number}
  29062. * @default 0
  29063. */
  29064. this.displacementScale = 1;
  29065. /**
  29066. * The offset of the displacement map's values on the mesh's vertices.
  29067. * The bias is added to the scaled sample of the displacement map.
  29068. * Without a displacement map set, this value is not applied.
  29069. *
  29070. * @type {number}
  29071. * @default 0
  29072. */
  29073. this.displacementBias = 0;
  29074. /**
  29075. * Renders the geometry as a wireframe.
  29076. *
  29077. * @type {boolean}
  29078. * @default false
  29079. */
  29080. this.wireframe = false;
  29081. /**
  29082. * Controls the thickness of the wireframe.
  29083. *
  29084. * WebGL and WebGPU ignore this property and always render
  29085. * 1 pixel wide lines.
  29086. *
  29087. * @type {number}
  29088. * @default 1
  29089. */
  29090. this.wireframeLinewidth = 1;
  29091. /**
  29092. * Whether the material is rendered with flat shading or not.
  29093. *
  29094. * @type {boolean}
  29095. * @default false
  29096. */
  29097. this.flatShading = false;
  29098. this.setValues( parameters );
  29099. }
  29100. copy( source ) {
  29101. super.copy( source );
  29102. this.bumpMap = source.bumpMap;
  29103. this.bumpScale = source.bumpScale;
  29104. this.normalMap = source.normalMap;
  29105. this.normalMapType = source.normalMapType;
  29106. this.normalScale.copy( source.normalScale );
  29107. this.displacementMap = source.displacementMap;
  29108. this.displacementScale = source.displacementScale;
  29109. this.displacementBias = source.displacementBias;
  29110. this.wireframe = source.wireframe;
  29111. this.wireframeLinewidth = source.wireframeLinewidth;
  29112. this.flatShading = source.flatShading;
  29113. return this;
  29114. }
  29115. }
  29116. /**
  29117. * A material for non-shiny surfaces, without specular highlights.
  29118. *
  29119. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29120. * model for calculating reflectance. This can simulate some surfaces (such
  29121. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29122. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29123. * shading.
  29124. *
  29125. * Due to the simplicity of the reflectance and illumination models,
  29126. * performance will be greater when using this material over the
  29127. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29128. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29129. *
  29130. * @augments Material
  29131. */
  29132. class MeshLambertMaterial extends Material {
  29133. /**
  29134. * Constructs a new mesh lambert material.
  29135. *
  29136. * @param {Object} [parameters] - An object with one or more properties
  29137. * defining the material's appearance. Any property of the material
  29138. * (including any property from inherited materials) can be passed
  29139. * in here. Color values can be passed any type of value accepted
  29140. * by {@link Color#set}.
  29141. */
  29142. constructor( parameters ) {
  29143. super();
  29144. /**
  29145. * This flag can be used for type testing.
  29146. *
  29147. * @type {boolean}
  29148. * @readonly
  29149. * @default true
  29150. */
  29151. this.isMeshLambertMaterial = true;
  29152. this.type = 'MeshLambertMaterial';
  29153. /**
  29154. * Color of the material.
  29155. *
  29156. * @type {Color}
  29157. * @default (1,1,1)
  29158. */
  29159. this.color = new Color( 0xffffff ); // diffuse
  29160. /**
  29161. * The color map. May optionally include an alpha channel, typically combined
  29162. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29163. * color is modulated by the diffuse `color`.
  29164. *
  29165. * @type {?Texture}
  29166. * @default null
  29167. */
  29168. this.map = null;
  29169. /**
  29170. * The light map. Requires a second set of UVs.
  29171. *
  29172. * @type {?Texture}
  29173. * @default null
  29174. */
  29175. this.lightMap = null;
  29176. /**
  29177. * Intensity of the baked light.
  29178. *
  29179. * @type {number}
  29180. * @default 1
  29181. */
  29182. this.lightMapIntensity = 1.0;
  29183. /**
  29184. * The red channel of this texture is used as the ambient occlusion map.
  29185. * Requires a second set of UVs.
  29186. *
  29187. * @type {?Texture}
  29188. * @default null
  29189. */
  29190. this.aoMap = null;
  29191. /**
  29192. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29193. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29194. * red channel is also `1`, ambient light is fully occluded on a surface.
  29195. *
  29196. * @type {number}
  29197. * @default 1
  29198. */
  29199. this.aoMapIntensity = 1.0;
  29200. /**
  29201. * Emissive (light) color of the material, essentially a solid color
  29202. * unaffected by other lighting.
  29203. *
  29204. * @type {Color}
  29205. * @default (0,0,0)
  29206. */
  29207. this.emissive = new Color( 0x000000 );
  29208. /**
  29209. * Intensity of the emissive light. Modulates the emissive color.
  29210. *
  29211. * @type {number}
  29212. * @default 1
  29213. */
  29214. this.emissiveIntensity = 1.0;
  29215. /**
  29216. * Set emissive (glow) map. The emissive map color is modulated by the
  29217. * emissive color and the emissive intensity. If you have an emissive map,
  29218. * be sure to set the emissive color to something other than black.
  29219. *
  29220. * @type {?Texture}
  29221. * @default null
  29222. */
  29223. this.emissiveMap = null;
  29224. /**
  29225. * The texture to create a bump map. The black and white values map to the
  29226. * perceived depth in relation to the lights. Bump doesn't actually affect
  29227. * the geometry of the object, only the lighting. If a normal map is defined
  29228. * this will be ignored.
  29229. *
  29230. * @type {?Texture}
  29231. * @default null
  29232. */
  29233. this.bumpMap = null;
  29234. /**
  29235. * How much the bump map affects the material. Typical range is `[0,1]`.
  29236. *
  29237. * @type {number}
  29238. * @default 1
  29239. */
  29240. this.bumpScale = 1;
  29241. /**
  29242. * The texture to create a normal map. The RGB values affect the surface
  29243. * normal for each pixel fragment and change the way the color is lit. Normal
  29244. * maps do not change the actual shape of the surface, only the lighting. In
  29245. * case the material has a normal map authored using the left handed
  29246. * convention, the `y` component of `normalScale` should be negated to compensate
  29247. * for the different handedness.
  29248. *
  29249. * @type {?Texture}
  29250. * @default null
  29251. */
  29252. this.normalMap = null;
  29253. /**
  29254. * The type of normal map.
  29255. *
  29256. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29257. * @default TangentSpaceNormalMap
  29258. */
  29259. this.normalMapType = TangentSpaceNormalMap;
  29260. /**
  29261. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29262. *
  29263. * @type {Vector2}
  29264. * @default (1,1)
  29265. */
  29266. this.normalScale = new Vector2( 1, 1 );
  29267. /**
  29268. * The displacement map affects the position of the mesh's vertices. Unlike
  29269. * other maps which only affect the light and shade of the material the
  29270. * displaced vertices can cast shadows, block other objects, and otherwise
  29271. * act as real geometry. The displacement texture is an image where the value
  29272. * of each pixel (white being the highest) is mapped against, and
  29273. * repositions, the vertices of the mesh.
  29274. *
  29275. * @type {?Texture}
  29276. * @default null
  29277. */
  29278. this.displacementMap = null;
  29279. /**
  29280. * How much the displacement map affects the mesh (where black is no
  29281. * displacement, and white is maximum displacement). Without a displacement
  29282. * map set, this value is not applied.
  29283. *
  29284. * @type {number}
  29285. * @default 0
  29286. */
  29287. this.displacementScale = 1;
  29288. /**
  29289. * The offset of the displacement map's values on the mesh's vertices.
  29290. * The bias is added to the scaled sample of the displacement map.
  29291. * Without a displacement map set, this value is not applied.
  29292. *
  29293. * @type {number}
  29294. * @default 0
  29295. */
  29296. this.displacementBias = 0;
  29297. /**
  29298. * Specular map used by the material.
  29299. *
  29300. * @type {?Texture}
  29301. * @default null
  29302. */
  29303. this.specularMap = null;
  29304. /**
  29305. * The alpha map is a grayscale texture that controls the opacity across the
  29306. * surface (black: fully transparent; white: fully opaque).
  29307. *
  29308. * Only the color of the texture is used, ignoring the alpha channel if one
  29309. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29310. * when sampling this texture due to the extra bit of precision provided for
  29311. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29312. * luminance/alpha textures will also still work as expected.
  29313. *
  29314. * @type {?Texture}
  29315. * @default null
  29316. */
  29317. this.alphaMap = null;
  29318. /**
  29319. * The environment map.
  29320. *
  29321. * @type {?Texture}
  29322. * @default null
  29323. */
  29324. this.envMap = null;
  29325. /**
  29326. * The rotation of the environment map in radians.
  29327. *
  29328. * @type {Euler}
  29329. * @default (0,0,0)
  29330. */
  29331. this.envMapRotation = new Euler();
  29332. /**
  29333. * How to combine the result of the surface's color with the environment map, if any.
  29334. *
  29335. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29336. * blend between the two colors.
  29337. *
  29338. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29339. * @default MultiplyOperation
  29340. */
  29341. this.combine = MultiplyOperation;
  29342. /**
  29343. * How much the environment map affects the surface.
  29344. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29345. *
  29346. * @type {number}
  29347. * @default 1
  29348. */
  29349. this.reflectivity = 1;
  29350. /**
  29351. * The index of refraction (IOR) of air (approximately 1) divided by the
  29352. * index of refraction of the material. It is used with environment mapping
  29353. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29354. * The refraction ratio should not exceed `1`.
  29355. *
  29356. * @type {number}
  29357. * @default 0.98
  29358. */
  29359. this.refractionRatio = 0.98;
  29360. /**
  29361. * Renders the geometry as a wireframe.
  29362. *
  29363. * @type {boolean}
  29364. * @default false
  29365. */
  29366. this.wireframe = false;
  29367. /**
  29368. * Controls the thickness of the wireframe.
  29369. *
  29370. * Can only be used with {@link SVGRenderer}.
  29371. *
  29372. * @type {number}
  29373. * @default 1
  29374. */
  29375. this.wireframeLinewidth = 1;
  29376. /**
  29377. * Defines appearance of wireframe ends.
  29378. *
  29379. * Can only be used with {@link SVGRenderer}.
  29380. *
  29381. * @type {('round'|'bevel'|'miter')}
  29382. * @default 'round'
  29383. */
  29384. this.wireframeLinecap = 'round';
  29385. /**
  29386. * Defines appearance of wireframe joints.
  29387. *
  29388. * Can only be used with {@link SVGRenderer}.
  29389. *
  29390. * @type {('round'|'bevel'|'miter')}
  29391. * @default 'round'
  29392. */
  29393. this.wireframeLinejoin = 'round';
  29394. /**
  29395. * Whether the material is rendered with flat shading or not.
  29396. *
  29397. * @type {boolean}
  29398. * @default false
  29399. */
  29400. this.flatShading = false;
  29401. /**
  29402. * Whether the material is affected by fog or not.
  29403. *
  29404. * @type {boolean}
  29405. * @default true
  29406. */
  29407. this.fog = true;
  29408. this.setValues( parameters );
  29409. }
  29410. copy( source ) {
  29411. super.copy( source );
  29412. this.color.copy( source.color );
  29413. this.map = source.map;
  29414. this.lightMap = source.lightMap;
  29415. this.lightMapIntensity = source.lightMapIntensity;
  29416. this.aoMap = source.aoMap;
  29417. this.aoMapIntensity = source.aoMapIntensity;
  29418. this.emissive.copy( source.emissive );
  29419. this.emissiveMap = source.emissiveMap;
  29420. this.emissiveIntensity = source.emissiveIntensity;
  29421. this.bumpMap = source.bumpMap;
  29422. this.bumpScale = source.bumpScale;
  29423. this.normalMap = source.normalMap;
  29424. this.normalMapType = source.normalMapType;
  29425. this.normalScale.copy( source.normalScale );
  29426. this.displacementMap = source.displacementMap;
  29427. this.displacementScale = source.displacementScale;
  29428. this.displacementBias = source.displacementBias;
  29429. this.specularMap = source.specularMap;
  29430. this.alphaMap = source.alphaMap;
  29431. this.envMap = source.envMap;
  29432. this.envMapRotation.copy( source.envMapRotation );
  29433. this.combine = source.combine;
  29434. this.reflectivity = source.reflectivity;
  29435. this.refractionRatio = source.refractionRatio;
  29436. this.wireframe = source.wireframe;
  29437. this.wireframeLinewidth = source.wireframeLinewidth;
  29438. this.wireframeLinecap = source.wireframeLinecap;
  29439. this.wireframeLinejoin = source.wireframeLinejoin;
  29440. this.flatShading = source.flatShading;
  29441. this.fog = source.fog;
  29442. return this;
  29443. }
  29444. }
  29445. /**
  29446. * A material for drawing geometry by depth. Depth is based off of the camera
  29447. * near and far plane. White is nearest, black is farthest.
  29448. *
  29449. * @augments Material
  29450. */
  29451. class MeshDepthMaterial extends Material {
  29452. /**
  29453. * Constructs a new mesh depth material.
  29454. *
  29455. * @param {Object} [parameters] - An object with one or more properties
  29456. * defining the material's appearance. Any property of the material
  29457. * (including any property from inherited materials) can be passed
  29458. * in here. Color values can be passed any type of value accepted
  29459. * by {@link Color#set}.
  29460. */
  29461. constructor( parameters ) {
  29462. super();
  29463. /**
  29464. * This flag can be used for type testing.
  29465. *
  29466. * @type {boolean}
  29467. * @readonly
  29468. * @default true
  29469. */
  29470. this.isMeshDepthMaterial = true;
  29471. this.type = 'MeshDepthMaterial';
  29472. /**
  29473. * Type for depth packing.
  29474. *
  29475. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29476. * @default BasicDepthPacking
  29477. */
  29478. this.depthPacking = BasicDepthPacking;
  29479. /**
  29480. * The color map. May optionally include an alpha channel, typically combined
  29481. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29482. *
  29483. * @type {?Texture}
  29484. * @default null
  29485. */
  29486. this.map = null;
  29487. /**
  29488. * The alpha map is a grayscale texture that controls the opacity across the
  29489. * surface (black: fully transparent; white: fully opaque).
  29490. *
  29491. * Only the color of the texture is used, ignoring the alpha channel if one
  29492. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29493. * when sampling this texture due to the extra bit of precision provided for
  29494. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29495. * luminance/alpha textures will also still work as expected.
  29496. *
  29497. * @type {?Texture}
  29498. * @default null
  29499. */
  29500. this.alphaMap = null;
  29501. /**
  29502. * The displacement map affects the position of the mesh's vertices. Unlike
  29503. * other maps which only affect the light and shade of the material the
  29504. * displaced vertices can cast shadows, block other objects, and otherwise
  29505. * act as real geometry. The displacement texture is an image where the value
  29506. * of each pixel (white being the highest) is mapped against, and
  29507. * repositions, the vertices of the mesh.
  29508. *
  29509. * @type {?Texture}
  29510. * @default null
  29511. */
  29512. this.displacementMap = null;
  29513. /**
  29514. * How much the displacement map affects the mesh (where black is no
  29515. * displacement, and white is maximum displacement). Without a displacement
  29516. * map set, this value is not applied.
  29517. *
  29518. * @type {number}
  29519. * @default 0
  29520. */
  29521. this.displacementScale = 1;
  29522. /**
  29523. * The offset of the displacement map's values on the mesh's vertices.
  29524. * The bias is added to the scaled sample of the displacement map.
  29525. * Without a displacement map set, this value is not applied.
  29526. *
  29527. * @type {number}
  29528. * @default 0
  29529. */
  29530. this.displacementBias = 0;
  29531. /**
  29532. * Renders the geometry as a wireframe.
  29533. *
  29534. * @type {boolean}
  29535. * @default false
  29536. */
  29537. this.wireframe = false;
  29538. /**
  29539. * Controls the thickness of the wireframe.
  29540. *
  29541. * WebGL and WebGPU ignore this property and always render
  29542. * 1 pixel wide lines.
  29543. *
  29544. * @type {number}
  29545. * @default 1
  29546. */
  29547. this.wireframeLinewidth = 1;
  29548. this.setValues( parameters );
  29549. }
  29550. copy( source ) {
  29551. super.copy( source );
  29552. this.depthPacking = source.depthPacking;
  29553. this.map = source.map;
  29554. this.alphaMap = source.alphaMap;
  29555. this.displacementMap = source.displacementMap;
  29556. this.displacementScale = source.displacementScale;
  29557. this.displacementBias = source.displacementBias;
  29558. this.wireframe = source.wireframe;
  29559. this.wireframeLinewidth = source.wireframeLinewidth;
  29560. return this;
  29561. }
  29562. }
  29563. /**
  29564. * A material used internally for implementing shadow mapping with
  29565. * point lights.
  29566. *
  29567. * Can also be used to customize the shadow casting of an object by assigning
  29568. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29569. * The following examples demonstrates this approach in order to ensure
  29570. * transparent parts of objects do no cast shadows.
  29571. *
  29572. * @augments Material
  29573. */
  29574. class MeshDistanceMaterial extends Material {
  29575. /**
  29576. * Constructs a new mesh distance material.
  29577. *
  29578. * @param {Object} [parameters] - An object with one or more properties
  29579. * defining the material's appearance. Any property of the material
  29580. * (including any property from inherited materials) can be passed
  29581. * in here. Color values can be passed any type of value accepted
  29582. * by {@link Color#set}.
  29583. */
  29584. constructor( parameters ) {
  29585. super();
  29586. /**
  29587. * This flag can be used for type testing.
  29588. *
  29589. * @type {boolean}
  29590. * @readonly
  29591. * @default true
  29592. */
  29593. this.isMeshDistanceMaterial = true;
  29594. this.type = 'MeshDistanceMaterial';
  29595. /**
  29596. * The color map. May optionally include an alpha channel, typically combined
  29597. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29598. *
  29599. * @type {?Texture}
  29600. * @default null
  29601. */
  29602. this.map = null;
  29603. /**
  29604. * The alpha map is a grayscale texture that controls the opacity across the
  29605. * surface (black: fully transparent; white: fully opaque).
  29606. *
  29607. * Only the color of the texture is used, ignoring the alpha channel if one
  29608. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29609. * when sampling this texture due to the extra bit of precision provided for
  29610. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29611. * luminance/alpha textures will also still work as expected.
  29612. *
  29613. * @type {?Texture}
  29614. * @default null
  29615. */
  29616. this.alphaMap = null;
  29617. /**
  29618. * The displacement map affects the position of the mesh's vertices. Unlike
  29619. * other maps which only affect the light and shade of the material the
  29620. * displaced vertices can cast shadows, block other objects, and otherwise
  29621. * act as real geometry. The displacement texture is an image where the value
  29622. * of each pixel (white being the highest) is mapped against, and
  29623. * repositions, the vertices of the mesh.
  29624. *
  29625. * @type {?Texture}
  29626. * @default null
  29627. */
  29628. this.displacementMap = null;
  29629. /**
  29630. * How much the displacement map affects the mesh (where black is no
  29631. * displacement, and white is maximum displacement). Without a displacement
  29632. * map set, this value is not applied.
  29633. *
  29634. * @type {number}
  29635. * @default 0
  29636. */
  29637. this.displacementScale = 1;
  29638. /**
  29639. * The offset of the displacement map's values on the mesh's vertices.
  29640. * The bias is added to the scaled sample of the displacement map.
  29641. * Without a displacement map set, this value is not applied.
  29642. *
  29643. * @type {number}
  29644. * @default 0
  29645. */
  29646. this.displacementBias = 0;
  29647. this.setValues( parameters );
  29648. }
  29649. copy( source ) {
  29650. super.copy( source );
  29651. this.map = source.map;
  29652. this.alphaMap = source.alphaMap;
  29653. this.displacementMap = source.displacementMap;
  29654. this.displacementScale = source.displacementScale;
  29655. this.displacementBias = source.displacementBias;
  29656. return this;
  29657. }
  29658. }
  29659. /**
  29660. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29661. * material color and shading.
  29662. *
  29663. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29664. * baked lighting. It will cast a shadow onto an object that receives shadows
  29665. * (and shadow clipping works), but it will not self-shadow or receive
  29666. * shadows.
  29667. *
  29668. * @augments Material
  29669. */
  29670. class MeshMatcapMaterial extends Material {
  29671. /**
  29672. * Constructs a new mesh matcap material.
  29673. *
  29674. * @param {Object} [parameters] - An object with one or more properties
  29675. * defining the material's appearance. Any property of the material
  29676. * (including any property from inherited materials) can be passed
  29677. * in here. Color values can be passed any type of value accepted
  29678. * by {@link Color#set}.
  29679. */
  29680. constructor( parameters ) {
  29681. super();
  29682. /**
  29683. * This flag can be used for type testing.
  29684. *
  29685. * @type {boolean}
  29686. * @readonly
  29687. * @default true
  29688. */
  29689. this.isMeshMatcapMaterial = true;
  29690. this.defines = { 'MATCAP': '' };
  29691. this.type = 'MeshMatcapMaterial';
  29692. /**
  29693. * Color of the material.
  29694. *
  29695. * @type {Color}
  29696. * @default (1,1,1)
  29697. */
  29698. this.color = new Color( 0xffffff ); // diffuse
  29699. /**
  29700. * The matcap map.
  29701. *
  29702. * @type {?Texture}
  29703. * @default null
  29704. */
  29705. this.matcap = null;
  29706. /**
  29707. * The color map. May optionally include an alpha channel, typically combined
  29708. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29709. * color is modulated by the diffuse `color`.
  29710. *
  29711. * @type {?Texture}
  29712. * @default null
  29713. */
  29714. this.map = null;
  29715. /**
  29716. * The texture to create a bump map. The black and white values map to the
  29717. * perceived depth in relation to the lights. Bump doesn't actually affect
  29718. * the geometry of the object, only the lighting. If a normal map is defined
  29719. * this will be ignored.
  29720. *
  29721. * @type {?Texture}
  29722. * @default null
  29723. */
  29724. this.bumpMap = null;
  29725. /**
  29726. * How much the bump map affects the material. Typical range is `[0,1]`.
  29727. *
  29728. * @type {number}
  29729. * @default 1
  29730. */
  29731. this.bumpScale = 1;
  29732. /**
  29733. * The texture to create a normal map. The RGB values affect the surface
  29734. * normal for each pixel fragment and change the way the color is lit. Normal
  29735. * maps do not change the actual shape of the surface, only the lighting. In
  29736. * case the material has a normal map authored using the left handed
  29737. * convention, the `y` component of `normalScale` should be negated to compensate
  29738. * for the different handedness.
  29739. *
  29740. * @type {?Texture}
  29741. * @default null
  29742. */
  29743. this.normalMap = null;
  29744. /**
  29745. * The type of normal map.
  29746. *
  29747. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29748. * @default TangentSpaceNormalMap
  29749. */
  29750. this.normalMapType = TangentSpaceNormalMap;
  29751. /**
  29752. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29753. *
  29754. * @type {Vector2}
  29755. * @default (1,1)
  29756. */
  29757. this.normalScale = new Vector2( 1, 1 );
  29758. /**
  29759. * The displacement map affects the position of the mesh's vertices. Unlike
  29760. * other maps which only affect the light and shade of the material the
  29761. * displaced vertices can cast shadows, block other objects, and otherwise
  29762. * act as real geometry. The displacement texture is an image where the value
  29763. * of each pixel (white being the highest) is mapped against, and
  29764. * repositions, the vertices of the mesh.
  29765. *
  29766. * @type {?Texture}
  29767. * @default null
  29768. */
  29769. this.displacementMap = null;
  29770. /**
  29771. * How much the displacement map affects the mesh (where black is no
  29772. * displacement, and white is maximum displacement). Without a displacement
  29773. * map set, this value is not applied.
  29774. *
  29775. * @type {number}
  29776. * @default 0
  29777. */
  29778. this.displacementScale = 1;
  29779. /**
  29780. * The offset of the displacement map's values on the mesh's vertices.
  29781. * The bias is added to the scaled sample of the displacement map.
  29782. * Without a displacement map set, this value is not applied.
  29783. *
  29784. * @type {number}
  29785. * @default 0
  29786. */
  29787. this.displacementBias = 0;
  29788. /**
  29789. * The alpha map is a grayscale texture that controls the opacity across the
  29790. * surface (black: fully transparent; white: fully opaque).
  29791. *
  29792. * Only the color of the texture is used, ignoring the alpha channel if one
  29793. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29794. * when sampling this texture due to the extra bit of precision provided for
  29795. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29796. * luminance/alpha textures will also still work as expected.
  29797. *
  29798. * @type {?Texture}
  29799. * @default null
  29800. */
  29801. this.alphaMap = null;
  29802. /**
  29803. * Whether the material is rendered with flat shading or not.
  29804. *
  29805. * @type {boolean}
  29806. * @default false
  29807. */
  29808. this.flatShading = false;
  29809. /**
  29810. * Whether the material is affected by fog or not.
  29811. *
  29812. * @type {boolean}
  29813. * @default true
  29814. */
  29815. this.fog = true;
  29816. this.setValues( parameters );
  29817. }
  29818. copy( source ) {
  29819. super.copy( source );
  29820. this.defines = { 'MATCAP': '' };
  29821. this.color.copy( source.color );
  29822. this.matcap = source.matcap;
  29823. this.map = source.map;
  29824. this.bumpMap = source.bumpMap;
  29825. this.bumpScale = source.bumpScale;
  29826. this.normalMap = source.normalMap;
  29827. this.normalMapType = source.normalMapType;
  29828. this.normalScale.copy( source.normalScale );
  29829. this.displacementMap = source.displacementMap;
  29830. this.displacementScale = source.displacementScale;
  29831. this.displacementBias = source.displacementBias;
  29832. this.alphaMap = source.alphaMap;
  29833. this.flatShading = source.flatShading;
  29834. this.fog = source.fog;
  29835. return this;
  29836. }
  29837. }
  29838. /**
  29839. * A material for rendering line primitives.
  29840. *
  29841. * Materials define the appearance of renderable 3D objects.
  29842. *
  29843. * ```js
  29844. * const material = new THREE.LineDashedMaterial( {
  29845. * color: 0xffffff,
  29846. * scale: 1,
  29847. * dashSize: 3,
  29848. * gapSize: 1,
  29849. * } );
  29850. * ```
  29851. *
  29852. * @augments LineBasicMaterial
  29853. */
  29854. class LineDashedMaterial extends LineBasicMaterial {
  29855. /**
  29856. * Constructs a new line dashed material.
  29857. *
  29858. * @param {Object} [parameters] - An object with one or more properties
  29859. * defining the material's appearance. Any property of the material
  29860. * (including any property from inherited materials) can be passed
  29861. * in here. Color values can be passed any type of value accepted
  29862. * by {@link Color#set}.
  29863. */
  29864. constructor( parameters ) {
  29865. super();
  29866. /**
  29867. * This flag can be used for type testing.
  29868. *
  29869. * @type {boolean}
  29870. * @readonly
  29871. * @default true
  29872. */
  29873. this.isLineDashedMaterial = true;
  29874. this.type = 'LineDashedMaterial';
  29875. /**
  29876. * The scale of the dashed part of a line.
  29877. *
  29878. * @type {number}
  29879. * @default 1
  29880. */
  29881. this.scale = 1;
  29882. /**
  29883. * The size of the dash. This is both the gap with the stroke.
  29884. *
  29885. * @type {number}
  29886. * @default 3
  29887. */
  29888. this.dashSize = 3;
  29889. /**
  29890. * The size of the gap.
  29891. *
  29892. * @type {number}
  29893. * @default 1
  29894. */
  29895. this.gapSize = 1;
  29896. this.setValues( parameters );
  29897. }
  29898. copy( source ) {
  29899. super.copy( source );
  29900. this.scale = source.scale;
  29901. this.dashSize = source.dashSize;
  29902. this.gapSize = source.gapSize;
  29903. return this;
  29904. }
  29905. }
  29906. /**
  29907. * Converts an array to a specific type.
  29908. *
  29909. * @param {TypedArray|Array} array - The array to convert.
  29910. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  29911. * @return {TypedArray} The converted array.
  29912. */
  29913. function convertArray( array, type ) {
  29914. if ( ! array || array.constructor === type ) return array;
  29915. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  29916. return new type( array ); // create typed array
  29917. }
  29918. return Array.prototype.slice.call( array ); // create Array
  29919. }
  29920. /**
  29921. * Returns `true` if the given object is a typed array.
  29922. *
  29923. * @param {any} object - The object to check.
  29924. * @return {boolean} Whether the given object is a typed array.
  29925. */
  29926. function isTypedArray( object ) {
  29927. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  29928. }
  29929. /**
  29930. * Returns an array by which times and values can be sorted.
  29931. *
  29932. * @param {Array<number>} times - The keyframe time values.
  29933. * @return {Array<number>} The array.
  29934. */
  29935. function getKeyframeOrder( times ) {
  29936. function compareTime( i, j ) {
  29937. return times[ i ] - times[ j ];
  29938. }
  29939. const n = times.length;
  29940. const result = new Array( n );
  29941. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  29942. result.sort( compareTime );
  29943. return result;
  29944. }
  29945. /**
  29946. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  29947. *
  29948. * @param {Array<number>} values - The values to sort.
  29949. * @param {number} stride - The stride.
  29950. * @param {Array<number>} order - The sort order.
  29951. * @return {Array<number>} The sorted values.
  29952. */
  29953. function sortedArray( values, stride, order ) {
  29954. const nValues = values.length;
  29955. const result = new values.constructor( nValues );
  29956. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  29957. const srcOffset = order[ i ] * stride;
  29958. for ( let j = 0; j !== stride; ++ j ) {
  29959. result[ dstOffset ++ ] = values[ srcOffset + j ];
  29960. }
  29961. }
  29962. return result;
  29963. }
  29964. /**
  29965. * Used for parsing AOS keyframe formats.
  29966. *
  29967. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  29968. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  29969. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  29970. * @param {string} valuePropertyName - The name of the property to use.
  29971. */
  29972. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  29973. let i = 1, key = jsonKeys[ 0 ];
  29974. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  29975. key = jsonKeys[ i ++ ];
  29976. }
  29977. if ( key === undefined ) return; // no data
  29978. let value = key[ valuePropertyName ];
  29979. if ( value === undefined ) return; // no data
  29980. if ( Array.isArray( value ) ) {
  29981. do {
  29982. value = key[ valuePropertyName ];
  29983. if ( value !== undefined ) {
  29984. times.push( key.time );
  29985. values.push( ...value ); // push all elements
  29986. }
  29987. key = jsonKeys[ i ++ ];
  29988. } while ( key !== undefined );
  29989. } else if ( value.toArray !== undefined ) {
  29990. // ...assume THREE.Math-ish
  29991. do {
  29992. value = key[ valuePropertyName ];
  29993. if ( value !== undefined ) {
  29994. times.push( key.time );
  29995. value.toArray( values, values.length );
  29996. }
  29997. key = jsonKeys[ i ++ ];
  29998. } while ( key !== undefined );
  29999. } else {
  30000. // otherwise push as-is
  30001. do {
  30002. value = key[ valuePropertyName ];
  30003. if ( value !== undefined ) {
  30004. times.push( key.time );
  30005. values.push( value );
  30006. }
  30007. key = jsonKeys[ i ++ ];
  30008. } while ( key !== undefined );
  30009. }
  30010. }
  30011. /**
  30012. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30013. *
  30014. * @param {AnimationClip} sourceClip - The values to sort.
  30015. * @param {string} name - The name of the clip.
  30016. * @param {number} startFrame - The start frame.
  30017. * @param {number} endFrame - The end frame.
  30018. * @param {number} [fps=30] - The FPS.
  30019. * @return {AnimationClip} The new sub clip.
  30020. */
  30021. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30022. const clip = sourceClip.clone();
  30023. clip.name = name;
  30024. const tracks = [];
  30025. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30026. const track = clip.tracks[ i ];
  30027. const valueSize = track.getValueSize();
  30028. const times = [];
  30029. const values = [];
  30030. for ( let j = 0; j < track.times.length; ++ j ) {
  30031. const frame = track.times[ j ] * fps;
  30032. if ( frame < startFrame || frame >= endFrame ) continue;
  30033. times.push( track.times[ j ] );
  30034. for ( let k = 0; k < valueSize; ++ k ) {
  30035. values.push( track.values[ j * valueSize + k ] );
  30036. }
  30037. }
  30038. if ( times.length === 0 ) continue;
  30039. track.times = convertArray( times, track.times.constructor );
  30040. track.values = convertArray( values, track.values.constructor );
  30041. tracks.push( track );
  30042. }
  30043. clip.tracks = tracks;
  30044. // find minimum .times value across all tracks in the trimmed clip
  30045. let minStartTime = Infinity;
  30046. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30047. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30048. minStartTime = clip.tracks[ i ].times[ 0 ];
  30049. }
  30050. }
  30051. // shift all tracks such that clip begins at t=0
  30052. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30053. clip.tracks[ i ].shift( -1 * minStartTime );
  30054. }
  30055. clip.resetDuration();
  30056. return clip;
  30057. }
  30058. /**
  30059. * Converts the keyframes of the given animation clip to an additive format.
  30060. *
  30061. * @param {AnimationClip} targetClip - The clip to make additive.
  30062. * @param {number} [referenceFrame=0] - The reference frame.
  30063. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30064. * @param {number} [fps=30] - The FPS.
  30065. * @return {AnimationClip} The updated clip which is now additive.
  30066. */
  30067. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30068. if ( fps <= 0 ) fps = 30;
  30069. const numTracks = referenceClip.tracks.length;
  30070. const referenceTime = referenceFrame / fps;
  30071. // Make each track's values relative to the values at the reference frame
  30072. for ( let i = 0; i < numTracks; ++ i ) {
  30073. const referenceTrack = referenceClip.tracks[ i ];
  30074. const referenceTrackType = referenceTrack.ValueTypeName;
  30075. // Skip this track if it's non-numeric
  30076. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30077. // Find the track in the target clip whose name and type matches the reference track
  30078. const targetTrack = targetClip.tracks.find( function ( track ) {
  30079. return track.name === referenceTrack.name
  30080. && track.ValueTypeName === referenceTrackType;
  30081. } );
  30082. if ( targetTrack === undefined ) continue;
  30083. let referenceOffset = 0;
  30084. const referenceValueSize = referenceTrack.getValueSize();
  30085. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30086. referenceOffset = referenceValueSize / 3;
  30087. }
  30088. let targetOffset = 0;
  30089. const targetValueSize = targetTrack.getValueSize();
  30090. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30091. targetOffset = targetValueSize / 3;
  30092. }
  30093. const lastIndex = referenceTrack.times.length - 1;
  30094. let referenceValue;
  30095. // Find the value to subtract out of the track
  30096. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30097. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30098. const startIndex = referenceOffset;
  30099. const endIndex = referenceValueSize - referenceOffset;
  30100. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30101. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30102. // Reference frame is after the last keyframe, so just use the last keyframe
  30103. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30104. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30105. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30106. } else {
  30107. // Interpolate to the reference value
  30108. const interpolant = referenceTrack.createInterpolant();
  30109. const startIndex = referenceOffset;
  30110. const endIndex = referenceValueSize - referenceOffset;
  30111. interpolant.evaluate( referenceTime );
  30112. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30113. }
  30114. // Conjugate the quaternion
  30115. if ( referenceTrackType === 'quaternion' ) {
  30116. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30117. referenceQuat.toArray( referenceValue );
  30118. }
  30119. // Subtract the reference value from all of the track values
  30120. const numTimes = targetTrack.times.length;
  30121. for ( let j = 0; j < numTimes; ++ j ) {
  30122. const valueStart = j * targetValueSize + targetOffset;
  30123. if ( referenceTrackType === 'quaternion' ) {
  30124. // Multiply the conjugate for quaternion track types
  30125. Quaternion.multiplyQuaternionsFlat(
  30126. targetTrack.values,
  30127. valueStart,
  30128. referenceValue,
  30129. 0,
  30130. targetTrack.values,
  30131. valueStart
  30132. );
  30133. } else {
  30134. const valueEnd = targetValueSize - targetOffset * 2;
  30135. // Subtract each value for all other numeric track types
  30136. for ( let k = 0; k < valueEnd; ++ k ) {
  30137. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30138. }
  30139. }
  30140. }
  30141. }
  30142. targetClip.blendMode = AdditiveAnimationBlendMode;
  30143. return targetClip;
  30144. }
  30145. /**
  30146. * A class with various methods to assist with animations.
  30147. *
  30148. * @hideconstructor
  30149. */
  30150. class AnimationUtils {
  30151. /**
  30152. * Converts an array to a specific type
  30153. *
  30154. * @static
  30155. * @param {TypedArray|Array} array - The array to convert.
  30156. * @param {TypedArray.constructor} type - The constructor of a type array.
  30157. * @return {TypedArray} The converted array
  30158. */
  30159. static convertArray( array, type ) {
  30160. return convertArray( array, type );
  30161. }
  30162. /**
  30163. * Returns `true` if the given object is a typed array.
  30164. *
  30165. * @static
  30166. * @param {any} object - The object to check.
  30167. * @return {boolean} Whether the given object is a typed array.
  30168. */
  30169. static isTypedArray( object ) {
  30170. return isTypedArray( object );
  30171. }
  30172. /**
  30173. * Returns an array by which times and values can be sorted.
  30174. *
  30175. * @static
  30176. * @param {Array<number>} times - The keyframe time values.
  30177. * @return {Array<number>} The array.
  30178. */
  30179. static getKeyframeOrder( times ) {
  30180. return getKeyframeOrder( times );
  30181. }
  30182. /**
  30183. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30184. *
  30185. * @static
  30186. * @param {Array<number>} values - The values to sort.
  30187. * @param {number} stride - The stride.
  30188. * @param {Array<number>} order - The sort order.
  30189. * @return {Array<number>} The sorted values.
  30190. */
  30191. static sortedArray( values, stride, order ) {
  30192. return sortedArray( values, stride, order );
  30193. }
  30194. /**
  30195. * Used for parsing AOS keyframe formats.
  30196. *
  30197. * @static
  30198. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30199. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30200. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30201. * @param {string} valuePropertyName - The name of the property to use.
  30202. */
  30203. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30204. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30205. }
  30206. /**
  30207. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30208. *
  30209. * @static
  30210. * @param {AnimationClip} sourceClip - The values to sort.
  30211. * @param {string} name - The name of the clip.
  30212. * @param {number} startFrame - The start frame.
  30213. * @param {number} endFrame - The end frame.
  30214. * @param {number} [fps=30] - The FPS.
  30215. * @return {AnimationClip} The new sub clip.
  30216. */
  30217. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30218. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30219. }
  30220. /**
  30221. * Converts the keyframes of the given animation clip to an additive format.
  30222. *
  30223. * @static
  30224. * @param {AnimationClip} targetClip - The clip to make additive.
  30225. * @param {number} [referenceFrame=0] - The reference frame.
  30226. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30227. * @param {number} [fps=30] - The FPS.
  30228. * @return {AnimationClip} The updated clip which is now additive.
  30229. */
  30230. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30231. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30232. }
  30233. }
  30234. /**
  30235. * Abstract base class of interpolants over parametric samples.
  30236. *
  30237. * The parameter domain is one dimensional, typically the time or a path
  30238. * along a curve defined by the data.
  30239. *
  30240. * The sample values can have any dimensionality and derived classes may
  30241. * apply special interpretations to the data.
  30242. *
  30243. * This class provides the interval seek in a Template Method, deferring
  30244. * the actual interpolation to derived classes.
  30245. *
  30246. * Time complexity is O(1) for linear access crossing at most two points
  30247. * and O(log N) for random access, where N is the number of positions.
  30248. *
  30249. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30250. *
  30251. * @abstract
  30252. */
  30253. class Interpolant {
  30254. /**
  30255. * Constructs a new interpolant.
  30256. *
  30257. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30258. * @param {TypedArray} sampleValues - The sample values.
  30259. * @param {number} sampleSize - The sample size
  30260. * @param {TypedArray} [resultBuffer] - The result buffer.
  30261. */
  30262. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30263. /**
  30264. * The parameter positions.
  30265. *
  30266. * @type {TypedArray}
  30267. */
  30268. this.parameterPositions = parameterPositions;
  30269. /**
  30270. * A cache index.
  30271. *
  30272. * @private
  30273. * @type {number}
  30274. * @default 0
  30275. */
  30276. this._cachedIndex = 0;
  30277. /**
  30278. * The result buffer.
  30279. *
  30280. * @type {TypedArray}
  30281. */
  30282. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30283. /**
  30284. * The sample values.
  30285. *
  30286. * @type {TypedArray}
  30287. */
  30288. this.sampleValues = sampleValues;
  30289. /**
  30290. * The value size.
  30291. *
  30292. * @type {TypedArray}
  30293. */
  30294. this.valueSize = sampleSize;
  30295. /**
  30296. * The interpolation settings.
  30297. *
  30298. * @type {?Object}
  30299. * @default null
  30300. */
  30301. this.settings = null;
  30302. /**
  30303. * The default settings object.
  30304. *
  30305. * @type {Object}
  30306. */
  30307. this.DefaultSettings_ = {};
  30308. }
  30309. /**
  30310. * Evaluate the interpolant at position `t`.
  30311. *
  30312. * @param {number} t - The interpolation factor.
  30313. * @return {TypedArray} The result buffer.
  30314. */
  30315. evaluate( t ) {
  30316. const pp = this.parameterPositions;
  30317. let i1 = this._cachedIndex,
  30318. t1 = pp[ i1 ],
  30319. t0 = pp[ i1 - 1 ];
  30320. validate_interval: {
  30321. seek: {
  30322. let right;
  30323. linear_scan: {
  30324. //- See http://jsperf.com/comparison-to-undefined/3
  30325. //- slower code:
  30326. //-
  30327. //- if ( t >= t1 || t1 === undefined ) {
  30328. forward_scan: if ( ! ( t < t1 ) ) {
  30329. for ( let giveUpAt = i1 + 2; ; ) {
  30330. if ( t1 === undefined ) {
  30331. if ( t < t0 ) break forward_scan;
  30332. // after end
  30333. i1 = pp.length;
  30334. this._cachedIndex = i1;
  30335. return this.copySampleValue_( i1 - 1 );
  30336. }
  30337. if ( i1 === giveUpAt ) break; // this loop
  30338. t0 = t1;
  30339. t1 = pp[ ++ i1 ];
  30340. if ( t < t1 ) {
  30341. // we have arrived at the sought interval
  30342. break seek;
  30343. }
  30344. }
  30345. // prepare binary search on the right side of the index
  30346. right = pp.length;
  30347. break linear_scan;
  30348. }
  30349. //- slower code:
  30350. //- if ( t < t0 || t0 === undefined ) {
  30351. if ( ! ( t >= t0 ) ) {
  30352. // looping?
  30353. const t1global = pp[ 1 ];
  30354. if ( t < t1global ) {
  30355. i1 = 2; // + 1, using the scan for the details
  30356. t0 = t1global;
  30357. }
  30358. // linear reverse scan
  30359. for ( let giveUpAt = i1 - 2; ; ) {
  30360. if ( t0 === undefined ) {
  30361. // before start
  30362. this._cachedIndex = 0;
  30363. return this.copySampleValue_( 0 );
  30364. }
  30365. if ( i1 === giveUpAt ) break; // this loop
  30366. t1 = t0;
  30367. t0 = pp[ -- i1 - 1 ];
  30368. if ( t >= t0 ) {
  30369. // we have arrived at the sought interval
  30370. break seek;
  30371. }
  30372. }
  30373. // prepare binary search on the left side of the index
  30374. right = i1;
  30375. i1 = 0;
  30376. break linear_scan;
  30377. }
  30378. // the interval is valid
  30379. break validate_interval;
  30380. } // linear scan
  30381. // binary search
  30382. while ( i1 < right ) {
  30383. const mid = ( i1 + right ) >>> 1;
  30384. if ( t < pp[ mid ] ) {
  30385. right = mid;
  30386. } else {
  30387. i1 = mid + 1;
  30388. }
  30389. }
  30390. t1 = pp[ i1 ];
  30391. t0 = pp[ i1 - 1 ];
  30392. // check boundary cases, again
  30393. if ( t0 === undefined ) {
  30394. this._cachedIndex = 0;
  30395. return this.copySampleValue_( 0 );
  30396. }
  30397. if ( t1 === undefined ) {
  30398. i1 = pp.length;
  30399. this._cachedIndex = i1;
  30400. return this.copySampleValue_( i1 - 1 );
  30401. }
  30402. } // seek
  30403. this._cachedIndex = i1;
  30404. this.intervalChanged_( i1, t0, t1 );
  30405. } // validate_interval
  30406. return this.interpolate_( i1, t0, t, t1 );
  30407. }
  30408. /**
  30409. * Returns the interpolation settings.
  30410. *
  30411. * @return {Object} The interpolation settings.
  30412. */
  30413. getSettings_() {
  30414. return this.settings || this.DefaultSettings_;
  30415. }
  30416. /**
  30417. * Copies a sample value to the result buffer.
  30418. *
  30419. * @param {number} index - An index into the sample value buffer.
  30420. * @return {TypedArray} The result buffer.
  30421. */
  30422. copySampleValue_( index ) {
  30423. // copies a sample value to the result buffer
  30424. const result = this.resultBuffer,
  30425. values = this.sampleValues,
  30426. stride = this.valueSize,
  30427. offset = index * stride;
  30428. for ( let i = 0; i !== stride; ++ i ) {
  30429. result[ i ] = values[ offset + i ];
  30430. }
  30431. return result;
  30432. }
  30433. /**
  30434. * Copies a sample value to the result buffer.
  30435. *
  30436. * @abstract
  30437. * @param {number} i1 - An index into the sample value buffer.
  30438. * @param {number} t0 - The previous interpolation factor.
  30439. * @param {number} t - The current interpolation factor.
  30440. * @param {number} t1 - The next interpolation factor.
  30441. * @return {TypedArray} The result buffer.
  30442. */
  30443. interpolate_( /* i1, t0, t, t1 */ ) {
  30444. throw new Error( 'call to abstract method' );
  30445. // implementations shall return this.resultBuffer
  30446. }
  30447. /**
  30448. * Optional method that is executed when the interval has changed.
  30449. *
  30450. * @param {number} i1 - An index into the sample value buffer.
  30451. * @param {number} t0 - The previous interpolation factor.
  30452. * @param {number} t - The current interpolation factor.
  30453. */
  30454. intervalChanged_( /* i1, t0, t1 */ ) {
  30455. // empty
  30456. }
  30457. }
  30458. /**
  30459. * Fast and simple cubic spline interpolant.
  30460. *
  30461. * It was derived from a Hermitian construction setting the first derivative
  30462. * at each sample position to the linear slope between neighboring positions
  30463. * over their parameter interval.
  30464. *
  30465. * @augments Interpolant
  30466. */
  30467. class CubicInterpolant extends Interpolant {
  30468. /**
  30469. * Constructs a new cubic interpolant.
  30470. *
  30471. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30472. * @param {TypedArray} sampleValues - The sample values.
  30473. * @param {number} sampleSize - The sample size
  30474. * @param {TypedArray} [resultBuffer] - The result buffer.
  30475. */
  30476. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30477. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30478. this._weightPrev = -0;
  30479. this._offsetPrev = -0;
  30480. this._weightNext = -0;
  30481. this._offsetNext = -0;
  30482. this.DefaultSettings_ = {
  30483. endingStart: ZeroCurvatureEnding,
  30484. endingEnd: ZeroCurvatureEnding
  30485. };
  30486. }
  30487. intervalChanged_( i1, t0, t1 ) {
  30488. const pp = this.parameterPositions;
  30489. let iPrev = i1 - 2,
  30490. iNext = i1 + 1,
  30491. tPrev = pp[ iPrev ],
  30492. tNext = pp[ iNext ];
  30493. if ( tPrev === undefined ) {
  30494. switch ( this.getSettings_().endingStart ) {
  30495. case ZeroSlopeEnding:
  30496. // f'(t0) = 0
  30497. iPrev = i1;
  30498. tPrev = 2 * t0 - t1;
  30499. break;
  30500. case WrapAroundEnding:
  30501. // use the other end of the curve
  30502. iPrev = pp.length - 2;
  30503. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30504. break;
  30505. default: // ZeroCurvatureEnding
  30506. // f''(t0) = 0 a.k.a. Natural Spline
  30507. iPrev = i1;
  30508. tPrev = t1;
  30509. }
  30510. }
  30511. if ( tNext === undefined ) {
  30512. switch ( this.getSettings_().endingEnd ) {
  30513. case ZeroSlopeEnding:
  30514. // f'(tN) = 0
  30515. iNext = i1;
  30516. tNext = 2 * t1 - t0;
  30517. break;
  30518. case WrapAroundEnding:
  30519. // use the other end of the curve
  30520. iNext = 1;
  30521. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30522. break;
  30523. default: // ZeroCurvatureEnding
  30524. // f''(tN) = 0, a.k.a. Natural Spline
  30525. iNext = i1 - 1;
  30526. tNext = t0;
  30527. }
  30528. }
  30529. const halfDt = ( t1 - t0 ) * 0.5,
  30530. stride = this.valueSize;
  30531. this._weightPrev = halfDt / ( t0 - tPrev );
  30532. this._weightNext = halfDt / ( tNext - t1 );
  30533. this._offsetPrev = iPrev * stride;
  30534. this._offsetNext = iNext * stride;
  30535. }
  30536. interpolate_( i1, t0, t, t1 ) {
  30537. const result = this.resultBuffer,
  30538. values = this.sampleValues,
  30539. stride = this.valueSize,
  30540. o1 = i1 * stride, o0 = o1 - stride,
  30541. oP = this._offsetPrev, oN = this._offsetNext,
  30542. wP = this._weightPrev, wN = this._weightNext,
  30543. p = ( t - t0 ) / ( t1 - t0 ),
  30544. pp = p * p,
  30545. ppp = pp * p;
  30546. // evaluate polynomials
  30547. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30548. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30549. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30550. const sN = wN * ppp - wN * pp;
  30551. // combine data linearly
  30552. for ( let i = 0; i !== stride; ++ i ) {
  30553. result[ i ] =
  30554. sP * values[ oP + i ] +
  30555. s0 * values[ o0 + i ] +
  30556. s1 * values[ o1 + i ] +
  30557. sN * values[ oN + i ];
  30558. }
  30559. return result;
  30560. }
  30561. }
  30562. /**
  30563. * A basic linear interpolant.
  30564. *
  30565. * @augments Interpolant
  30566. */
  30567. class LinearInterpolant extends Interpolant {
  30568. /**
  30569. * Constructs a new linear interpolant.
  30570. *
  30571. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30572. * @param {TypedArray} sampleValues - The sample values.
  30573. * @param {number} sampleSize - The sample size
  30574. * @param {TypedArray} [resultBuffer] - The result buffer.
  30575. */
  30576. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30577. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30578. }
  30579. interpolate_( i1, t0, t, t1 ) {
  30580. const result = this.resultBuffer,
  30581. values = this.sampleValues,
  30582. stride = this.valueSize,
  30583. offset1 = i1 * stride,
  30584. offset0 = offset1 - stride,
  30585. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30586. weight0 = 1 - weight1;
  30587. for ( let i = 0; i !== stride; ++ i ) {
  30588. result[ i ] =
  30589. values[ offset0 + i ] * weight0 +
  30590. values[ offset1 + i ] * weight1;
  30591. }
  30592. return result;
  30593. }
  30594. }
  30595. /**
  30596. * Interpolant that evaluates to the sample value at the position preceding
  30597. * the parameter.
  30598. *
  30599. * @augments Interpolant
  30600. */
  30601. class DiscreteInterpolant extends Interpolant {
  30602. /**
  30603. * Constructs a new discrete interpolant.
  30604. *
  30605. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30606. * @param {TypedArray} sampleValues - The sample values.
  30607. * @param {number} sampleSize - The sample size
  30608. * @param {TypedArray} [resultBuffer] - The result buffer.
  30609. */
  30610. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30611. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30612. }
  30613. interpolate_( i1 /*, t0, t, t1 */ ) {
  30614. return this.copySampleValue_( i1 - 1 );
  30615. }
  30616. }
  30617. /**
  30618. * Represents s a timed sequence of keyframes, which are composed of lists of
  30619. * times and related values, and which are used to animate a specific property
  30620. * of an object.
  30621. */
  30622. class KeyframeTrack {
  30623. /**
  30624. * Constructs a new keyframe track.
  30625. *
  30626. * @param {string} name - The keyframe track's name.
  30627. * @param {Array<number>} times - A list of keyframe times.
  30628. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30629. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30630. */
  30631. constructor( name, times, values, interpolation ) {
  30632. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30633. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30634. /**
  30635. * The track's name can refer to morph targets or bones or
  30636. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30637. * for the forms of strings that can be parsed for property binding.
  30638. *
  30639. * @type {string}
  30640. */
  30641. this.name = name;
  30642. /**
  30643. * The keyframe times.
  30644. *
  30645. * @type {Float32Array}
  30646. */
  30647. this.times = convertArray( times, this.TimeBufferType );
  30648. /**
  30649. * The keyframe values.
  30650. *
  30651. * @type {Float32Array}
  30652. */
  30653. this.values = convertArray( values, this.ValueBufferType );
  30654. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30655. }
  30656. /**
  30657. * Converts the keyframe track to JSON.
  30658. *
  30659. * @static
  30660. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30661. * @return {Object} The serialized keyframe track as JSON.
  30662. */
  30663. static toJSON( track ) {
  30664. const trackType = track.constructor;
  30665. let json;
  30666. // derived classes can define a static toJSON method
  30667. if ( trackType.toJSON !== this.toJSON ) {
  30668. json = trackType.toJSON( track );
  30669. } else {
  30670. // by default, we assume the data can be serialized as-is
  30671. json = {
  30672. 'name': track.name,
  30673. 'times': convertArray( track.times, Array ),
  30674. 'values': convertArray( track.values, Array )
  30675. };
  30676. const interpolation = track.getInterpolation();
  30677. if ( interpolation !== track.DefaultInterpolation ) {
  30678. json.interpolation = interpolation;
  30679. }
  30680. }
  30681. json.type = track.ValueTypeName; // mandatory
  30682. return json;
  30683. }
  30684. /**
  30685. * Factory method for creating a new discrete interpolant.
  30686. *
  30687. * @static
  30688. * @param {TypedArray} [result] - The result buffer.
  30689. * @return {DiscreteInterpolant} The new interpolant.
  30690. */
  30691. InterpolantFactoryMethodDiscrete( result ) {
  30692. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30693. }
  30694. /**
  30695. * Factory method for creating a new linear interpolant.
  30696. *
  30697. * @static
  30698. * @param {TypedArray} [result] - The result buffer.
  30699. * @return {LinearInterpolant} The new interpolant.
  30700. */
  30701. InterpolantFactoryMethodLinear( result ) {
  30702. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30703. }
  30704. /**
  30705. * Factory method for creating a new smooth interpolant.
  30706. *
  30707. * @static
  30708. * @param {TypedArray} [result] - The result buffer.
  30709. * @return {CubicInterpolant} The new interpolant.
  30710. */
  30711. InterpolantFactoryMethodSmooth( result ) {
  30712. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30713. }
  30714. /**
  30715. * Defines the interpolation factor method for this keyframe track.
  30716. *
  30717. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30718. * @return {KeyframeTrack} A reference to this keyframe track.
  30719. */
  30720. setInterpolation( interpolation ) {
  30721. let factoryMethod;
  30722. switch ( interpolation ) {
  30723. case InterpolateDiscrete:
  30724. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30725. break;
  30726. case InterpolateLinear:
  30727. factoryMethod = this.InterpolantFactoryMethodLinear;
  30728. break;
  30729. case InterpolateSmooth:
  30730. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30731. break;
  30732. }
  30733. if ( factoryMethod === undefined ) {
  30734. const message = 'unsupported interpolation for ' +
  30735. this.ValueTypeName + ' keyframe track named ' + this.name;
  30736. if ( this.createInterpolant === undefined ) {
  30737. // fall back to default, unless the default itself is messed up
  30738. if ( interpolation !== this.DefaultInterpolation ) {
  30739. this.setInterpolation( this.DefaultInterpolation );
  30740. } else {
  30741. throw new Error( message ); // fatal, in this case
  30742. }
  30743. }
  30744. console.warn( 'THREE.KeyframeTrack:', message );
  30745. return this;
  30746. }
  30747. this.createInterpolant = factoryMethod;
  30748. return this;
  30749. }
  30750. /**
  30751. * Returns the current interpolation type.
  30752. *
  30753. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30754. */
  30755. getInterpolation() {
  30756. switch ( this.createInterpolant ) {
  30757. case this.InterpolantFactoryMethodDiscrete:
  30758. return InterpolateDiscrete;
  30759. case this.InterpolantFactoryMethodLinear:
  30760. return InterpolateLinear;
  30761. case this.InterpolantFactoryMethodSmooth:
  30762. return InterpolateSmooth;
  30763. }
  30764. }
  30765. /**
  30766. * Returns the value size.
  30767. *
  30768. * @return {number} The value size.
  30769. */
  30770. getValueSize() {
  30771. return this.values.length / this.times.length;
  30772. }
  30773. /**
  30774. * Moves all keyframes either forward or backward in time.
  30775. *
  30776. * @param {number} timeOffset - The offset to move the time values.
  30777. * @return {KeyframeTrack} A reference to this keyframe track.
  30778. */
  30779. shift( timeOffset ) {
  30780. if ( timeOffset !== 0.0 ) {
  30781. const times = this.times;
  30782. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30783. times[ i ] += timeOffset;
  30784. }
  30785. }
  30786. return this;
  30787. }
  30788. /**
  30789. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30790. *
  30791. * @param {number} timeScale - The time scale.
  30792. * @return {KeyframeTrack} A reference to this keyframe track.
  30793. */
  30794. scale( timeScale ) {
  30795. if ( timeScale !== 1.0 ) {
  30796. const times = this.times;
  30797. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30798. times[ i ] *= timeScale;
  30799. }
  30800. }
  30801. return this;
  30802. }
  30803. /**
  30804. * Removes keyframes before and after animation without changing any values within the defined time range.
  30805. *
  30806. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30807. * keys this will change their values
  30808. *
  30809. * @param {number} startTime - The start time.
  30810. * @param {number} endTime - The end time.
  30811. * @return {KeyframeTrack} A reference to this keyframe track.
  30812. */
  30813. trim( startTime, endTime ) {
  30814. const times = this.times,
  30815. nKeys = times.length;
  30816. let from = 0,
  30817. to = nKeys - 1;
  30818. while ( from !== nKeys && times[ from ] < startTime ) {
  30819. ++ from;
  30820. }
  30821. while ( to !== -1 && times[ to ] > endTime ) {
  30822. -- to;
  30823. }
  30824. ++ to; // inclusive -> exclusive bound
  30825. if ( from !== 0 || to !== nKeys ) {
  30826. // empty tracks are forbidden, so keep at least one keyframe
  30827. if ( from >= to ) {
  30828. to = Math.max( to, 1 );
  30829. from = to - 1;
  30830. }
  30831. const stride = this.getValueSize();
  30832. this.times = times.slice( from, to );
  30833. this.values = this.values.slice( from * stride, to * stride );
  30834. }
  30835. return this;
  30836. }
  30837. /**
  30838. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30839. * are valid.
  30840. *
  30841. * @return {boolean} Whether the keyframes are valid or not.
  30842. */
  30843. validate() {
  30844. let valid = true;
  30845. const valueSize = this.getValueSize();
  30846. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30847. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  30848. valid = false;
  30849. }
  30850. const times = this.times,
  30851. values = this.values,
  30852. nKeys = times.length;
  30853. if ( nKeys === 0 ) {
  30854. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  30855. valid = false;
  30856. }
  30857. let prevTime = null;
  30858. for ( let i = 0; i !== nKeys; i ++ ) {
  30859. const currTime = times[ i ];
  30860. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30861. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30862. valid = false;
  30863. break;
  30864. }
  30865. if ( prevTime !== null && prevTime > currTime ) {
  30866. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30867. valid = false;
  30868. break;
  30869. }
  30870. prevTime = currTime;
  30871. }
  30872. if ( values !== undefined ) {
  30873. if ( isTypedArray( values ) ) {
  30874. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30875. const value = values[ i ];
  30876. if ( isNaN( value ) ) {
  30877. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  30878. valid = false;
  30879. break;
  30880. }
  30881. }
  30882. }
  30883. }
  30884. return valid;
  30885. }
  30886. /**
  30887. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30888. * common in morph target sequences).
  30889. *
  30890. * @return {AnimationClip} A reference to this animation clip.
  30891. */
  30892. optimize() {
  30893. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30894. // times or values may be shared with other tracks, so overwriting is unsafe
  30895. const times = this.times.slice(),
  30896. values = this.values.slice(),
  30897. stride = this.getValueSize(),
  30898. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  30899. lastIndex = times.length - 1;
  30900. let writeIndex = 1;
  30901. for ( let i = 1; i < lastIndex; ++ i ) {
  30902. let keep = false;
  30903. const time = times[ i ];
  30904. const timeNext = times[ i + 1 ];
  30905. // remove adjacent keyframes scheduled at the same time
  30906. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  30907. if ( ! smoothInterpolation ) {
  30908. // remove unnecessary keyframes same as their neighbors
  30909. const offset = i * stride,
  30910. offsetP = offset - stride,
  30911. offsetN = offset + stride;
  30912. for ( let j = 0; j !== stride; ++ j ) {
  30913. const value = values[ offset + j ];
  30914. if ( value !== values[ offsetP + j ] ||
  30915. value !== values[ offsetN + j ] ) {
  30916. keep = true;
  30917. break;
  30918. }
  30919. }
  30920. } else {
  30921. keep = true;
  30922. }
  30923. }
  30924. // in-place compaction
  30925. if ( keep ) {
  30926. if ( i !== writeIndex ) {
  30927. times[ writeIndex ] = times[ i ];
  30928. const readOffset = i * stride,
  30929. writeOffset = writeIndex * stride;
  30930. for ( let j = 0; j !== stride; ++ j ) {
  30931. values[ writeOffset + j ] = values[ readOffset + j ];
  30932. }
  30933. }
  30934. ++ writeIndex;
  30935. }
  30936. }
  30937. // flush last keyframe (compaction looks ahead)
  30938. if ( lastIndex > 0 ) {
  30939. times[ writeIndex ] = times[ lastIndex ];
  30940. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  30941. values[ writeOffset + j ] = values[ readOffset + j ];
  30942. }
  30943. ++ writeIndex;
  30944. }
  30945. if ( writeIndex !== times.length ) {
  30946. this.times = times.slice( 0, writeIndex );
  30947. this.values = values.slice( 0, writeIndex * stride );
  30948. } else {
  30949. this.times = times;
  30950. this.values = values;
  30951. }
  30952. return this;
  30953. }
  30954. /**
  30955. * Returns a new keyframe track with copied values from this instance.
  30956. *
  30957. * @return {KeyframeTrack} A clone of this instance.
  30958. */
  30959. clone() {
  30960. const times = this.times.slice();
  30961. const values = this.values.slice();
  30962. const TypedKeyframeTrack = this.constructor;
  30963. const track = new TypedKeyframeTrack( this.name, times, values );
  30964. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  30965. track.createInterpolant = this.createInterpolant;
  30966. return track;
  30967. }
  30968. }
  30969. /**
  30970. * The value type name.
  30971. *
  30972. * @type {String}
  30973. * @default ''
  30974. */
  30975. KeyframeTrack.prototype.ValueTypeName = '';
  30976. /**
  30977. * The time buffer type of this keyframe track.
  30978. *
  30979. * @type {TypedArray|Array}
  30980. * @default Float32Array.constructor
  30981. */
  30982. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  30983. /**
  30984. * The value buffer type of this keyframe track.
  30985. *
  30986. * @type {TypedArray|Array}
  30987. * @default Float32Array.constructor
  30988. */
  30989. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  30990. /**
  30991. * The default interpolation type of this keyframe track.
  30992. *
  30993. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  30994. * @default InterpolateLinear
  30995. */
  30996. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  30997. /**
  30998. * A track for boolean keyframe values.
  30999. *
  31000. * @augments KeyframeTrack
  31001. */
  31002. class BooleanKeyframeTrack extends KeyframeTrack {
  31003. /**
  31004. * Constructs a new boolean keyframe track.
  31005. *
  31006. * This keyframe track type has no `interpolation` parameter because the
  31007. * interpolation is always discrete.
  31008. *
  31009. * @param {string} name - The keyframe track's name.
  31010. * @param {Array<number>} times - A list of keyframe times.
  31011. * @param {Array<boolean>} values - A list of keyframe values.
  31012. */
  31013. constructor( name, times, values ) {
  31014. super( name, times, values );
  31015. }
  31016. }
  31017. /**
  31018. * The value type name.
  31019. *
  31020. * @type {String}
  31021. * @default 'bool'
  31022. */
  31023. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31024. /**
  31025. * The value buffer type of this keyframe track.
  31026. *
  31027. * @type {TypedArray|Array}
  31028. * @default Array.constructor
  31029. */
  31030. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31031. /**
  31032. * The default interpolation type of this keyframe track.
  31033. *
  31034. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31035. * @default InterpolateDiscrete
  31036. */
  31037. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31038. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31039. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31040. /**
  31041. * A track for color keyframe values.
  31042. *
  31043. * @augments KeyframeTrack
  31044. */
  31045. class ColorKeyframeTrack extends KeyframeTrack {
  31046. /**
  31047. * Constructs a new color keyframe track.
  31048. *
  31049. * @param {string} name - The keyframe track's name.
  31050. * @param {Array<number>} times - A list of keyframe times.
  31051. * @param {Array<number>} values - A list of keyframe values.
  31052. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31053. */
  31054. constructor( name, times, values, interpolation ) {
  31055. super( name, times, values, interpolation );
  31056. }
  31057. }
  31058. /**
  31059. * The value type name.
  31060. *
  31061. * @type {String}
  31062. * @default 'color'
  31063. */
  31064. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31065. /**
  31066. * A track for numeric keyframe values.
  31067. *
  31068. * @augments KeyframeTrack
  31069. */
  31070. class NumberKeyframeTrack extends KeyframeTrack {
  31071. /**
  31072. * Constructs a new number keyframe track.
  31073. *
  31074. * @param {string} name - The keyframe track's name.
  31075. * @param {Array<number>} times - A list of keyframe times.
  31076. * @param {Array<number>} values - A list of keyframe values.
  31077. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31078. */
  31079. constructor( name, times, values, interpolation ) {
  31080. super( name, times, values, interpolation );
  31081. }
  31082. }
  31083. /**
  31084. * The value type name.
  31085. *
  31086. * @type {String}
  31087. * @default 'number'
  31088. */
  31089. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31090. /**
  31091. * Spherical linear unit quaternion interpolant.
  31092. *
  31093. * @augments Interpolant
  31094. */
  31095. class QuaternionLinearInterpolant extends Interpolant {
  31096. /**
  31097. * Constructs a new SLERP interpolant.
  31098. *
  31099. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31100. * @param {TypedArray} sampleValues - The sample values.
  31101. * @param {number} sampleSize - The sample size
  31102. * @param {TypedArray} [resultBuffer] - The result buffer.
  31103. */
  31104. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31105. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31106. }
  31107. interpolate_( i1, t0, t, t1 ) {
  31108. const result = this.resultBuffer,
  31109. values = this.sampleValues,
  31110. stride = this.valueSize,
  31111. alpha = ( t - t0 ) / ( t1 - t0 );
  31112. let offset = i1 * stride;
  31113. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31114. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31115. }
  31116. return result;
  31117. }
  31118. }
  31119. /**
  31120. * A track for Quaternion keyframe values.
  31121. *
  31122. * @augments KeyframeTrack
  31123. */
  31124. class QuaternionKeyframeTrack extends KeyframeTrack {
  31125. /**
  31126. * Constructs a new Quaternion keyframe track.
  31127. *
  31128. * @param {string} name - The keyframe track's name.
  31129. * @param {Array<number>} times - A list of keyframe times.
  31130. * @param {Array<number>} values - A list of keyframe values.
  31131. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31132. */
  31133. constructor( name, times, values, interpolation ) {
  31134. super( name, times, values, interpolation );
  31135. }
  31136. /**
  31137. * Overwritten so the method returns Quaternion based interpolant.
  31138. *
  31139. * @static
  31140. * @param {TypedArray} [result] - The result buffer.
  31141. * @return {QuaternionLinearInterpolant} The new interpolant.
  31142. */
  31143. InterpolantFactoryMethodLinear( result ) {
  31144. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31145. }
  31146. }
  31147. /**
  31148. * The value type name.
  31149. *
  31150. * @type {String}
  31151. * @default 'quaternion'
  31152. */
  31153. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31154. // ValueBufferType is inherited
  31155. // DefaultInterpolation is inherited;
  31156. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31157. /**
  31158. * A track for string keyframe values.
  31159. *
  31160. * @augments KeyframeTrack
  31161. */
  31162. class StringKeyframeTrack extends KeyframeTrack {
  31163. /**
  31164. * Constructs a new string keyframe track.
  31165. *
  31166. * This keyframe track type has no `interpolation` parameter because the
  31167. * interpolation is always discrete.
  31168. *
  31169. * @param {string} name - The keyframe track's name.
  31170. * @param {Array<number>} times - A list of keyframe times.
  31171. * @param {Array<string>} values - A list of keyframe values.
  31172. */
  31173. constructor( name, times, values ) {
  31174. super( name, times, values );
  31175. }
  31176. }
  31177. /**
  31178. * The value type name.
  31179. *
  31180. * @type {String}
  31181. * @default 'string'
  31182. */
  31183. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31184. /**
  31185. * The value buffer type of this keyframe track.
  31186. *
  31187. * @type {TypedArray|Array}
  31188. * @default Array.constructor
  31189. */
  31190. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31191. /**
  31192. * The default interpolation type of this keyframe track.
  31193. *
  31194. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31195. * @default InterpolateDiscrete
  31196. */
  31197. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31198. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31199. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31200. /**
  31201. * A track for vector keyframe values.
  31202. *
  31203. * @augments KeyframeTrack
  31204. */
  31205. class VectorKeyframeTrack extends KeyframeTrack {
  31206. /**
  31207. * Constructs a new vector keyframe track.
  31208. *
  31209. * @param {string} name - The keyframe track's name.
  31210. * @param {Array<number>} times - A list of keyframe times.
  31211. * @param {Array<number>} values - A list of keyframe values.
  31212. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31213. */
  31214. constructor( name, times, values, interpolation ) {
  31215. super( name, times, values, interpolation );
  31216. }
  31217. }
  31218. /**
  31219. * The value type name.
  31220. *
  31221. * @type {String}
  31222. * @default 'vector'
  31223. */
  31224. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31225. /**
  31226. * A reusable set of keyframe tracks which represent an animation.
  31227. */
  31228. class AnimationClip {
  31229. /**
  31230. * Constructs a new animation clip.
  31231. *
  31232. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31233. * use the static interface of this class for creating clips. In most cases though, animation clips
  31234. * will automatically be created by loaders when importing animated 3D assets.
  31235. *
  31236. * @param {string} [name=''] - The clip's name.
  31237. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31238. * the duration will be calculated from the passed keyframes.
  31239. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31240. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31241. * is blended/combined when two or more animations are simultaneously played.
  31242. */
  31243. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31244. /**
  31245. * The clip's name.
  31246. *
  31247. * @type {string}
  31248. */
  31249. this.name = name;
  31250. /**
  31251. * An array of keyframe tracks.
  31252. *
  31253. * @type {Array<KeyframeTrack>}
  31254. */
  31255. this.tracks = tracks;
  31256. /**
  31257. * The clip's duration in seconds.
  31258. *
  31259. * @type {number}
  31260. */
  31261. this.duration = duration;
  31262. /**
  31263. * Defines how the animation is blended/combined when two or more animations
  31264. * are simultaneously played.
  31265. *
  31266. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31267. */
  31268. this.blendMode = blendMode;
  31269. /**
  31270. * The UUID of the animation clip.
  31271. *
  31272. * @type {string}
  31273. * @readonly
  31274. */
  31275. this.uuid = generateUUID();
  31276. // this means it should figure out its duration by scanning the tracks
  31277. if ( this.duration < 0 ) {
  31278. this.resetDuration();
  31279. }
  31280. }
  31281. /**
  31282. * Factory method for creating an animation clip from the given JSON.
  31283. *
  31284. * @static
  31285. * @param {Object} json - The serialized animation clip.
  31286. * @return {AnimationClip} The new animation clip.
  31287. */
  31288. static parse( json ) {
  31289. const tracks = [],
  31290. jsonTracks = json.tracks,
  31291. frameTime = 1.0 / ( json.fps || 1.0 );
  31292. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31293. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31294. }
  31295. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31296. clip.uuid = json.uuid;
  31297. return clip;
  31298. }
  31299. /**
  31300. * Serializes the given animation clip into JSON.
  31301. *
  31302. * @static
  31303. * @param {AnimationClip} clip - The animation clip to serialize.
  31304. * @return {Object} The JSON object.
  31305. */
  31306. static toJSON( clip ) {
  31307. const tracks = [],
  31308. clipTracks = clip.tracks;
  31309. const json = {
  31310. 'name': clip.name,
  31311. 'duration': clip.duration,
  31312. 'tracks': tracks,
  31313. 'uuid': clip.uuid,
  31314. 'blendMode': clip.blendMode
  31315. };
  31316. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31317. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31318. }
  31319. return json;
  31320. }
  31321. /**
  31322. * Returns a new animation clip from the passed morph targets array of a
  31323. * geometry, taking a name and the number of frames per second.
  31324. *
  31325. * Note: The fps parameter is required, but the animation speed can be
  31326. * overridden via {@link AnimationAction#setDuration}.
  31327. *
  31328. * @static
  31329. * @param {string} name - The name of the animation clip.
  31330. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31331. * @param {number} fps - The Frames-Per-Second value.
  31332. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31333. * @return {AnimationClip} The new animation clip.
  31334. */
  31335. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31336. const numMorphTargets = morphTargetSequence.length;
  31337. const tracks = [];
  31338. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31339. let times = [];
  31340. let values = [];
  31341. times.push(
  31342. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31343. i,
  31344. ( i + 1 ) % numMorphTargets );
  31345. values.push( 0, 1, 0 );
  31346. const order = getKeyframeOrder( times );
  31347. times = sortedArray( times, 1, order );
  31348. values = sortedArray( values, 1, order );
  31349. // if there is a key at the first frame, duplicate it as the
  31350. // last frame as well for perfect loop.
  31351. if ( ! noLoop && times[ 0 ] === 0 ) {
  31352. times.push( numMorphTargets );
  31353. values.push( values[ 0 ] );
  31354. }
  31355. tracks.push(
  31356. new NumberKeyframeTrack(
  31357. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31358. times, values
  31359. ).scale( 1.0 / fps ) );
  31360. }
  31361. return new this( name, -1, tracks );
  31362. }
  31363. /**
  31364. * Searches for an animation clip by name, taking as its first parameter
  31365. * either an array of clips, or a mesh or geometry that contains an
  31366. * array named "animations" property.
  31367. *
  31368. * @static
  31369. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31370. * @param {string} name - The name to search for.
  31371. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31372. */
  31373. static findByName( objectOrClipArray, name ) {
  31374. let clipArray = objectOrClipArray;
  31375. if ( ! Array.isArray( objectOrClipArray ) ) {
  31376. const o = objectOrClipArray;
  31377. clipArray = o.geometry && o.geometry.animations || o.animations;
  31378. }
  31379. for ( let i = 0; i < clipArray.length; i ++ ) {
  31380. if ( clipArray[ i ].name === name ) {
  31381. return clipArray[ i ];
  31382. }
  31383. }
  31384. return null;
  31385. }
  31386. /**
  31387. * Returns an array of new AnimationClips created from the morph target
  31388. * sequences of a geometry, trying to sort morph target names into
  31389. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31390. *
  31391. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31392. *
  31393. * @static
  31394. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31395. * @param {number} fps - The Frames-Per-Second value.
  31396. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31397. * @return {Array<AnimationClip>} An array of new animation clips.
  31398. */
  31399. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31400. const animationToMorphTargets = {};
  31401. // tested with https://regex101.com/ on trick sequences
  31402. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31403. const pattern = /^([\w-]*?)([\d]+)$/;
  31404. // sort morph target names into animation groups based
  31405. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31406. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31407. const morphTarget = morphTargets[ i ];
  31408. const parts = morphTarget.name.match( pattern );
  31409. if ( parts && parts.length > 1 ) {
  31410. const name = parts[ 1 ];
  31411. let animationMorphTargets = animationToMorphTargets[ name ];
  31412. if ( ! animationMorphTargets ) {
  31413. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31414. }
  31415. animationMorphTargets.push( morphTarget );
  31416. }
  31417. }
  31418. const clips = [];
  31419. for ( const name in animationToMorphTargets ) {
  31420. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31421. }
  31422. return clips;
  31423. }
  31424. /**
  31425. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31426. *
  31427. * @static
  31428. * @deprecated since r175.
  31429. * @param {Object} animation - A serialized animation clip as JSON.
  31430. * @param {Array<Bones>} bones - An array of bones.
  31431. * @return {?AnimationClip} The new animation clip.
  31432. */
  31433. static parseAnimation( animation, bones ) {
  31434. console.warn( 'THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31435. if ( ! animation ) {
  31436. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  31437. return null;
  31438. }
  31439. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31440. // only return track if there are actually keys.
  31441. if ( animationKeys.length !== 0 ) {
  31442. const times = [];
  31443. const values = [];
  31444. flattenJSON( animationKeys, times, values, propertyName );
  31445. // empty keys are filtered out, so check again
  31446. if ( times.length !== 0 ) {
  31447. destTracks.push( new trackType( trackName, times, values ) );
  31448. }
  31449. }
  31450. };
  31451. const tracks = [];
  31452. const clipName = animation.name || 'default';
  31453. const fps = animation.fps || 30;
  31454. const blendMode = animation.blendMode;
  31455. // automatic length determination in AnimationClip.
  31456. let duration = animation.length || -1;
  31457. const hierarchyTracks = animation.hierarchy || [];
  31458. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31459. const animationKeys = hierarchyTracks[ h ].keys;
  31460. // skip empty tracks
  31461. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31462. // process morph targets
  31463. if ( animationKeys[ 0 ].morphTargets ) {
  31464. // figure out all morph targets used in this track
  31465. const morphTargetNames = {};
  31466. let k;
  31467. for ( k = 0; k < animationKeys.length; k ++ ) {
  31468. if ( animationKeys[ k ].morphTargets ) {
  31469. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31470. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31471. }
  31472. }
  31473. }
  31474. // create a track for each morph target with all zero
  31475. // morphTargetInfluences except for the keys in which
  31476. // the morphTarget is named.
  31477. for ( const morphTargetName in morphTargetNames ) {
  31478. const times = [];
  31479. const values = [];
  31480. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31481. const animationKey = animationKeys[ k ];
  31482. times.push( animationKey.time );
  31483. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31484. }
  31485. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31486. }
  31487. duration = morphTargetNames.length * fps;
  31488. } else {
  31489. // ...assume skeletal animation
  31490. const boneName = '.bones[' + bones[ h ].name + ']';
  31491. addNonemptyTrack(
  31492. VectorKeyframeTrack, boneName + '.position',
  31493. animationKeys, 'pos', tracks );
  31494. addNonemptyTrack(
  31495. QuaternionKeyframeTrack, boneName + '.quaternion',
  31496. animationKeys, 'rot', tracks );
  31497. addNonemptyTrack(
  31498. VectorKeyframeTrack, boneName + '.scale',
  31499. animationKeys, 'scl', tracks );
  31500. }
  31501. }
  31502. if ( tracks.length === 0 ) {
  31503. return null;
  31504. }
  31505. const clip = new this( clipName, duration, tracks, blendMode );
  31506. return clip;
  31507. }
  31508. /**
  31509. * Sets the duration of this clip to the duration of its longest keyframe track.
  31510. *
  31511. * @return {AnimationClip} A reference to this animation clip.
  31512. */
  31513. resetDuration() {
  31514. const tracks = this.tracks;
  31515. let duration = 0;
  31516. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31517. const track = this.tracks[ i ];
  31518. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31519. }
  31520. this.duration = duration;
  31521. return this;
  31522. }
  31523. /**
  31524. * Trims all tracks to the clip's duration.
  31525. *
  31526. * @return {AnimationClip} A reference to this animation clip.
  31527. */
  31528. trim() {
  31529. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31530. this.tracks[ i ].trim( 0, this.duration );
  31531. }
  31532. return this;
  31533. }
  31534. /**
  31535. * Performs minimal validation on each track in the clip. Returns `true` if all
  31536. * tracks are valid.
  31537. *
  31538. * @return {boolean} Whether the clip's keyframes are valid or not.
  31539. */
  31540. validate() {
  31541. let valid = true;
  31542. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31543. valid = valid && this.tracks[ i ].validate();
  31544. }
  31545. return valid;
  31546. }
  31547. /**
  31548. * Optimizes each track by removing equivalent sequential keys (which are
  31549. * common in morph target sequences).
  31550. *
  31551. * @return {AnimationClip} A reference to this animation clip.
  31552. */
  31553. optimize() {
  31554. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31555. this.tracks[ i ].optimize();
  31556. }
  31557. return this;
  31558. }
  31559. /**
  31560. * Returns a new animation clip with copied values from this instance.
  31561. *
  31562. * @return {AnimationClip} A clone of this instance.
  31563. */
  31564. clone() {
  31565. const tracks = [];
  31566. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31567. tracks.push( this.tracks[ i ].clone() );
  31568. }
  31569. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31570. }
  31571. /**
  31572. * Serializes this animation clip into JSON.
  31573. *
  31574. * @return {Object} The JSON object.
  31575. */
  31576. toJSON() {
  31577. return this.constructor.toJSON( this );
  31578. }
  31579. }
  31580. function getTrackTypeForValueTypeName( typeName ) {
  31581. switch ( typeName.toLowerCase() ) {
  31582. case 'scalar':
  31583. case 'double':
  31584. case 'float':
  31585. case 'number':
  31586. case 'integer':
  31587. return NumberKeyframeTrack;
  31588. case 'vector':
  31589. case 'vector2':
  31590. case 'vector3':
  31591. case 'vector4':
  31592. return VectorKeyframeTrack;
  31593. case 'color':
  31594. return ColorKeyframeTrack;
  31595. case 'quaternion':
  31596. return QuaternionKeyframeTrack;
  31597. case 'bool':
  31598. case 'boolean':
  31599. return BooleanKeyframeTrack;
  31600. case 'string':
  31601. return StringKeyframeTrack;
  31602. }
  31603. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31604. }
  31605. function parseKeyframeTrack( json ) {
  31606. if ( json.type === undefined ) {
  31607. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31608. }
  31609. const trackType = getTrackTypeForValueTypeName( json.type );
  31610. if ( json.times === undefined ) {
  31611. const times = [], values = [];
  31612. flattenJSON( json.keys, times, values, 'value' );
  31613. json.times = times;
  31614. json.values = values;
  31615. }
  31616. // derived classes can define a static parse method
  31617. if ( trackType.parse !== undefined ) {
  31618. return trackType.parse( json );
  31619. } else {
  31620. // by default, we assume a constructor compatible with the base
  31621. return new trackType( json.name, json.times, json.values, json.interpolation );
  31622. }
  31623. }
  31624. /**
  31625. * @class
  31626. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31627. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31628. * @hideconstructor
  31629. */
  31630. const Cache = {
  31631. /**
  31632. * Whether caching is enabled or not.
  31633. *
  31634. * @static
  31635. * @type {boolean}
  31636. * @default false
  31637. */
  31638. enabled: false,
  31639. /**
  31640. * A dictionary that holds cached files.
  31641. *
  31642. * @static
  31643. * @type {Object<string,Object>}
  31644. */
  31645. files: {},
  31646. /**
  31647. * Adds a cache entry with a key to reference the file. If this key already
  31648. * holds a file, it is overwritten.
  31649. *
  31650. * @static
  31651. * @param {string} key - The key to reference the cached file.
  31652. * @param {Object} file - The file to be cached.
  31653. */
  31654. add: function ( key, file ) {
  31655. if ( this.enabled === false ) return;
  31656. // console.log( 'THREE.Cache', 'Adding key:', key );
  31657. this.files[ key ] = file;
  31658. },
  31659. /**
  31660. * Gets the cached value for the given key.
  31661. *
  31662. * @static
  31663. * @param {string} key - The key to reference the cached file.
  31664. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31665. */
  31666. get: function ( key ) {
  31667. if ( this.enabled === false ) return;
  31668. // console.log( 'THREE.Cache', 'Checking key:', key );
  31669. return this.files[ key ];
  31670. },
  31671. /**
  31672. * Removes the cached file associated with the given key.
  31673. *
  31674. * @static
  31675. * @param {string} key - The key to reference the cached file.
  31676. */
  31677. remove: function ( key ) {
  31678. delete this.files[ key ];
  31679. },
  31680. /**
  31681. * Remove all values from the cache.
  31682. *
  31683. * @static
  31684. */
  31685. clear: function () {
  31686. this.files = {};
  31687. }
  31688. };
  31689. /**
  31690. * Handles and keeps track of loaded and pending data. A default global
  31691. * instance of this class is created and used by loaders if not supplied
  31692. * manually.
  31693. *
  31694. * In general that should be sufficient, however there are times when it can
  31695. * be useful to have separate loaders - for example if you want to show
  31696. * separate loading bars for objects and textures.
  31697. *
  31698. * ```js
  31699. * const manager = new THREE.LoadingManager();
  31700. * manager.onLoad = () => console.log( 'Loading complete!' );
  31701. *
  31702. * const loader1 = new OBJLoader( manager );
  31703. * const loader2 = new ColladaLoader( manager );
  31704. * ```
  31705. */
  31706. class LoadingManager {
  31707. /**
  31708. * Constructs a new loading manager.
  31709. *
  31710. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31711. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31712. * @param {Function} [onError] - Executes when an error occurs.
  31713. */
  31714. constructor( onLoad, onProgress, onError ) {
  31715. const scope = this;
  31716. let isLoading = false;
  31717. let itemsLoaded = 0;
  31718. let itemsTotal = 0;
  31719. let urlModifier = undefined;
  31720. const handlers = [];
  31721. // Refer to #5689 for the reason why we don't set .onStart
  31722. // in the constructor
  31723. /**
  31724. * Executes when an item starts loading.
  31725. *
  31726. * @type {Function|undefined}
  31727. * @default undefined
  31728. */
  31729. this.onStart = undefined;
  31730. /**
  31731. * Executes when all items have been loaded.
  31732. *
  31733. * @type {Function|undefined}
  31734. * @default undefined
  31735. */
  31736. this.onLoad = onLoad;
  31737. /**
  31738. * Executes when single items have been loaded.
  31739. *
  31740. * @type {Function|undefined}
  31741. * @default undefined
  31742. */
  31743. this.onProgress = onProgress;
  31744. /**
  31745. * Executes when an error occurs.
  31746. *
  31747. * @type {Function|undefined}
  31748. * @default undefined
  31749. */
  31750. this.onError = onError;
  31751. /**
  31752. * Used for aborting ongoing requests in loaders using this manager.
  31753. *
  31754. * @type {AbortController}
  31755. */
  31756. this.abortController = new AbortController();
  31757. /**
  31758. * This should be called by any loader using the manager when the loader
  31759. * starts loading an item.
  31760. *
  31761. * @param {string} url - The URL to load.
  31762. */
  31763. this.itemStart = function ( url ) {
  31764. itemsTotal ++;
  31765. if ( isLoading === false ) {
  31766. if ( scope.onStart !== undefined ) {
  31767. scope.onStart( url, itemsLoaded, itemsTotal );
  31768. }
  31769. }
  31770. isLoading = true;
  31771. };
  31772. /**
  31773. * This should be called by any loader using the manager when the loader
  31774. * ended loading an item.
  31775. *
  31776. * @param {string} url - The URL of the loaded item.
  31777. */
  31778. this.itemEnd = function ( url ) {
  31779. itemsLoaded ++;
  31780. if ( scope.onProgress !== undefined ) {
  31781. scope.onProgress( url, itemsLoaded, itemsTotal );
  31782. }
  31783. if ( itemsLoaded === itemsTotal ) {
  31784. isLoading = false;
  31785. if ( scope.onLoad !== undefined ) {
  31786. scope.onLoad();
  31787. }
  31788. }
  31789. };
  31790. /**
  31791. * This should be called by any loader using the manager when the loader
  31792. * encounters an error when loading an item.
  31793. *
  31794. * @param {string} url - The URL of the item that produces an error.
  31795. */
  31796. this.itemError = function ( url ) {
  31797. if ( scope.onError !== undefined ) {
  31798. scope.onError( url );
  31799. }
  31800. };
  31801. /**
  31802. * Given a URL, uses the URL modifier callback (if any) and returns a
  31803. * resolved URL. If no URL modifier is set, returns the original URL.
  31804. *
  31805. * @param {string} url - The URL to load.
  31806. * @return {string} The resolved URL.
  31807. */
  31808. this.resolveURL = function ( url ) {
  31809. if ( urlModifier ) {
  31810. return urlModifier( url );
  31811. }
  31812. return url;
  31813. };
  31814. /**
  31815. * If provided, the callback will be passed each resource URL before a
  31816. * request is sent. The callback may return the original URL, or a new URL to
  31817. * override loading behavior. This behavior can be used to load assets from
  31818. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31819. *
  31820. * ```js
  31821. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31822. *
  31823. * const manager = new THREE.LoadingManager();
  31824. *
  31825. * // Initialize loading manager with URL callback.
  31826. * const objectURLs = [];
  31827. * manager.setURLModifier( ( url ) => {
  31828. *
  31829. * url = URL.createObjectURL( blobs[ url ] );
  31830. * objectURLs.push( url );
  31831. * return url;
  31832. *
  31833. * } );
  31834. *
  31835. * // Load as usual, then revoke the blob URLs.
  31836. * const loader = new GLTFLoader( manager );
  31837. * loader.load( 'fish.gltf', (gltf) => {
  31838. *
  31839. * scene.add( gltf.scene );
  31840. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31841. *
  31842. * } );
  31843. * ```
  31844. *
  31845. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31846. * @return {LoadingManager} A reference to this loading manager.
  31847. */
  31848. this.setURLModifier = function ( transform ) {
  31849. urlModifier = transform;
  31850. return this;
  31851. };
  31852. /**
  31853. * Registers a loader with the given regular expression. Can be used to
  31854. * define what loader should be used in order to load specific files. A
  31855. * typical use case is to overwrite the default loader for textures.
  31856. *
  31857. * ```js
  31858. * // add handler for TGA textures
  31859. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31860. * ```
  31861. *
  31862. * @param {string} regex - A regular expression.
  31863. * @param {Loader} loader - A loader that should handle matched cases.
  31864. * @return {LoadingManager} A reference to this loading manager.
  31865. */
  31866. this.addHandler = function ( regex, loader ) {
  31867. handlers.push( regex, loader );
  31868. return this;
  31869. };
  31870. /**
  31871. * Removes the loader for the given regular expression.
  31872. *
  31873. * @param {string} regex - A regular expression.
  31874. * @return {LoadingManager} A reference to this loading manager.
  31875. */
  31876. this.removeHandler = function ( regex ) {
  31877. const index = handlers.indexOf( regex );
  31878. if ( index !== -1 ) {
  31879. handlers.splice( index, 2 );
  31880. }
  31881. return this;
  31882. };
  31883. /**
  31884. * Can be used to retrieve the registered loader for the given file path.
  31885. *
  31886. * @param {string} file - The file path.
  31887. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  31888. */
  31889. this.getHandler = function ( file ) {
  31890. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  31891. const regex = handlers[ i ];
  31892. const loader = handlers[ i + 1 ];
  31893. if ( regex.global ) regex.lastIndex = 0; // see #17920
  31894. if ( regex.test( file ) ) {
  31895. return loader;
  31896. }
  31897. }
  31898. return null;
  31899. };
  31900. /**
  31901. * Can be used to abort ongoing loading requests in loaders using this manager.
  31902. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  31903. * is supported in the browser.
  31904. *
  31905. * @return {LoadingManager} A reference to this loading manager.
  31906. */
  31907. this.abort = function () {
  31908. this.abortController.abort();
  31909. this.abortController = new AbortController();
  31910. return this;
  31911. };
  31912. }
  31913. }
  31914. /**
  31915. * The global default loading manager.
  31916. *
  31917. * @constant
  31918. * @type {LoadingManager}
  31919. */
  31920. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  31921. /**
  31922. * Abstract base class for loaders.
  31923. *
  31924. * @abstract
  31925. */
  31926. class Loader {
  31927. /**
  31928. * Constructs a new loader.
  31929. *
  31930. * @param {LoadingManager} [manager] - The loading manager.
  31931. */
  31932. constructor( manager ) {
  31933. /**
  31934. * The loading manager.
  31935. *
  31936. * @type {LoadingManager}
  31937. * @default DefaultLoadingManager
  31938. */
  31939. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  31940. /**
  31941. * The crossOrigin string to implement CORS for loading the url from a
  31942. * different domain that allows CORS.
  31943. *
  31944. * @type {string}
  31945. * @default 'anonymous'
  31946. */
  31947. this.crossOrigin = 'anonymous';
  31948. /**
  31949. * Whether the XMLHttpRequest uses credentials.
  31950. *
  31951. * @type {boolean}
  31952. * @default false
  31953. */
  31954. this.withCredentials = false;
  31955. /**
  31956. * The base path from which the asset will be loaded.
  31957. *
  31958. * @type {string}
  31959. */
  31960. this.path = '';
  31961. /**
  31962. * The base path from which additional resources like textures will be loaded.
  31963. *
  31964. * @type {string}
  31965. */
  31966. this.resourcePath = '';
  31967. /**
  31968. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  31969. * used in HTTP request.
  31970. *
  31971. * @type {Object<string, any>}
  31972. */
  31973. this.requestHeader = {};
  31974. }
  31975. /**
  31976. * This method needs to be implemented by all concrete loaders. It holds the
  31977. * logic for loading assets from the backend.
  31978. *
  31979. * @abstract
  31980. * @param {string} url - The path/URL of the file to be loaded.
  31981. * @param {Function} onLoad - Executed when the loading process has been finished.
  31982. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31983. * @param {onErrorCallback} [onError] - Executed when errors occur.
  31984. */
  31985. load( /* url, onLoad, onProgress, onError */ ) {}
  31986. /**
  31987. * A async version of {@link Loader#load}.
  31988. *
  31989. * @param {string} url - The path/URL of the file to be loaded.
  31990. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  31991. * @return {Promise} A Promise that resolves when the asset has been loaded.
  31992. */
  31993. loadAsync( url, onProgress ) {
  31994. const scope = this;
  31995. return new Promise( function ( resolve, reject ) {
  31996. scope.load( url, resolve, onProgress, reject );
  31997. } );
  31998. }
  31999. /**
  32000. * This method needs to be implemented by all concrete loaders. It holds the
  32001. * logic for parsing the asset into three.js entities.
  32002. *
  32003. * @abstract
  32004. * @param {any} data - The data to parse.
  32005. */
  32006. parse( /* data */ ) {}
  32007. /**
  32008. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32009. * from a different domain that allows CORS.
  32010. *
  32011. * @param {string} crossOrigin - The `crossOrigin` value.
  32012. * @return {Loader} A reference to this instance.
  32013. */
  32014. setCrossOrigin( crossOrigin ) {
  32015. this.crossOrigin = crossOrigin;
  32016. return this;
  32017. }
  32018. /**
  32019. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32020. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32021. *
  32022. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32023. *
  32024. * @param {boolean} value - The `withCredentials` value.
  32025. * @return {Loader} A reference to this instance.
  32026. */
  32027. setWithCredentials( value ) {
  32028. this.withCredentials = value;
  32029. return this;
  32030. }
  32031. /**
  32032. * Sets the base path for the asset.
  32033. *
  32034. * @param {string} path - The base path.
  32035. * @return {Loader} A reference to this instance.
  32036. */
  32037. setPath( path ) {
  32038. this.path = path;
  32039. return this;
  32040. }
  32041. /**
  32042. * Sets the base path for dependent resources like textures.
  32043. *
  32044. * @param {string} resourcePath - The resource path.
  32045. * @return {Loader} A reference to this instance.
  32046. */
  32047. setResourcePath( resourcePath ) {
  32048. this.resourcePath = resourcePath;
  32049. return this;
  32050. }
  32051. /**
  32052. * Sets the given request header.
  32053. *
  32054. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32055. * for configuring the HTTP request.
  32056. * @return {Loader} A reference to this instance.
  32057. */
  32058. setRequestHeader( requestHeader ) {
  32059. this.requestHeader = requestHeader;
  32060. return this;
  32061. }
  32062. /**
  32063. * This method can be implemented in loaders for aborting ongoing requests.
  32064. *
  32065. * @abstract
  32066. * @return {Loader} A reference to this instance.
  32067. */
  32068. abort() {
  32069. return this;
  32070. }
  32071. }
  32072. /**
  32073. * Callback for onProgress in loaders.
  32074. *
  32075. * @callback onProgressCallback
  32076. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32077. */
  32078. /**
  32079. * Callback for onError in loaders.
  32080. *
  32081. * @callback onErrorCallback
  32082. * @param {Error} error - The error which occurred during the loading process.
  32083. */
  32084. /**
  32085. * The default material name that is used by loaders
  32086. * when creating materials for loaded 3D objects.
  32087. *
  32088. * Note: Not all loaders might honor this setting.
  32089. *
  32090. * @static
  32091. * @type {string}
  32092. * @default '__DEFAULT'
  32093. */
  32094. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32095. const loading = {};
  32096. class HttpError extends Error {
  32097. constructor( message, response ) {
  32098. super( message );
  32099. this.response = response;
  32100. }
  32101. }
  32102. /**
  32103. * A low level class for loading resources with the Fetch API, used internally by
  32104. * most loaders. It can also be used directly to load any file type that does
  32105. * not have a loader.
  32106. *
  32107. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32108. * once to your application.
  32109. *
  32110. * ```js
  32111. * const loader = new THREE.FileLoader();
  32112. * const data = await loader.loadAsync( 'example.txt' );
  32113. * ```
  32114. *
  32115. * @augments Loader
  32116. */
  32117. class FileLoader extends Loader {
  32118. /**
  32119. * Constructs a new file loader.
  32120. *
  32121. * @param {LoadingManager} [manager] - The loading manager.
  32122. */
  32123. constructor( manager ) {
  32124. super( manager );
  32125. /**
  32126. * The expected mime type. Valid values can be found
  32127. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32128. *
  32129. * @type {string}
  32130. */
  32131. this.mimeType = '';
  32132. /**
  32133. * The expected response type.
  32134. *
  32135. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32136. * @default ''
  32137. */
  32138. this.responseType = '';
  32139. /**
  32140. * Used for aborting requests.
  32141. *
  32142. * @private
  32143. * @type {AbortController}
  32144. */
  32145. this._abortController = new AbortController();
  32146. }
  32147. /**
  32148. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32149. *
  32150. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32151. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32152. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32153. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32154. * @return {any|undefined} The cached resource if available.
  32155. */
  32156. load( url, onLoad, onProgress, onError ) {
  32157. if ( url === undefined ) url = '';
  32158. if ( this.path !== undefined ) url = this.path + url;
  32159. url = this.manager.resolveURL( url );
  32160. const cached = Cache.get( `file:${url}` );
  32161. if ( cached !== undefined ) {
  32162. this.manager.itemStart( url );
  32163. setTimeout( () => {
  32164. if ( onLoad ) onLoad( cached );
  32165. this.manager.itemEnd( url );
  32166. }, 0 );
  32167. return cached;
  32168. }
  32169. // Check if request is duplicate
  32170. if ( loading[ url ] !== undefined ) {
  32171. loading[ url ].push( {
  32172. onLoad: onLoad,
  32173. onProgress: onProgress,
  32174. onError: onError
  32175. } );
  32176. return;
  32177. }
  32178. // Initialise array for duplicate requests
  32179. loading[ url ] = [];
  32180. loading[ url ].push( {
  32181. onLoad: onLoad,
  32182. onProgress: onProgress,
  32183. onError: onError,
  32184. } );
  32185. // create request
  32186. const req = new Request( url, {
  32187. headers: new Headers( this.requestHeader ),
  32188. credentials: this.withCredentials ? 'include' : 'same-origin',
  32189. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32190. } );
  32191. // record states ( avoid data race )
  32192. const mimeType = this.mimeType;
  32193. const responseType = this.responseType;
  32194. // start the fetch
  32195. fetch( req )
  32196. .then( response => {
  32197. if ( response.status === 200 || response.status === 0 ) {
  32198. // Some browsers return HTTP Status 0 when using non-http protocol
  32199. // e.g. 'file://' or 'data://'. Handle as success.
  32200. if ( response.status === 0 ) {
  32201. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  32202. }
  32203. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32204. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32205. return response;
  32206. }
  32207. const callbacks = loading[ url ];
  32208. const reader = response.body.getReader();
  32209. // Nginx needs X-File-Size check
  32210. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32211. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32212. const total = contentLength ? parseInt( contentLength ) : 0;
  32213. const lengthComputable = total !== 0;
  32214. let loaded = 0;
  32215. // periodically read data into the new stream tracking while download progress
  32216. const stream = new ReadableStream( {
  32217. start( controller ) {
  32218. readData();
  32219. function readData() {
  32220. reader.read().then( ( { done, value } ) => {
  32221. if ( done ) {
  32222. controller.close();
  32223. } else {
  32224. loaded += value.byteLength;
  32225. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32226. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32227. const callback = callbacks[ i ];
  32228. if ( callback.onProgress ) callback.onProgress( event );
  32229. }
  32230. controller.enqueue( value );
  32231. readData();
  32232. }
  32233. }, ( e ) => {
  32234. controller.error( e );
  32235. } );
  32236. }
  32237. }
  32238. } );
  32239. return new Response( stream );
  32240. } else {
  32241. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32242. }
  32243. } )
  32244. .then( response => {
  32245. switch ( responseType ) {
  32246. case 'arraybuffer':
  32247. return response.arrayBuffer();
  32248. case 'blob':
  32249. return response.blob();
  32250. case 'document':
  32251. return response.text()
  32252. .then( text => {
  32253. const parser = new DOMParser();
  32254. return parser.parseFromString( text, mimeType );
  32255. } );
  32256. case 'json':
  32257. return response.json();
  32258. default:
  32259. if ( mimeType === '' ) {
  32260. return response.text();
  32261. } else {
  32262. // sniff encoding
  32263. const re = /charset="?([^;"\s]*)"?/i;
  32264. const exec = re.exec( mimeType );
  32265. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32266. const decoder = new TextDecoder( label );
  32267. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32268. }
  32269. }
  32270. } )
  32271. .then( data => {
  32272. // Add to cache only on HTTP success, so that we do not cache
  32273. // error response bodies as proper responses to requests.
  32274. Cache.add( `file:${url}`, data );
  32275. const callbacks = loading[ url ];
  32276. delete loading[ url ];
  32277. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32278. const callback = callbacks[ i ];
  32279. if ( callback.onLoad ) callback.onLoad( data );
  32280. }
  32281. } )
  32282. .catch( err => {
  32283. // Abort errors and other errors are handled the same
  32284. const callbacks = loading[ url ];
  32285. if ( callbacks === undefined ) {
  32286. // When onLoad was called and url was deleted in `loading`
  32287. this.manager.itemError( url );
  32288. throw err;
  32289. }
  32290. delete loading[ url ];
  32291. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32292. const callback = callbacks[ i ];
  32293. if ( callback.onError ) callback.onError( err );
  32294. }
  32295. this.manager.itemError( url );
  32296. } )
  32297. .finally( () => {
  32298. this.manager.itemEnd( url );
  32299. } );
  32300. this.manager.itemStart( url );
  32301. }
  32302. /**
  32303. * Sets the expected response type.
  32304. *
  32305. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32306. * @return {FileLoader} A reference to this file loader.
  32307. */
  32308. setResponseType( value ) {
  32309. this.responseType = value;
  32310. return this;
  32311. }
  32312. /**
  32313. * Sets the expected mime type of the loaded file.
  32314. *
  32315. * @param {string} value - The mime type.
  32316. * @return {FileLoader} A reference to this file loader.
  32317. */
  32318. setMimeType( value ) {
  32319. this.mimeType = value;
  32320. return this;
  32321. }
  32322. /**
  32323. * Aborts ongoing fetch requests.
  32324. *
  32325. * @return {FileLoader} A reference to this instance.
  32326. */
  32327. abort() {
  32328. this._abortController.abort();
  32329. this._abortController = new AbortController();
  32330. return this;
  32331. }
  32332. }
  32333. /**
  32334. * Class for loading animation clips in the JSON format. The files are internally
  32335. * loaded via {@link FileLoader}.
  32336. *
  32337. * ```js
  32338. * const loader = new THREE.AnimationLoader();
  32339. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32340. * ```
  32341. *
  32342. * @augments Loader
  32343. */
  32344. class AnimationLoader extends Loader {
  32345. /**
  32346. * Constructs a new animation loader.
  32347. *
  32348. * @param {LoadingManager} [manager] - The loading manager.
  32349. */
  32350. constructor( manager ) {
  32351. super( manager );
  32352. }
  32353. /**
  32354. * Starts loading from the given URL and pass the loaded animations as an array
  32355. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32356. *
  32357. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32358. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32359. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32360. * @param {onErrorCallback} onError - Executed when errors occur.
  32361. */
  32362. load( url, onLoad, onProgress, onError ) {
  32363. const scope = this;
  32364. const loader = new FileLoader( this.manager );
  32365. loader.setPath( this.path );
  32366. loader.setRequestHeader( this.requestHeader );
  32367. loader.setWithCredentials( this.withCredentials );
  32368. loader.load( url, function ( text ) {
  32369. try {
  32370. onLoad( scope.parse( JSON.parse( text ) ) );
  32371. } catch ( e ) {
  32372. if ( onError ) {
  32373. onError( e );
  32374. } else {
  32375. console.error( e );
  32376. }
  32377. scope.manager.itemError( url );
  32378. }
  32379. }, onProgress, onError );
  32380. }
  32381. /**
  32382. * Parses the given JSON object and returns an array of animation clips.
  32383. *
  32384. * @param {Object} json - The serialized animation clips.
  32385. * @return {Array<AnimationClip>} The parsed animation clips.
  32386. */
  32387. parse( json ) {
  32388. const animations = [];
  32389. for ( let i = 0; i < json.length; i ++ ) {
  32390. const clip = AnimationClip.parse( json[ i ] );
  32391. animations.push( clip );
  32392. }
  32393. return animations;
  32394. }
  32395. }
  32396. /**
  32397. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32398. * Textures are internally loaded via {@link FileLoader}.
  32399. *
  32400. * Derived classes have to implement the `parse()` method which holds the parsing
  32401. * for the respective format.
  32402. *
  32403. * @abstract
  32404. * @augments Loader
  32405. */
  32406. class CompressedTextureLoader extends Loader {
  32407. /**
  32408. * Constructs a new compressed texture loader.
  32409. *
  32410. * @param {LoadingManager} [manager] - The loading manager.
  32411. */
  32412. constructor( manager ) {
  32413. super( manager );
  32414. }
  32415. /**
  32416. * Starts loading from the given URL and passes the loaded compressed texture
  32417. * to the `onLoad()` callback. The method also returns a new texture object which can
  32418. * directly be used for material creation. If you do it this way, the texture
  32419. * may pop up in your scene once the respective loading process is finished.
  32420. *
  32421. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32422. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32423. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32424. * @param {onErrorCallback} onError - Executed when errors occur.
  32425. * @return {CompressedTexture} The compressed texture.
  32426. */
  32427. load( url, onLoad, onProgress, onError ) {
  32428. const scope = this;
  32429. const images = [];
  32430. const texture = new CompressedTexture();
  32431. const loader = new FileLoader( this.manager );
  32432. loader.setPath( this.path );
  32433. loader.setResponseType( 'arraybuffer' );
  32434. loader.setRequestHeader( this.requestHeader );
  32435. loader.setWithCredentials( scope.withCredentials );
  32436. let loaded = 0;
  32437. function loadTexture( i ) {
  32438. loader.load( url[ i ], function ( buffer ) {
  32439. const texDatas = scope.parse( buffer, true );
  32440. images[ i ] = {
  32441. width: texDatas.width,
  32442. height: texDatas.height,
  32443. format: texDatas.format,
  32444. mipmaps: texDatas.mipmaps
  32445. };
  32446. loaded += 1;
  32447. if ( loaded === 6 ) {
  32448. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32449. texture.image = images;
  32450. texture.format = texDatas.format;
  32451. texture.needsUpdate = true;
  32452. if ( onLoad ) onLoad( texture );
  32453. }
  32454. }, onProgress, onError );
  32455. }
  32456. if ( Array.isArray( url ) ) {
  32457. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32458. loadTexture( i );
  32459. }
  32460. } else {
  32461. // compressed cubemap texture stored in a single DDS file
  32462. loader.load( url, function ( buffer ) {
  32463. const texDatas = scope.parse( buffer, true );
  32464. if ( texDatas.isCubemap ) {
  32465. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32466. for ( let f = 0; f < faces; f ++ ) {
  32467. images[ f ] = { mipmaps: [] };
  32468. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32469. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32470. images[ f ].format = texDatas.format;
  32471. images[ f ].width = texDatas.width;
  32472. images[ f ].height = texDatas.height;
  32473. }
  32474. }
  32475. texture.image = images;
  32476. } else {
  32477. texture.image.width = texDatas.width;
  32478. texture.image.height = texDatas.height;
  32479. texture.mipmaps = texDatas.mipmaps;
  32480. }
  32481. if ( texDatas.mipmapCount === 1 ) {
  32482. texture.minFilter = LinearFilter;
  32483. }
  32484. texture.format = texDatas.format;
  32485. texture.needsUpdate = true;
  32486. if ( onLoad ) onLoad( texture );
  32487. }, onProgress, onError );
  32488. }
  32489. return texture;
  32490. }
  32491. }
  32492. const _loading = new WeakMap();
  32493. /**
  32494. * A loader for loading images. The class loads images with the HTML `Image` API.
  32495. *
  32496. * ```js
  32497. * const loader = new THREE.ImageLoader();
  32498. * const image = await loader.loadAsync( 'image.png' );
  32499. * ```
  32500. * Please note that `ImageLoader` has dropped support for progress
  32501. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32502. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32503. *
  32504. * @augments Loader
  32505. */
  32506. class ImageLoader extends Loader {
  32507. /**
  32508. * Constructs a new image loader.
  32509. *
  32510. * @param {LoadingManager} [manager] - The loading manager.
  32511. */
  32512. constructor( manager ) {
  32513. super( manager );
  32514. }
  32515. /**
  32516. * Starts loading from the given URL and passes the loaded image
  32517. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32518. * directly be used for texture creation. If you do it this way, the texture
  32519. * may pop up in your scene once the respective loading process is finished.
  32520. *
  32521. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32522. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32523. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32524. * @param {onErrorCallback} onError - Executed when errors occur.
  32525. * @return {Image} The image.
  32526. */
  32527. load( url, onLoad, onProgress, onError ) {
  32528. if ( this.path !== undefined ) url = this.path + url;
  32529. url = this.manager.resolveURL( url );
  32530. const scope = this;
  32531. const cached = Cache.get( `image:${url}` );
  32532. if ( cached !== undefined ) {
  32533. if ( cached.complete === true ) {
  32534. scope.manager.itemStart( url );
  32535. setTimeout( function () {
  32536. if ( onLoad ) onLoad( cached );
  32537. scope.manager.itemEnd( url );
  32538. }, 0 );
  32539. } else {
  32540. let arr = _loading.get( cached );
  32541. if ( arr === undefined ) {
  32542. arr = [];
  32543. _loading.set( cached, arr );
  32544. }
  32545. arr.push( { onLoad, onError } );
  32546. }
  32547. return cached;
  32548. }
  32549. const image = createElementNS( 'img' );
  32550. function onImageLoad() {
  32551. removeEventListeners();
  32552. if ( onLoad ) onLoad( this );
  32553. //
  32554. const callbacks = _loading.get( this ) || [];
  32555. for ( let i = 0; i < callbacks.length; i ++ ) {
  32556. const callback = callbacks[ i ];
  32557. if ( callback.onLoad ) callback.onLoad( this );
  32558. }
  32559. _loading.delete( this );
  32560. scope.manager.itemEnd( url );
  32561. }
  32562. function onImageError( event ) {
  32563. removeEventListeners();
  32564. if ( onError ) onError( event );
  32565. Cache.remove( `image:${url}` );
  32566. //
  32567. const callbacks = _loading.get( this ) || [];
  32568. for ( let i = 0; i < callbacks.length; i ++ ) {
  32569. const callback = callbacks[ i ];
  32570. if ( callback.onError ) callback.onError( event );
  32571. }
  32572. _loading.delete( this );
  32573. scope.manager.itemError( url );
  32574. scope.manager.itemEnd( url );
  32575. }
  32576. function removeEventListeners() {
  32577. image.removeEventListener( 'load', onImageLoad, false );
  32578. image.removeEventListener( 'error', onImageError, false );
  32579. }
  32580. image.addEventListener( 'load', onImageLoad, false );
  32581. image.addEventListener( 'error', onImageError, false );
  32582. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32583. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32584. }
  32585. Cache.add( `image:${url}`, image );
  32586. scope.manager.itemStart( url );
  32587. image.src = url;
  32588. return image;
  32589. }
  32590. }
  32591. /**
  32592. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32593. *
  32594. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32595. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32596. * like vertical and horizontal cross, column and row layouts are not supported.
  32597. *
  32598. * Note that, by convention, cube maps are specified in a coordinate system
  32599. * in which positive-x is to the right when looking up the positive-z axis --
  32600. * in other words, using a left-handed coordinate system. Since three.js uses
  32601. * a right-handed coordinate system, environment maps used in three.js will
  32602. * have pos-x and neg-x swapped.
  32603. *
  32604. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32605. * is set to `SRGBColorSpace` by default.
  32606. *
  32607. * ```js
  32608. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32609. * const cubeTexture = await loader.loadAsync( [
  32610. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32611. * ] );
  32612. * scene.background = cubeTexture;
  32613. * ```
  32614. *
  32615. * @augments Loader
  32616. */
  32617. class CubeTextureLoader extends Loader {
  32618. /**
  32619. * Constructs a new cube texture loader.
  32620. *
  32621. * @param {LoadingManager} [manager] - The loading manager.
  32622. */
  32623. constructor( manager ) {
  32624. super( manager );
  32625. }
  32626. /**
  32627. * Starts loading from the given URL and pass the fully loaded cube texture
  32628. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32629. * directly be used for material creation. If you do it this way, the cube texture
  32630. * may pop up in your scene once the respective loading process is finished.
  32631. *
  32632. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32633. * cube texture. The urls should be specified in the following order: pos-x,
  32634. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32635. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32636. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32637. * @param {onErrorCallback} onError - Executed when errors occur.
  32638. * @return {CubeTexture} The cube texture.
  32639. */
  32640. load( urls, onLoad, onProgress, onError ) {
  32641. const texture = new CubeTexture();
  32642. texture.colorSpace = SRGBColorSpace;
  32643. const loader = new ImageLoader( this.manager );
  32644. loader.setCrossOrigin( this.crossOrigin );
  32645. loader.setPath( this.path );
  32646. let loaded = 0;
  32647. function loadTexture( i ) {
  32648. loader.load( urls[ i ], function ( image ) {
  32649. texture.images[ i ] = image;
  32650. loaded ++;
  32651. if ( loaded === 6 ) {
  32652. texture.needsUpdate = true;
  32653. if ( onLoad ) onLoad( texture );
  32654. }
  32655. }, undefined, onError );
  32656. }
  32657. for ( let i = 0; i < urls.length; ++ i ) {
  32658. loadTexture( i );
  32659. }
  32660. return texture;
  32661. }
  32662. }
  32663. /**
  32664. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32665. * Textures are internally loaded via {@link FileLoader}.
  32666. *
  32667. * Derived classes have to implement the `parse()` method which holds the parsing
  32668. * for the respective format.
  32669. *
  32670. * @abstract
  32671. * @augments Loader
  32672. */
  32673. class DataTextureLoader extends Loader {
  32674. /**
  32675. * Constructs a new data texture loader.
  32676. *
  32677. * @param {LoadingManager} [manager] - The loading manager.
  32678. */
  32679. constructor( manager ) {
  32680. super( manager );
  32681. }
  32682. /**
  32683. * Starts loading from the given URL and passes the loaded data texture
  32684. * to the `onLoad()` callback. The method also returns a new texture object which can
  32685. * directly be used for material creation. If you do it this way, the texture
  32686. * may pop up in your scene once the respective loading process is finished.
  32687. *
  32688. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32689. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32690. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32691. * @param {onErrorCallback} onError - Executed when errors occur.
  32692. * @return {DataTexture} The data texture.
  32693. */
  32694. load( url, onLoad, onProgress, onError ) {
  32695. const scope = this;
  32696. const texture = new DataTexture();
  32697. const loader = new FileLoader( this.manager );
  32698. loader.setResponseType( 'arraybuffer' );
  32699. loader.setRequestHeader( this.requestHeader );
  32700. loader.setPath( this.path );
  32701. loader.setWithCredentials( scope.withCredentials );
  32702. loader.load( url, function ( buffer ) {
  32703. let texData;
  32704. try {
  32705. texData = scope.parse( buffer );
  32706. } catch ( error ) {
  32707. if ( onError !== undefined ) {
  32708. onError( error );
  32709. } else {
  32710. console.error( error );
  32711. return;
  32712. }
  32713. }
  32714. if ( texData.image !== undefined ) {
  32715. texture.image = texData.image;
  32716. } else if ( texData.data !== undefined ) {
  32717. texture.image.width = texData.width;
  32718. texture.image.height = texData.height;
  32719. texture.image.data = texData.data;
  32720. }
  32721. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32722. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32723. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32724. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32725. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32726. if ( texData.colorSpace !== undefined ) {
  32727. texture.colorSpace = texData.colorSpace;
  32728. }
  32729. if ( texData.flipY !== undefined ) {
  32730. texture.flipY = texData.flipY;
  32731. }
  32732. if ( texData.format !== undefined ) {
  32733. texture.format = texData.format;
  32734. }
  32735. if ( texData.type !== undefined ) {
  32736. texture.type = texData.type;
  32737. }
  32738. if ( texData.mipmaps !== undefined ) {
  32739. texture.mipmaps = texData.mipmaps;
  32740. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32741. }
  32742. if ( texData.mipmapCount === 1 ) {
  32743. texture.minFilter = LinearFilter;
  32744. }
  32745. if ( texData.generateMipmaps !== undefined ) {
  32746. texture.generateMipmaps = texData.generateMipmaps;
  32747. }
  32748. texture.needsUpdate = true;
  32749. if ( onLoad ) onLoad( texture, texData );
  32750. }, onProgress, onError );
  32751. return texture;
  32752. }
  32753. }
  32754. /**
  32755. * Class for loading textures. Images are internally
  32756. * loaded via {@link ImageLoader}.
  32757. *
  32758. * ```js
  32759. * const loader = new THREE.TextureLoader();
  32760. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32761. *
  32762. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32763. * ```
  32764. * Please note that `TextureLoader` has dropped support for progress
  32765. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32766. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32767. *
  32768. * @augments Loader
  32769. */
  32770. class TextureLoader extends Loader {
  32771. /**
  32772. * Constructs a new texture loader.
  32773. *
  32774. * @param {LoadingManager} [manager] - The loading manager.
  32775. */
  32776. constructor( manager ) {
  32777. super( manager );
  32778. }
  32779. /**
  32780. * Starts loading from the given URL and pass the fully loaded texture
  32781. * to the `onLoad()` callback. The method also returns a new texture object which can
  32782. * directly be used for material creation. If you do it this way, the texture
  32783. * may pop up in your scene once the respective loading process is finished.
  32784. *
  32785. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32786. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32787. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32788. * @param {onErrorCallback} onError - Executed when errors occur.
  32789. * @return {Texture} The texture.
  32790. */
  32791. load( url, onLoad, onProgress, onError ) {
  32792. const texture = new Texture();
  32793. const loader = new ImageLoader( this.manager );
  32794. loader.setCrossOrigin( this.crossOrigin );
  32795. loader.setPath( this.path );
  32796. loader.load( url, function ( image ) {
  32797. texture.image = image;
  32798. texture.needsUpdate = true;
  32799. if ( onLoad !== undefined ) {
  32800. onLoad( texture );
  32801. }
  32802. }, onProgress, onError );
  32803. return texture;
  32804. }
  32805. }
  32806. /**
  32807. * Abstract base class for lights - all other light types inherit the
  32808. * properties and methods described here.
  32809. *
  32810. * @abstract
  32811. * @augments Object3D
  32812. */
  32813. class Light extends Object3D {
  32814. /**
  32815. * Constructs a new light.
  32816. *
  32817. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32818. * @param {number} [intensity=1] - The light's strength/intensity.
  32819. */
  32820. constructor( color, intensity = 1 ) {
  32821. super();
  32822. /**
  32823. * This flag can be used for type testing.
  32824. *
  32825. * @type {boolean}
  32826. * @readonly
  32827. * @default true
  32828. */
  32829. this.isLight = true;
  32830. this.type = 'Light';
  32831. /**
  32832. * The light's color.
  32833. *
  32834. * @type {Color}
  32835. */
  32836. this.color = new Color( color );
  32837. /**
  32838. * The light's intensity.
  32839. *
  32840. * @type {number}
  32841. * @default 1
  32842. */
  32843. this.intensity = intensity;
  32844. }
  32845. /**
  32846. * Frees the GPU-related resources allocated by this instance. Call this
  32847. * method whenever this instance is no longer used in your app.
  32848. */
  32849. dispose() {
  32850. // Empty here in base class; some subclasses override.
  32851. }
  32852. copy( source, recursive ) {
  32853. super.copy( source, recursive );
  32854. this.color.copy( source.color );
  32855. this.intensity = source.intensity;
  32856. return this;
  32857. }
  32858. toJSON( meta ) {
  32859. const data = super.toJSON( meta );
  32860. data.object.color = this.color.getHex();
  32861. data.object.intensity = this.intensity;
  32862. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32863. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32864. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32865. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32866. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32867. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32868. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32869. return data;
  32870. }
  32871. }
  32872. /**
  32873. * A light source positioned directly above the scene, with color fading from
  32874. * the sky color to the ground color.
  32875. *
  32876. * This light cannot be used to cast shadows.
  32877. *
  32878. * ```js
  32879. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32880. * scene.add( light );
  32881. * ```
  32882. *
  32883. * @augments Light
  32884. */
  32885. class HemisphereLight extends Light {
  32886. /**
  32887. * Constructs a new hemisphere light.
  32888. *
  32889. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  32890. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  32891. * @param {number} [intensity=1] - The light's strength/intensity.
  32892. */
  32893. constructor( skyColor, groundColor, intensity ) {
  32894. super( skyColor, intensity );
  32895. /**
  32896. * This flag can be used for type testing.
  32897. *
  32898. * @type {boolean}
  32899. * @readonly
  32900. * @default true
  32901. */
  32902. this.isHemisphereLight = true;
  32903. this.type = 'HemisphereLight';
  32904. this.position.copy( Object3D.DEFAULT_UP );
  32905. this.updateMatrix();
  32906. /**
  32907. * The light's ground color.
  32908. *
  32909. * @type {Color}
  32910. */
  32911. this.groundColor = new Color( groundColor );
  32912. }
  32913. copy( source, recursive ) {
  32914. super.copy( source, recursive );
  32915. this.groundColor.copy( source.groundColor );
  32916. return this;
  32917. }
  32918. }
  32919. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  32920. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  32921. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  32922. /**
  32923. * Abstract base class for light shadow classes. These classes
  32924. * represent the shadow configuration for different light types.
  32925. *
  32926. * @abstract
  32927. */
  32928. class LightShadow {
  32929. /**
  32930. * Constructs a new light shadow.
  32931. *
  32932. * @param {Camera} camera - The light's view of the world.
  32933. */
  32934. constructor( camera ) {
  32935. /**
  32936. * The light's view of the world.
  32937. *
  32938. * @type {Camera}
  32939. */
  32940. this.camera = camera;
  32941. /**
  32942. * The intensity of the shadow. The default is `1`.
  32943. * Valid values are in the range `[0, 1]`.
  32944. *
  32945. * @type {number}
  32946. * @default 1
  32947. */
  32948. this.intensity = 1;
  32949. /**
  32950. * Shadow map bias, how much to add or subtract from the normalized depth
  32951. * when deciding whether a surface is in shadow.
  32952. *
  32953. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  32954. * may help reduce artifacts in shadows.
  32955. *
  32956. * @type {number}
  32957. * @default 0
  32958. */
  32959. this.bias = 0;
  32960. /**
  32961. * Defines how much the position used to query the shadow map is offset along
  32962. * the object normal. The default is `0`. Increasing this value can be used to
  32963. * reduce shadow acne especially in large scenes where light shines onto
  32964. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  32965. *
  32966. * @type {number}
  32967. * @default 0
  32968. */
  32969. this.normalBias = 0;
  32970. /**
  32971. * Setting this to values greater than 1 will blur the edges of the shadow.
  32972. * High values will cause unwanted banding effects in the shadows - a greater
  32973. * map size will allow for a higher value to be used here before these effects
  32974. * become visible.
  32975. *
  32976. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  32977. * and it is recommended to increase softness by decreasing the shadow map size instead.
  32978. *
  32979. * The property has no effect when the shadow map type is `BasicShadowMap`.
  32980. *
  32981. * @type {number}
  32982. * @default 1
  32983. */
  32984. this.radius = 1;
  32985. /**
  32986. * The amount of samples to use when blurring a VSM shadow map.
  32987. *
  32988. * @type {number}
  32989. * @default 8
  32990. */
  32991. this.blurSamples = 8;
  32992. /**
  32993. * Defines the width and height of the shadow map. Higher values give better quality
  32994. * shadows at the cost of computation time. Values must be powers of two.
  32995. *
  32996. * @type {Vector2}
  32997. * @default (512,512)
  32998. */
  32999. this.mapSize = new Vector2( 512, 512 );
  33000. /**
  33001. * The type of shadow texture. The default is `UnsignedByteType`.
  33002. *
  33003. * @type {number}
  33004. * @default UnsignedByteType
  33005. */
  33006. this.mapType = UnsignedByteType;
  33007. /**
  33008. * The depth map generated using the internal camera; a location beyond a
  33009. * pixel's depth is in shadow. Computed internally during rendering.
  33010. *
  33011. * @type {?RenderTarget}
  33012. * @default null
  33013. */
  33014. this.map = null;
  33015. /**
  33016. * The distribution map generated using the internal camera; an occlusion is
  33017. * calculated based on the distribution of depths. Computed internally during
  33018. * rendering.
  33019. *
  33020. * @type {?RenderTarget}
  33021. * @default null
  33022. */
  33023. this.mapPass = null;
  33024. /**
  33025. * Model to shadow camera space, to compute location and depth in shadow map.
  33026. * This is computed internally during rendering.
  33027. *
  33028. * @type {Matrix4}
  33029. */
  33030. this.matrix = new Matrix4();
  33031. /**
  33032. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33033. * lighting / shadows, you may set this to `false`.
  33034. *
  33035. * @type {boolean}
  33036. * @default true
  33037. */
  33038. this.autoUpdate = true;
  33039. /**
  33040. * When set to `true`, shadow maps will be updated in the next `render` call.
  33041. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33042. * set this property to `true` and then make a render call to update the light's shadow.
  33043. *
  33044. * @type {boolean}
  33045. * @default false
  33046. */
  33047. this.needsUpdate = false;
  33048. this._frustum = new Frustum();
  33049. this._frameExtents = new Vector2( 1, 1 );
  33050. this._viewportCount = 1;
  33051. this._viewports = [
  33052. new Vector4( 0, 0, 1, 1 )
  33053. ];
  33054. }
  33055. /**
  33056. * Used internally by the renderer to get the number of viewports that need
  33057. * to be rendered for this shadow.
  33058. *
  33059. * @return {number} The viewport count.
  33060. */
  33061. getViewportCount() {
  33062. return this._viewportCount;
  33063. }
  33064. /**
  33065. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33066. *
  33067. * @return {Frustum} The shadow camera frustum.
  33068. */
  33069. getFrustum() {
  33070. return this._frustum;
  33071. }
  33072. /**
  33073. * Update the matrices for the camera and shadow, used internally by the renderer.
  33074. *
  33075. * @param {Light} light - The light for which the shadow is being rendered.
  33076. */
  33077. updateMatrices( light ) {
  33078. const shadowCamera = this.camera;
  33079. const shadowMatrix = this.matrix;
  33080. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33081. shadowCamera.position.copy( _lightPositionWorld$1 );
  33082. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33083. shadowCamera.lookAt( _lookTarget$1 );
  33084. shadowCamera.updateMatrixWorld();
  33085. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33086. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  33087. shadowMatrix.set(
  33088. 0.5, 0.0, 0.0, 0.5,
  33089. 0.0, 0.5, 0.0, 0.5,
  33090. 0.0, 0.0, 0.5, 0.5,
  33091. 0.0, 0.0, 0.0, 1.0
  33092. );
  33093. shadowMatrix.multiply( _projScreenMatrix$1 );
  33094. }
  33095. /**
  33096. * Returns a viewport definition for the given viewport index.
  33097. *
  33098. * @param {number} viewportIndex - The viewport index.
  33099. * @return {Vector4} The viewport.
  33100. */
  33101. getViewport( viewportIndex ) {
  33102. return this._viewports[ viewportIndex ];
  33103. }
  33104. /**
  33105. * Returns the frame extends.
  33106. *
  33107. * @return {Vector2} The frame extends.
  33108. */
  33109. getFrameExtents() {
  33110. return this._frameExtents;
  33111. }
  33112. /**
  33113. * Frees the GPU-related resources allocated by this instance. Call this
  33114. * method whenever this instance is no longer used in your app.
  33115. */
  33116. dispose() {
  33117. if ( this.map ) {
  33118. this.map.dispose();
  33119. }
  33120. if ( this.mapPass ) {
  33121. this.mapPass.dispose();
  33122. }
  33123. }
  33124. /**
  33125. * Copies the values of the given light shadow instance to this instance.
  33126. *
  33127. * @param {LightShadow} source - The light shadow to copy.
  33128. * @return {LightShadow} A reference to this light shadow instance.
  33129. */
  33130. copy( source ) {
  33131. this.camera = source.camera.clone();
  33132. this.intensity = source.intensity;
  33133. this.bias = source.bias;
  33134. this.radius = source.radius;
  33135. this.autoUpdate = source.autoUpdate;
  33136. this.needsUpdate = source.needsUpdate;
  33137. this.normalBias = source.normalBias;
  33138. this.blurSamples = source.blurSamples;
  33139. this.mapSize.copy( source.mapSize );
  33140. return this;
  33141. }
  33142. /**
  33143. * Returns a new light shadow instance with copied values from this instance.
  33144. *
  33145. * @return {LightShadow} A clone of this instance.
  33146. */
  33147. clone() {
  33148. return new this.constructor().copy( this );
  33149. }
  33150. /**
  33151. * Serializes the light shadow into JSON.
  33152. *
  33153. * @return {Object} A JSON object representing the serialized light shadow.
  33154. * @see {@link ObjectLoader#parse}
  33155. */
  33156. toJSON() {
  33157. const object = {};
  33158. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33159. if ( this.bias !== 0 ) object.bias = this.bias;
  33160. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33161. if ( this.radius !== 1 ) object.radius = this.radius;
  33162. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33163. object.camera = this.camera.toJSON( false ).object;
  33164. delete object.camera.matrix;
  33165. return object;
  33166. }
  33167. }
  33168. /**
  33169. * Represents the shadow configuration of directional lights.
  33170. *
  33171. * @augments LightShadow
  33172. */
  33173. class SpotLightShadow extends LightShadow {
  33174. /**
  33175. * Constructs a new spot light shadow.
  33176. */
  33177. constructor() {
  33178. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33179. /**
  33180. * This flag can be used for type testing.
  33181. *
  33182. * @type {boolean}
  33183. * @readonly
  33184. * @default true
  33185. */
  33186. this.isSpotLightShadow = true;
  33187. /**
  33188. * Used to focus the shadow camera. The camera's field of view is set as a
  33189. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33190. *
  33191. * @type {number}
  33192. * @default 1
  33193. */
  33194. this.focus = 1;
  33195. /**
  33196. * Texture aspect ratio.
  33197. *
  33198. * @type {number}
  33199. * @default 1
  33200. */
  33201. this.aspect = 1;
  33202. }
  33203. updateMatrices( light ) {
  33204. const camera = this.camera;
  33205. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33206. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33207. const far = light.distance || camera.far;
  33208. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33209. camera.fov = fov;
  33210. camera.aspect = aspect;
  33211. camera.far = far;
  33212. camera.updateProjectionMatrix();
  33213. }
  33214. super.updateMatrices( light );
  33215. }
  33216. copy( source ) {
  33217. super.copy( source );
  33218. this.focus = source.focus;
  33219. return this;
  33220. }
  33221. }
  33222. /**
  33223. * This light gets emitted from a single point in one direction, along a cone
  33224. * that increases in size the further from the light it gets.
  33225. *
  33226. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33227. *
  33228. * ```js
  33229. * // white spotlight shining from the side, modulated by a texture
  33230. * const spotLight = new THREE.SpotLight( 0xffffff );
  33231. * spotLight.position.set( 100, 1000, 100 );
  33232. * spotLight.map = new THREE.TextureLoader().load( url );
  33233. *
  33234. * spotLight.castShadow = true;
  33235. * spotLight.shadow.mapSize.width = 1024;
  33236. * spotLight.shadow.mapSize.height = 1024;
  33237. * spotLight.shadow.camera.near = 500;
  33238. * spotLight.shadow.camera.far = 4000;
  33239. * spotLight.shadow.camera.fov = 30;s
  33240. * ```
  33241. *
  33242. * @augments Light
  33243. */
  33244. class SpotLight extends Light {
  33245. /**
  33246. * Constructs a new spot light.
  33247. *
  33248. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33249. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33250. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33251. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33252. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33253. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33254. */
  33255. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33256. super( color, intensity );
  33257. /**
  33258. * This flag can be used for type testing.
  33259. *
  33260. * @type {boolean}
  33261. * @readonly
  33262. * @default true
  33263. */
  33264. this.isSpotLight = true;
  33265. this.type = 'SpotLight';
  33266. this.position.copy( Object3D.DEFAULT_UP );
  33267. this.updateMatrix();
  33268. /**
  33269. * The spot light points from its position to the
  33270. * target's position.
  33271. *
  33272. * For the target's position to be changed to anything other
  33273. * than the default, it must be added to the scene.
  33274. *
  33275. * It is also possible to set the target to be another 3D object
  33276. * in the scene. The light will now track the target object.
  33277. *
  33278. * @type {Object3D}
  33279. */
  33280. this.target = new Object3D();
  33281. /**
  33282. * Maximum range of the light. `0` means no limit.
  33283. *
  33284. * @type {number}
  33285. * @default 0
  33286. */
  33287. this.distance = distance;
  33288. /**
  33289. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33290. *
  33291. * @type {number}
  33292. * @default Math.PI/3
  33293. */
  33294. this.angle = angle;
  33295. /**
  33296. * Percent of the spotlight cone that is attenuated due to penumbra.
  33297. * Value range is `[0,1]`.
  33298. *
  33299. * @type {number}
  33300. * @default 0
  33301. */
  33302. this.penumbra = penumbra;
  33303. /**
  33304. * The amount the light dims along the distance of the light. In context of
  33305. * physically-correct rendering the default value should not be changed.
  33306. *
  33307. * @type {number}
  33308. * @default 2
  33309. */
  33310. this.decay = decay;
  33311. /**
  33312. * A texture used to modulate the color of the light. The spot light
  33313. * color is mixed with the RGB value of this texture, with a ratio
  33314. * corresponding to its alpha value. The cookie-like masking effect is
  33315. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33316. *
  33317. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33318. *
  33319. * @type {?Texture}
  33320. * @default null
  33321. */
  33322. this.map = null;
  33323. /**
  33324. * This property holds the light's shadow configuration.
  33325. *
  33326. * @type {SpotLightShadow}
  33327. */
  33328. this.shadow = new SpotLightShadow();
  33329. }
  33330. /**
  33331. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33332. * Changing the power will also change the light's intensity.
  33333. *
  33334. * @type {number}
  33335. */
  33336. get power() {
  33337. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33338. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33339. return this.intensity * Math.PI;
  33340. }
  33341. set power( power ) {
  33342. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33343. this.intensity = power / Math.PI;
  33344. }
  33345. dispose() {
  33346. this.shadow.dispose();
  33347. }
  33348. copy( source, recursive ) {
  33349. super.copy( source, recursive );
  33350. this.distance = source.distance;
  33351. this.angle = source.angle;
  33352. this.penumbra = source.penumbra;
  33353. this.decay = source.decay;
  33354. this.target = source.target.clone();
  33355. this.shadow = source.shadow.clone();
  33356. return this;
  33357. }
  33358. }
  33359. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33360. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33361. const _lookTarget = /*@__PURE__*/ new Vector3();
  33362. /**
  33363. * Represents the shadow configuration of point lights.
  33364. *
  33365. * @augments LightShadow
  33366. */
  33367. class PointLightShadow extends LightShadow {
  33368. /**
  33369. * Constructs a new point light shadow.
  33370. */
  33371. constructor() {
  33372. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33373. /**
  33374. * This flag can be used for type testing.
  33375. *
  33376. * @type {boolean}
  33377. * @readonly
  33378. * @default true
  33379. */
  33380. this.isPointLightShadow = true;
  33381. this._frameExtents = new Vector2( 4, 2 );
  33382. this._viewportCount = 6;
  33383. this._viewports = [
  33384. // These viewports map a cube-map onto a 2D texture with the
  33385. // following orientation:
  33386. //
  33387. // xzXZ
  33388. // y Y
  33389. //
  33390. // X - Positive x direction
  33391. // x - Negative x direction
  33392. // Y - Positive y direction
  33393. // y - Negative y direction
  33394. // Z - Positive z direction
  33395. // z - Negative z direction
  33396. // positive X
  33397. new Vector4( 2, 1, 1, 1 ),
  33398. // negative X
  33399. new Vector4( 0, 1, 1, 1 ),
  33400. // positive Z
  33401. new Vector4( 3, 1, 1, 1 ),
  33402. // negative Z
  33403. new Vector4( 1, 1, 1, 1 ),
  33404. // positive Y
  33405. new Vector4( 3, 0, 1, 1 ),
  33406. // negative Y
  33407. new Vector4( 1, 0, 1, 1 )
  33408. ];
  33409. this._cubeDirections = [
  33410. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33411. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33412. ];
  33413. this._cubeUps = [
  33414. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33415. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33416. ];
  33417. }
  33418. /**
  33419. * Update the matrices for the camera and shadow, used internally by the renderer.
  33420. *
  33421. * @param {Light} light - The light for which the shadow is being rendered.
  33422. * @param {number} [viewportIndex=0] - The viewport index.
  33423. */
  33424. updateMatrices( light, viewportIndex = 0 ) {
  33425. const camera = this.camera;
  33426. const shadowMatrix = this.matrix;
  33427. const far = light.distance || camera.far;
  33428. if ( far !== camera.far ) {
  33429. camera.far = far;
  33430. camera.updateProjectionMatrix();
  33431. }
  33432. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33433. camera.position.copy( _lightPositionWorld );
  33434. _lookTarget.copy( camera.position );
  33435. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33436. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33437. camera.lookAt( _lookTarget );
  33438. camera.updateMatrixWorld();
  33439. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33440. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33441. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  33442. }
  33443. }
  33444. /**
  33445. * A light that gets emitted from a single point in all directions. A common
  33446. * use case for this is to replicate the light emitted from a bare
  33447. * lightbulb.
  33448. *
  33449. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33450. *
  33451. * ```js
  33452. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33453. * light.position.set( 50, 50, 50 );
  33454. * scene.add( light );
  33455. * ```
  33456. *
  33457. * @augments Light
  33458. */
  33459. class PointLight extends Light {
  33460. /**
  33461. * Constructs a new point light.
  33462. *
  33463. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33464. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33465. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33466. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33467. */
  33468. constructor( color, intensity, distance = 0, decay = 2 ) {
  33469. super( color, intensity );
  33470. /**
  33471. * This flag can be used for type testing.
  33472. *
  33473. * @type {boolean}
  33474. * @readonly
  33475. * @default true
  33476. */
  33477. this.isPointLight = true;
  33478. this.type = 'PointLight';
  33479. /**
  33480. * When distance is zero, light will attenuate according to inverse-square
  33481. * law to infinite distance. When distance is non-zero, light will attenuate
  33482. * according to inverse-square law until near the distance cutoff, where it
  33483. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33484. * physically correct.
  33485. *
  33486. * @type {number}
  33487. * @default 0
  33488. */
  33489. this.distance = distance;
  33490. /**
  33491. * The amount the light dims along the distance of the light. In context of
  33492. * physically-correct rendering the default value should not be changed.
  33493. *
  33494. * @type {number}
  33495. * @default 2
  33496. */
  33497. this.decay = decay;
  33498. /**
  33499. * This property holds the light's shadow configuration.
  33500. *
  33501. * @type {PointLightShadow}
  33502. */
  33503. this.shadow = new PointLightShadow();
  33504. }
  33505. /**
  33506. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33507. * Changing the power will also change the light's intensity.
  33508. *
  33509. * @type {number}
  33510. */
  33511. get power() {
  33512. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33513. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33514. return this.intensity * 4 * Math.PI;
  33515. }
  33516. set power( power ) {
  33517. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33518. this.intensity = power / ( 4 * Math.PI );
  33519. }
  33520. dispose() {
  33521. this.shadow.dispose();
  33522. }
  33523. copy( source, recursive ) {
  33524. super.copy( source, recursive );
  33525. this.distance = source.distance;
  33526. this.decay = source.decay;
  33527. this.shadow = source.shadow.clone();
  33528. return this;
  33529. }
  33530. }
  33531. /**
  33532. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33533. *
  33534. * In this projection mode, an object's size in the rendered image stays
  33535. * constant regardless of its distance from the camera. This can be useful
  33536. * for rendering 2D scenes and UI elements, amongst other things.
  33537. *
  33538. * ```js
  33539. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33540. * scene.add( camera );
  33541. * ```
  33542. *
  33543. * @augments Camera
  33544. */
  33545. class OrthographicCamera extends Camera {
  33546. /**
  33547. * Constructs a new orthographic camera.
  33548. *
  33549. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33550. * @param {number} [right=1] - The right plane of the camera's frustum.
  33551. * @param {number} [top=1] - The top plane of the camera's frustum.
  33552. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33553. * @param {number} [near=0.1] - The camera's near plane.
  33554. * @param {number} [far=2000] - The camera's far plane.
  33555. */
  33556. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33557. super();
  33558. /**
  33559. * This flag can be used for type testing.
  33560. *
  33561. * @type {boolean}
  33562. * @readonly
  33563. * @default true
  33564. */
  33565. this.isOrthographicCamera = true;
  33566. this.type = 'OrthographicCamera';
  33567. /**
  33568. * The zoom factor of the camera.
  33569. *
  33570. * @type {number}
  33571. * @default 1
  33572. */
  33573. this.zoom = 1;
  33574. /**
  33575. * Represents the frustum window specification. This property should not be edited
  33576. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33577. *
  33578. * @type {?Object}
  33579. * @default null
  33580. */
  33581. this.view = null;
  33582. /**
  33583. * The left plane of the camera's frustum.
  33584. *
  33585. * @type {number}
  33586. * @default -1
  33587. */
  33588. this.left = left;
  33589. /**
  33590. * The right plane of the camera's frustum.
  33591. *
  33592. * @type {number}
  33593. * @default 1
  33594. */
  33595. this.right = right;
  33596. /**
  33597. * The top plane of the camera's frustum.
  33598. *
  33599. * @type {number}
  33600. * @default 1
  33601. */
  33602. this.top = top;
  33603. /**
  33604. * The bottom plane of the camera's frustum.
  33605. *
  33606. * @type {number}
  33607. * @default -1
  33608. */
  33609. this.bottom = bottom;
  33610. /**
  33611. * The camera's near plane. The valid range is greater than `0`
  33612. * and less than the current value of {@link OrthographicCamera#far}.
  33613. *
  33614. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33615. * valid value for an orthographic camera's near plane.
  33616. *
  33617. * @type {number}
  33618. * @default 0.1
  33619. */
  33620. this.near = near;
  33621. /**
  33622. * The camera's far plane. Must be greater than the
  33623. * current value of {@link OrthographicCamera#near}.
  33624. *
  33625. * @type {number}
  33626. * @default 2000
  33627. */
  33628. this.far = far;
  33629. this.updateProjectionMatrix();
  33630. }
  33631. copy( source, recursive ) {
  33632. super.copy( source, recursive );
  33633. this.left = source.left;
  33634. this.right = source.right;
  33635. this.top = source.top;
  33636. this.bottom = source.bottom;
  33637. this.near = source.near;
  33638. this.far = source.far;
  33639. this.zoom = source.zoom;
  33640. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33641. return this;
  33642. }
  33643. /**
  33644. * Sets an offset in a larger frustum. This is useful for multi-window or
  33645. * multi-monitor/multi-machine setups.
  33646. *
  33647. * @param {number} fullWidth - The full width of multiview setup.
  33648. * @param {number} fullHeight - The full height of multiview setup.
  33649. * @param {number} x - The horizontal offset of the subcamera.
  33650. * @param {number} y - The vertical offset of the subcamera.
  33651. * @param {number} width - The width of subcamera.
  33652. * @param {number} height - The height of subcamera.
  33653. * @see {@link PerspectiveCamera#setViewOffset}
  33654. */
  33655. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33656. if ( this.view === null ) {
  33657. this.view = {
  33658. enabled: true,
  33659. fullWidth: 1,
  33660. fullHeight: 1,
  33661. offsetX: 0,
  33662. offsetY: 0,
  33663. width: 1,
  33664. height: 1
  33665. };
  33666. }
  33667. this.view.enabled = true;
  33668. this.view.fullWidth = fullWidth;
  33669. this.view.fullHeight = fullHeight;
  33670. this.view.offsetX = x;
  33671. this.view.offsetY = y;
  33672. this.view.width = width;
  33673. this.view.height = height;
  33674. this.updateProjectionMatrix();
  33675. }
  33676. /**
  33677. * Removes the view offset from the projection matrix.
  33678. */
  33679. clearViewOffset() {
  33680. if ( this.view !== null ) {
  33681. this.view.enabled = false;
  33682. }
  33683. this.updateProjectionMatrix();
  33684. }
  33685. /**
  33686. * Updates the camera's projection matrix. Must be called after any change of
  33687. * camera properties.
  33688. */
  33689. updateProjectionMatrix() {
  33690. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33691. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33692. const cx = ( this.right + this.left ) / 2;
  33693. const cy = ( this.top + this.bottom ) / 2;
  33694. let left = cx - dx;
  33695. let right = cx + dx;
  33696. let top = cy + dy;
  33697. let bottom = cy - dy;
  33698. if ( this.view !== null && this.view.enabled ) {
  33699. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33700. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33701. left += scaleW * this.view.offsetX;
  33702. right = left + scaleW * this.view.width;
  33703. top -= scaleH * this.view.offsetY;
  33704. bottom = top - scaleH * this.view.height;
  33705. }
  33706. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33707. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33708. }
  33709. toJSON( meta ) {
  33710. const data = super.toJSON( meta );
  33711. data.object.zoom = this.zoom;
  33712. data.object.left = this.left;
  33713. data.object.right = this.right;
  33714. data.object.top = this.top;
  33715. data.object.bottom = this.bottom;
  33716. data.object.near = this.near;
  33717. data.object.far = this.far;
  33718. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33719. return data;
  33720. }
  33721. }
  33722. /**
  33723. * Represents the shadow configuration of directional lights.
  33724. *
  33725. * @augments LightShadow
  33726. */
  33727. class DirectionalLightShadow extends LightShadow {
  33728. /**
  33729. * Constructs a new directional light shadow.
  33730. */
  33731. constructor() {
  33732. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33733. /**
  33734. * This flag can be used for type testing.
  33735. *
  33736. * @type {boolean}
  33737. * @readonly
  33738. * @default true
  33739. */
  33740. this.isDirectionalLightShadow = true;
  33741. }
  33742. }
  33743. /**
  33744. * A light that gets emitted in a specific direction. This light will behave
  33745. * as though it is infinitely far away and the rays produced from it are all
  33746. * parallel. The common use case for this is to simulate daylight; the sun is
  33747. * far enough away that its position can be considered to be infinite, and
  33748. * all light rays coming from it are parallel.
  33749. *
  33750. * A common point of confusion for directional lights is that setting the
  33751. * rotation has no effect. This is because three.js's DirectionalLight is the
  33752. * equivalent to what is often called a 'Target Direct Light' in other
  33753. * applications.
  33754. *
  33755. * This means that its direction is calculated as pointing from the light's
  33756. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33757. * (as opposed to a 'Free Direct Light' that just has a rotation
  33758. * component).
  33759. *
  33760. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33761. *
  33762. * ```js
  33763. * // White directional light at half intensity shining from the top.
  33764. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33765. * scene.add( directionalLight );
  33766. * ```
  33767. *
  33768. * @augments Light
  33769. */
  33770. class DirectionalLight extends Light {
  33771. /**
  33772. * Constructs a new directional light.
  33773. *
  33774. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33775. * @param {number} [intensity=1] - The light's strength/intensity.
  33776. */
  33777. constructor( color, intensity ) {
  33778. super( color, intensity );
  33779. /**
  33780. * This flag can be used for type testing.
  33781. *
  33782. * @type {boolean}
  33783. * @readonly
  33784. * @default true
  33785. */
  33786. this.isDirectionalLight = true;
  33787. this.type = 'DirectionalLight';
  33788. this.position.copy( Object3D.DEFAULT_UP );
  33789. this.updateMatrix();
  33790. /**
  33791. * The directional light points from its position to the
  33792. * target's position.
  33793. *
  33794. * For the target's position to be changed to anything other
  33795. * than the default, it must be added to the scene.
  33796. *
  33797. * It is also possible to set the target to be another 3D object
  33798. * in the scene. The light will now track the target object.
  33799. *
  33800. * @type {Object3D}
  33801. */
  33802. this.target = new Object3D();
  33803. /**
  33804. * This property holds the light's shadow configuration.
  33805. *
  33806. * @type {DirectionalLightShadow}
  33807. */
  33808. this.shadow = new DirectionalLightShadow();
  33809. }
  33810. dispose() {
  33811. this.shadow.dispose();
  33812. }
  33813. copy( source ) {
  33814. super.copy( source );
  33815. this.target = source.target.clone();
  33816. this.shadow = source.shadow.clone();
  33817. return this;
  33818. }
  33819. }
  33820. /**
  33821. * This light globally illuminates all objects in the scene equally.
  33822. *
  33823. * It cannot be used to cast shadows as it does not have a direction.
  33824. *
  33825. * ```js
  33826. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33827. * scene.add( light );
  33828. * ```
  33829. *
  33830. * @augments Light
  33831. */
  33832. class AmbientLight extends Light {
  33833. /**
  33834. * Constructs a new ambient light.
  33835. *
  33836. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33837. * @param {number} [intensity=1] - The light's strength/intensity.
  33838. */
  33839. constructor( color, intensity ) {
  33840. super( color, intensity );
  33841. /**
  33842. * This flag can be used for type testing.
  33843. *
  33844. * @type {boolean}
  33845. * @readonly
  33846. * @default true
  33847. */
  33848. this.isAmbientLight = true;
  33849. this.type = 'AmbientLight';
  33850. }
  33851. }
  33852. /**
  33853. * This class emits light uniformly across the face a rectangular plane.
  33854. * This light type can be used to simulate light sources such as bright
  33855. * windows or strip lighting.
  33856. *
  33857. * Important Notes:
  33858. *
  33859. * - There is no shadow support.
  33860. * - Only PBR materials are supported.
  33861. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33862. * into your app and init the uniforms/textures.
  33863. *
  33864. * ```js
  33865. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33866. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33867. *
  33868. * const intensity = 1; const width = 10; const height = 10;
  33869. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33870. * rectLight.position.set( 5, 5, 0 );
  33871. * rectLight.lookAt( 0, 0, 0 );
  33872. * scene.add( rectLight )
  33873. * ```
  33874. *
  33875. * @augments Light
  33876. */
  33877. class RectAreaLight extends Light {
  33878. /**
  33879. * Constructs a new area light.
  33880. *
  33881. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33882. * @param {number} [intensity=1] - The light's strength/intensity.
  33883. * @param {number} [width=10] - The width of the light.
  33884. * @param {number} [height=10] - The height of the light.
  33885. */
  33886. constructor( color, intensity, width = 10, height = 10 ) {
  33887. super( color, intensity );
  33888. /**
  33889. * This flag can be used for type testing.
  33890. *
  33891. * @type {boolean}
  33892. * @readonly
  33893. * @default true
  33894. */
  33895. this.isRectAreaLight = true;
  33896. this.type = 'RectAreaLight';
  33897. /**
  33898. * The width of the light.
  33899. *
  33900. * @type {number}
  33901. * @default 10
  33902. */
  33903. this.width = width;
  33904. /**
  33905. * The height of the light.
  33906. *
  33907. * @type {number}
  33908. * @default 10
  33909. */
  33910. this.height = height;
  33911. }
  33912. /**
  33913. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33914. * Changing the power will also change the light's intensity.
  33915. *
  33916. * @type {number}
  33917. */
  33918. get power() {
  33919. // compute the light's luminous power (in lumens) from its intensity (in nits)
  33920. return this.intensity * this.width * this.height * Math.PI;
  33921. }
  33922. set power( power ) {
  33923. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  33924. this.intensity = power / ( this.width * this.height * Math.PI );
  33925. }
  33926. copy( source ) {
  33927. super.copy( source );
  33928. this.width = source.width;
  33929. this.height = source.height;
  33930. return this;
  33931. }
  33932. toJSON( meta ) {
  33933. const data = super.toJSON( meta );
  33934. data.object.width = this.width;
  33935. data.object.height = this.height;
  33936. return data;
  33937. }
  33938. }
  33939. /**
  33940. * Represents a third-order spherical harmonics (SH). Light probes use this class
  33941. * to encode lighting information.
  33942. *
  33943. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  33944. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  33945. */
  33946. class SphericalHarmonics3 {
  33947. /**
  33948. * Constructs a new spherical harmonics.
  33949. */
  33950. constructor() {
  33951. /**
  33952. * This flag can be used for type testing.
  33953. *
  33954. * @type {boolean}
  33955. * @readonly
  33956. * @default true
  33957. */
  33958. this.isSphericalHarmonics3 = true;
  33959. /**
  33960. * An array holding the (9) SH coefficients.
  33961. *
  33962. * @type {Array<Vector3>}
  33963. */
  33964. this.coefficients = [];
  33965. for ( let i = 0; i < 9; i ++ ) {
  33966. this.coefficients.push( new Vector3() );
  33967. }
  33968. }
  33969. /**
  33970. * Sets the given SH coefficients to this instance by copying
  33971. * the values.
  33972. *
  33973. * @param {Array<Vector3>} coefficients - The SH coefficients.
  33974. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33975. */
  33976. set( coefficients ) {
  33977. for ( let i = 0; i < 9; i ++ ) {
  33978. this.coefficients[ i ].copy( coefficients[ i ] );
  33979. }
  33980. return this;
  33981. }
  33982. /**
  33983. * Sets all SH coefficients to `0`.
  33984. *
  33985. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  33986. */
  33987. zero() {
  33988. for ( let i = 0; i < 9; i ++ ) {
  33989. this.coefficients[ i ].set( 0, 0, 0 );
  33990. }
  33991. return this;
  33992. }
  33993. /**
  33994. * Returns the radiance in the direction of the given normal.
  33995. *
  33996. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  33997. * @param {Vector3} target - The target vector that is used to store the method's result.
  33998. * @return {Vector3} The radiance.
  33999. */
  34000. getAt( normal, target ) {
  34001. // normal is assumed to be unit length
  34002. const x = normal.x, y = normal.y, z = normal.z;
  34003. const coeff = this.coefficients;
  34004. // band 0
  34005. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34006. // band 1
  34007. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34008. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34009. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34010. // band 2
  34011. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34012. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34013. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34014. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34015. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34016. return target;
  34017. }
  34018. /**
  34019. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34020. * direction of the given normal.
  34021. *
  34022. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34023. * @param {Vector3} target - The target vector that is used to store the method's result.
  34024. * @return {Vector3} The irradiance.
  34025. */
  34026. getIrradianceAt( normal, target ) {
  34027. // normal is assumed to be unit length
  34028. const x = normal.x, y = normal.y, z = normal.z;
  34029. const coeff = this.coefficients;
  34030. // band 0
  34031. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34032. // band 1
  34033. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34034. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34035. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34036. // band 2
  34037. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34038. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34039. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34040. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34041. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34042. return target;
  34043. }
  34044. /**
  34045. * Adds the given SH to this instance.
  34046. *
  34047. * @param {SphericalHarmonics3} sh - The SH to add.
  34048. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34049. */
  34050. add( sh ) {
  34051. for ( let i = 0; i < 9; i ++ ) {
  34052. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34053. }
  34054. return this;
  34055. }
  34056. /**
  34057. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34058. * {@link SphericalHarmonics3#scale} at once.
  34059. *
  34060. * @param {SphericalHarmonics3} sh - The SH to add.
  34061. * @param {number} s - The scale factor.
  34062. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34063. */
  34064. addScaledSH( sh, s ) {
  34065. for ( let i = 0; i < 9; i ++ ) {
  34066. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34067. }
  34068. return this;
  34069. }
  34070. /**
  34071. * Scales this SH by the given scale factor.
  34072. *
  34073. * @param {number} s - The scale factor.
  34074. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34075. */
  34076. scale( s ) {
  34077. for ( let i = 0; i < 9; i ++ ) {
  34078. this.coefficients[ i ].multiplyScalar( s );
  34079. }
  34080. return this;
  34081. }
  34082. /**
  34083. * Linear interpolates between the given SH and this instance by the given
  34084. * alpha factor.
  34085. *
  34086. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34087. * @param {number} alpha - The alpha factor.
  34088. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34089. */
  34090. lerp( sh, alpha ) {
  34091. for ( let i = 0; i < 9; i ++ ) {
  34092. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34093. }
  34094. return this;
  34095. }
  34096. /**
  34097. * Returns `true` if this spherical harmonics is equal with the given one.
  34098. *
  34099. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34100. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34101. */
  34102. equals( sh ) {
  34103. for ( let i = 0; i < 9; i ++ ) {
  34104. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34105. return false;
  34106. }
  34107. }
  34108. return true;
  34109. }
  34110. /**
  34111. * Copies the values of the given spherical harmonics to this instance.
  34112. *
  34113. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34114. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34115. */
  34116. copy( sh ) {
  34117. return this.set( sh.coefficients );
  34118. }
  34119. /**
  34120. * Returns a new spherical harmonics with copied values from this instance.
  34121. *
  34122. * @return {SphericalHarmonics3} A clone of this instance.
  34123. */
  34124. clone() {
  34125. return new this.constructor().copy( this );
  34126. }
  34127. /**
  34128. * Sets the SH coefficients of this instance from the given array.
  34129. *
  34130. * @param {Array<number>} array - An array holding the SH coefficients.
  34131. * @param {number} [offset=0] - The array offset where to start copying.
  34132. * @return {SphericalHarmonics3} A clone of this instance.
  34133. */
  34134. fromArray( array, offset = 0 ) {
  34135. const coefficients = this.coefficients;
  34136. for ( let i = 0; i < 9; i ++ ) {
  34137. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34138. }
  34139. return this;
  34140. }
  34141. /**
  34142. * Returns an array with the SH coefficients, or copies them into the provided
  34143. * array. The coefficients are represented as numbers.
  34144. *
  34145. * @param {Array<number>} [array=[]] - The target array.
  34146. * @param {number} [offset=0] - The array offset where to start copying.
  34147. * @return {Array<number>} An array with flat SH coefficients.
  34148. */
  34149. toArray( array = [], offset = 0 ) {
  34150. const coefficients = this.coefficients;
  34151. for ( let i = 0; i < 9; i ++ ) {
  34152. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34153. }
  34154. return array;
  34155. }
  34156. /**
  34157. * Computes the SH basis for the given normal vector.
  34158. *
  34159. * @param {Vector3} normal - The normal.
  34160. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34161. */
  34162. static getBasisAt( normal, shBasis ) {
  34163. // normal is assumed to be unit length
  34164. const x = normal.x, y = normal.y, z = normal.z;
  34165. // band 0
  34166. shBasis[ 0 ] = 0.282095;
  34167. // band 1
  34168. shBasis[ 1 ] = 0.488603 * y;
  34169. shBasis[ 2 ] = 0.488603 * z;
  34170. shBasis[ 3 ] = 0.488603 * x;
  34171. // band 2
  34172. shBasis[ 4 ] = 1.092548 * x * y;
  34173. shBasis[ 5 ] = 1.092548 * y * z;
  34174. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34175. shBasis[ 7 ] = 1.092548 * x * z;
  34176. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34177. }
  34178. }
  34179. /**
  34180. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34181. * classical light sources (e.g. directional, point or spot lights), light
  34182. * probes do not emit light. Instead they store information about light
  34183. * passing through 3D space. During rendering, the light that hits a 3D
  34184. * object is approximated by using the data from the light probe.
  34185. *
  34186. * Light probes are usually created from (radiance) environment maps. The
  34187. * class {@link LightProbeGenerator} can be used to create light probes from
  34188. * cube textures or render targets. However, light estimation data could also
  34189. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34190. * augmented reality content that reacts to real world lighting.
  34191. *
  34192. * The current probe implementation in three.js supports so-called diffuse
  34193. * light probes. This type of light probe is functionally equivalent to an
  34194. * irradiance environment map.
  34195. *
  34196. * @augments Light
  34197. */
  34198. class LightProbe extends Light {
  34199. /**
  34200. * Constructs a new light probe.
  34201. *
  34202. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34203. * @param {number} [intensity=1] - The light's strength/intensity.
  34204. */
  34205. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34206. super( undefined, intensity );
  34207. /**
  34208. * This flag can be used for type testing.
  34209. *
  34210. * @type {boolean}
  34211. * @readonly
  34212. * @default true
  34213. */
  34214. this.isLightProbe = true;
  34215. /**
  34216. * A light probe uses spherical harmonics to encode lighting information.
  34217. *
  34218. * @type {SphericalHarmonics3}
  34219. */
  34220. this.sh = sh;
  34221. }
  34222. copy( source ) {
  34223. super.copy( source );
  34224. this.sh.copy( source.sh );
  34225. return this;
  34226. }
  34227. /**
  34228. * Deserializes the light prove from the given JSON.
  34229. *
  34230. * @param {Object} json - The JSON holding the serialized light probe.
  34231. * @return {LightProbe} A reference to this light probe.
  34232. */
  34233. fromJSON( json ) {
  34234. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34235. this.sh.fromArray( json.sh );
  34236. return this;
  34237. }
  34238. toJSON( meta ) {
  34239. const data = super.toJSON( meta );
  34240. data.object.sh = this.sh.toArray();
  34241. return data;
  34242. }
  34243. }
  34244. /**
  34245. * Class for loading geometries. The files are internally
  34246. * loaded via {@link FileLoader}.
  34247. *
  34248. * ```js
  34249. * const loader = new THREE.MaterialLoader();
  34250. * const material = await loader.loadAsync( 'material.json' );
  34251. * ```
  34252. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34253. *
  34254. * @augments Loader
  34255. */
  34256. class MaterialLoader extends Loader {
  34257. /**
  34258. * Constructs a new material loader.
  34259. *
  34260. * @param {LoadingManager} [manager] - The loading manager.
  34261. */
  34262. constructor( manager ) {
  34263. super( manager );
  34264. /**
  34265. * A dictionary holding textures used by the material.
  34266. *
  34267. * @type {Object<string,Texture>}
  34268. */
  34269. this.textures = {};
  34270. }
  34271. /**
  34272. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34273. *
  34274. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34275. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34276. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34277. * @param {onErrorCallback} onError - Executed when errors occur.
  34278. */
  34279. load( url, onLoad, onProgress, onError ) {
  34280. const scope = this;
  34281. const loader = new FileLoader( scope.manager );
  34282. loader.setPath( scope.path );
  34283. loader.setRequestHeader( scope.requestHeader );
  34284. loader.setWithCredentials( scope.withCredentials );
  34285. loader.load( url, function ( text ) {
  34286. try {
  34287. onLoad( scope.parse( JSON.parse( text ) ) );
  34288. } catch ( e ) {
  34289. if ( onError ) {
  34290. onError( e );
  34291. } else {
  34292. console.error( e );
  34293. }
  34294. scope.manager.itemError( url );
  34295. }
  34296. }, onProgress, onError );
  34297. }
  34298. /**
  34299. * Parses the given JSON object and returns a material.
  34300. *
  34301. * @param {Object} json - The serialized material.
  34302. * @return {Material} The parsed material.
  34303. */
  34304. parse( json ) {
  34305. const textures = this.textures;
  34306. function getTexture( name ) {
  34307. if ( textures[ name ] === undefined ) {
  34308. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  34309. }
  34310. return textures[ name ];
  34311. }
  34312. const material = this.createMaterialFromType( json.type );
  34313. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34314. if ( json.name !== undefined ) material.name = json.name;
  34315. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34316. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34317. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34318. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34319. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34320. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34321. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34322. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34323. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34324. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34325. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34326. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34327. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34328. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34329. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34330. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34331. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34332. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34333. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34334. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34335. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34336. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34337. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34338. if ( json.fog !== undefined ) material.fog = json.fog;
  34339. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34340. if ( json.blending !== undefined ) material.blending = json.blending;
  34341. if ( json.combine !== undefined ) material.combine = json.combine;
  34342. if ( json.side !== undefined ) material.side = json.side;
  34343. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34344. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34345. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34346. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34347. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34348. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34349. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34350. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34351. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34352. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34353. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34354. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34355. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34356. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34357. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34358. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34359. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34360. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34361. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34362. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34363. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34364. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34365. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34366. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34367. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34368. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34369. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34370. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34371. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34372. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34373. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34374. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34375. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34376. if ( json.scale !== undefined ) material.scale = json.scale;
  34377. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34378. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34379. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34380. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34381. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34382. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34383. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34384. if ( json.visible !== undefined ) material.visible = json.visible;
  34385. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34386. if ( json.userData !== undefined ) material.userData = json.userData;
  34387. if ( json.vertexColors !== undefined ) {
  34388. if ( typeof json.vertexColors === 'number' ) {
  34389. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34390. } else {
  34391. material.vertexColors = json.vertexColors;
  34392. }
  34393. }
  34394. // Shader Material
  34395. if ( json.uniforms !== undefined ) {
  34396. for ( const name in json.uniforms ) {
  34397. const uniform = json.uniforms[ name ];
  34398. material.uniforms[ name ] = {};
  34399. switch ( uniform.type ) {
  34400. case 't':
  34401. material.uniforms[ name ].value = getTexture( uniform.value );
  34402. break;
  34403. case 'c':
  34404. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34405. break;
  34406. case 'v2':
  34407. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34408. break;
  34409. case 'v3':
  34410. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34411. break;
  34412. case 'v4':
  34413. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34414. break;
  34415. case 'm3':
  34416. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34417. break;
  34418. case 'm4':
  34419. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34420. break;
  34421. default:
  34422. material.uniforms[ name ].value = uniform.value;
  34423. }
  34424. }
  34425. }
  34426. if ( json.defines !== undefined ) material.defines = json.defines;
  34427. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34428. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34429. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34430. if ( json.extensions !== undefined ) {
  34431. for ( const key in json.extensions ) {
  34432. material.extensions[ key ] = json.extensions[ key ];
  34433. }
  34434. }
  34435. if ( json.lights !== undefined ) material.lights = json.lights;
  34436. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34437. // for PointsMaterial
  34438. if ( json.size !== undefined ) material.size = json.size;
  34439. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34440. // maps
  34441. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34442. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34443. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34444. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34445. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34446. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34447. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34448. if ( json.normalScale !== undefined ) {
  34449. let normalScale = json.normalScale;
  34450. if ( Array.isArray( normalScale ) === false ) {
  34451. // Blender exporter used to export a scalar. See #7459
  34452. normalScale = [ normalScale, normalScale ];
  34453. }
  34454. material.normalScale = new Vector2().fromArray( normalScale );
  34455. }
  34456. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34457. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34458. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34459. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34460. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34461. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34462. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34463. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34464. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34465. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34466. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34467. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34468. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34469. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34470. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34471. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34472. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34473. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34474. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34475. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34476. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34477. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34478. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34479. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34480. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34481. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34482. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34483. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34484. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34485. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34486. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34487. return material;
  34488. }
  34489. /**
  34490. * Textures are not embedded in the material JSON so they have
  34491. * to be injected before the loading process starts.
  34492. *
  34493. * @param {Object} value - A dictionary holding textures for material properties.
  34494. * @return {MaterialLoader} A reference to this material loader.
  34495. */
  34496. setTextures( value ) {
  34497. this.textures = value;
  34498. return this;
  34499. }
  34500. /**
  34501. * Creates a material for the given type.
  34502. *
  34503. * @param {string} type - The material type.
  34504. * @return {Material} The new material.
  34505. */
  34506. createMaterialFromType( type ) {
  34507. return MaterialLoader.createMaterialFromType( type );
  34508. }
  34509. /**
  34510. * Creates a material for the given type.
  34511. *
  34512. * @static
  34513. * @param {string} type - The material type.
  34514. * @return {Material} The new material.
  34515. */
  34516. static createMaterialFromType( type ) {
  34517. const materialLib = {
  34518. ShadowMaterial,
  34519. SpriteMaterial,
  34520. RawShaderMaterial,
  34521. ShaderMaterial,
  34522. PointsMaterial,
  34523. MeshPhysicalMaterial,
  34524. MeshStandardMaterial,
  34525. MeshPhongMaterial,
  34526. MeshToonMaterial,
  34527. MeshNormalMaterial,
  34528. MeshLambertMaterial,
  34529. MeshDepthMaterial,
  34530. MeshDistanceMaterial,
  34531. MeshBasicMaterial,
  34532. MeshMatcapMaterial,
  34533. LineDashedMaterial,
  34534. LineBasicMaterial,
  34535. Material
  34536. };
  34537. return new materialLib[ type ]();
  34538. }
  34539. }
  34540. /**
  34541. * A class with loader utility functions.
  34542. */
  34543. class LoaderUtils {
  34544. /**
  34545. * Extracts the base URL from the given URL.
  34546. *
  34547. * @param {string} url -The URL to extract the base URL from.
  34548. * @return {string} The extracted base URL.
  34549. */
  34550. static extractUrlBase( url ) {
  34551. const index = url.lastIndexOf( '/' );
  34552. if ( index === -1 ) return './';
  34553. return url.slice( 0, index + 1 );
  34554. }
  34555. /**
  34556. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34557. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34558. * string.
  34559. *
  34560. * @param {string} url -The URL to resolve.
  34561. * @param {string} path - The base path for relative URLs to be resolved against.
  34562. * @return {string} The resolved URL.
  34563. */
  34564. static resolveURL( url, path ) {
  34565. // Invalid URL
  34566. if ( typeof url !== 'string' || url === '' ) return '';
  34567. // Host Relative URL
  34568. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34569. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34570. }
  34571. // Absolute URL http://,https://,//
  34572. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34573. // Data URI
  34574. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34575. // Blob URL
  34576. if ( /^blob:.*$/i.test( url ) ) return url;
  34577. // Relative URL
  34578. return path + url;
  34579. }
  34580. }
  34581. /**
  34582. * An instanced version of a geometry.
  34583. */
  34584. class InstancedBufferGeometry extends BufferGeometry {
  34585. /**
  34586. * Constructs a new instanced buffer geometry.
  34587. */
  34588. constructor() {
  34589. super();
  34590. /**
  34591. * This flag can be used for type testing.
  34592. *
  34593. * @type {boolean}
  34594. * @readonly
  34595. * @default true
  34596. */
  34597. this.isInstancedBufferGeometry = true;
  34598. this.type = 'InstancedBufferGeometry';
  34599. /**
  34600. * The instance count.
  34601. *
  34602. * @type {number}
  34603. * @default Infinity
  34604. */
  34605. this.instanceCount = Infinity;
  34606. }
  34607. copy( source ) {
  34608. super.copy( source );
  34609. this.instanceCount = source.instanceCount;
  34610. return this;
  34611. }
  34612. toJSON() {
  34613. const data = super.toJSON();
  34614. data.instanceCount = this.instanceCount;
  34615. data.isInstancedBufferGeometry = true;
  34616. return data;
  34617. }
  34618. }
  34619. /**
  34620. * Class for loading geometries. The files are internally
  34621. * loaded via {@link FileLoader}.
  34622. *
  34623. * ```js
  34624. * const loader = new THREE.BufferGeometryLoader();
  34625. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34626. *
  34627. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34628. * const object = new THREE.Mesh( geometry, material );
  34629. * scene.add( object );
  34630. * ```
  34631. *
  34632. * @augments Loader
  34633. */
  34634. class BufferGeometryLoader extends Loader {
  34635. /**
  34636. * Constructs a new geometry loader.
  34637. *
  34638. * @param {LoadingManager} [manager] - The loading manager.
  34639. */
  34640. constructor( manager ) {
  34641. super( manager );
  34642. }
  34643. /**
  34644. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34645. *
  34646. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34647. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34648. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34649. * @param {onErrorCallback} onError - Executed when errors occur.
  34650. */
  34651. load( url, onLoad, onProgress, onError ) {
  34652. const scope = this;
  34653. const loader = new FileLoader( scope.manager );
  34654. loader.setPath( scope.path );
  34655. loader.setRequestHeader( scope.requestHeader );
  34656. loader.setWithCredentials( scope.withCredentials );
  34657. loader.load( url, function ( text ) {
  34658. try {
  34659. onLoad( scope.parse( JSON.parse( text ) ) );
  34660. } catch ( e ) {
  34661. if ( onError ) {
  34662. onError( e );
  34663. } else {
  34664. console.error( e );
  34665. }
  34666. scope.manager.itemError( url );
  34667. }
  34668. }, onProgress, onError );
  34669. }
  34670. /**
  34671. * Parses the given JSON object and returns a geometry.
  34672. *
  34673. * @param {Object} json - The serialized geometry.
  34674. * @return {BufferGeometry} The parsed geometry.
  34675. */
  34676. parse( json ) {
  34677. const interleavedBufferMap = {};
  34678. const arrayBufferMap = {};
  34679. function getInterleavedBuffer( json, uuid ) {
  34680. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34681. const interleavedBuffers = json.interleavedBuffers;
  34682. const interleavedBuffer = interleavedBuffers[ uuid ];
  34683. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34684. const array = getTypedArray( interleavedBuffer.type, buffer );
  34685. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34686. ib.uuid = interleavedBuffer.uuid;
  34687. interleavedBufferMap[ uuid ] = ib;
  34688. return ib;
  34689. }
  34690. function getArrayBuffer( json, uuid ) {
  34691. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34692. const arrayBuffers = json.arrayBuffers;
  34693. const arrayBuffer = arrayBuffers[ uuid ];
  34694. const ab = new Uint32Array( arrayBuffer ).buffer;
  34695. arrayBufferMap[ uuid ] = ab;
  34696. return ab;
  34697. }
  34698. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34699. const index = json.data.index;
  34700. if ( index !== undefined ) {
  34701. const typedArray = getTypedArray( index.type, index.array );
  34702. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34703. }
  34704. const attributes = json.data.attributes;
  34705. for ( const key in attributes ) {
  34706. const attribute = attributes[ key ];
  34707. let bufferAttribute;
  34708. if ( attribute.isInterleavedBufferAttribute ) {
  34709. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34710. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34711. } else {
  34712. const typedArray = getTypedArray( attribute.type, attribute.array );
  34713. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34714. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34715. }
  34716. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34717. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34718. geometry.setAttribute( key, bufferAttribute );
  34719. }
  34720. const morphAttributes = json.data.morphAttributes;
  34721. if ( morphAttributes ) {
  34722. for ( const key in morphAttributes ) {
  34723. const attributeArray = morphAttributes[ key ];
  34724. const array = [];
  34725. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34726. const attribute = attributeArray[ i ];
  34727. let bufferAttribute;
  34728. if ( attribute.isInterleavedBufferAttribute ) {
  34729. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34730. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34731. } else {
  34732. const typedArray = getTypedArray( attribute.type, attribute.array );
  34733. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34734. }
  34735. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34736. array.push( bufferAttribute );
  34737. }
  34738. geometry.morphAttributes[ key ] = array;
  34739. }
  34740. }
  34741. const morphTargetsRelative = json.data.morphTargetsRelative;
  34742. if ( morphTargetsRelative ) {
  34743. geometry.morphTargetsRelative = true;
  34744. }
  34745. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34746. if ( groups !== undefined ) {
  34747. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34748. const group = groups[ i ];
  34749. geometry.addGroup( group.start, group.count, group.materialIndex );
  34750. }
  34751. }
  34752. const boundingSphere = json.data.boundingSphere;
  34753. if ( boundingSphere !== undefined ) {
  34754. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34755. }
  34756. if ( json.name ) geometry.name = json.name;
  34757. if ( json.userData ) geometry.userData = json.userData;
  34758. return geometry;
  34759. }
  34760. }
  34761. /**
  34762. * 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}.
  34763. * The files are internally loaded via {@link FileLoader}.
  34764. *
  34765. * ```js
  34766. * const loader = new THREE.ObjectLoader();
  34767. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34768. * scene.add( obj );
  34769. *
  34770. * // Alternatively, to parse a previously loaded JSON structure
  34771. * const object = await loader.parseAsync( a_json_object );
  34772. * scene.add( object );
  34773. * ```
  34774. *
  34775. * @augments Loader
  34776. */
  34777. class ObjectLoader extends Loader {
  34778. /**
  34779. * Constructs a new object loader.
  34780. *
  34781. * @param {LoadingManager} [manager] - The loading manager.
  34782. */
  34783. constructor( manager ) {
  34784. super( manager );
  34785. }
  34786. /**
  34787. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34788. *
  34789. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34790. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34791. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34792. * @param {onErrorCallback} onError - Executed when errors occur.
  34793. */
  34794. load( url, onLoad, onProgress, onError ) {
  34795. const scope = this;
  34796. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34797. this.resourcePath = this.resourcePath || path;
  34798. const loader = new FileLoader( this.manager );
  34799. loader.setPath( this.path );
  34800. loader.setRequestHeader( this.requestHeader );
  34801. loader.setWithCredentials( this.withCredentials );
  34802. loader.load( url, function ( text ) {
  34803. let json = null;
  34804. try {
  34805. json = JSON.parse( text );
  34806. } catch ( error ) {
  34807. if ( onError !== undefined ) onError( error );
  34808. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34809. return;
  34810. }
  34811. const metadata = json.metadata;
  34812. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34813. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34814. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34815. return;
  34816. }
  34817. scope.parse( json, onLoad );
  34818. }, onProgress, onError );
  34819. }
  34820. /**
  34821. * Async version of {@link ObjectLoader#load}.
  34822. *
  34823. * @async
  34824. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34825. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34826. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34827. */
  34828. async loadAsync( url, onProgress ) {
  34829. const scope = this;
  34830. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34831. this.resourcePath = this.resourcePath || path;
  34832. const loader = new FileLoader( this.manager );
  34833. loader.setPath( this.path );
  34834. loader.setRequestHeader( this.requestHeader );
  34835. loader.setWithCredentials( this.withCredentials );
  34836. const text = await loader.loadAsync( url, onProgress );
  34837. const json = JSON.parse( text );
  34838. const metadata = json.metadata;
  34839. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34840. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34841. }
  34842. return await scope.parseAsync( json );
  34843. }
  34844. /**
  34845. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34846. * but can also be used directly to parse a previously loaded JSON structure.
  34847. *
  34848. * @param {Object} json - The serialized 3D object.
  34849. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34850. * @return {Object3D} The parsed 3D object.
  34851. */
  34852. parse( json, onLoad ) {
  34853. const animations = this.parseAnimations( json.animations );
  34854. const shapes = this.parseShapes( json.shapes );
  34855. const geometries = this.parseGeometries( json.geometries, shapes );
  34856. const images = this.parseImages( json.images, function () {
  34857. if ( onLoad !== undefined ) onLoad( object );
  34858. } );
  34859. const textures = this.parseTextures( json.textures, images );
  34860. const materials = this.parseMaterials( json.materials, textures );
  34861. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34862. const skeletons = this.parseSkeletons( json.skeletons, object );
  34863. this.bindSkeletons( object, skeletons );
  34864. this.bindLightTargets( object );
  34865. //
  34866. if ( onLoad !== undefined ) {
  34867. let hasImages = false;
  34868. for ( const uuid in images ) {
  34869. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34870. hasImages = true;
  34871. break;
  34872. }
  34873. }
  34874. if ( hasImages === false ) onLoad( object );
  34875. }
  34876. return object;
  34877. }
  34878. /**
  34879. * Async version of {@link ObjectLoader#parse}.
  34880. *
  34881. * @param {Object} json - The serialized 3D object.
  34882. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  34883. */
  34884. async parseAsync( json ) {
  34885. const animations = this.parseAnimations( json.animations );
  34886. const shapes = this.parseShapes( json.shapes );
  34887. const geometries = this.parseGeometries( json.geometries, shapes );
  34888. const images = await this.parseImagesAsync( json.images );
  34889. const textures = this.parseTextures( json.textures, images );
  34890. const materials = this.parseMaterials( json.materials, textures );
  34891. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34892. const skeletons = this.parseSkeletons( json.skeletons, object );
  34893. this.bindSkeletons( object, skeletons );
  34894. this.bindLightTargets( object );
  34895. return object;
  34896. }
  34897. // internals
  34898. parseShapes( json ) {
  34899. const shapes = {};
  34900. if ( json !== undefined ) {
  34901. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34902. const shape = new Shape().fromJSON( json[ i ] );
  34903. shapes[ shape.uuid ] = shape;
  34904. }
  34905. }
  34906. return shapes;
  34907. }
  34908. parseSkeletons( json, object ) {
  34909. const skeletons = {};
  34910. const bones = {};
  34911. // generate bone lookup table
  34912. object.traverse( function ( child ) {
  34913. if ( child.isBone ) bones[ child.uuid ] = child;
  34914. } );
  34915. // create skeletons
  34916. if ( json !== undefined ) {
  34917. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34918. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  34919. skeletons[ skeleton.uuid ] = skeleton;
  34920. }
  34921. }
  34922. return skeletons;
  34923. }
  34924. parseGeometries( json, shapes ) {
  34925. const geometries = {};
  34926. if ( json !== undefined ) {
  34927. const bufferGeometryLoader = new BufferGeometryLoader();
  34928. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34929. let geometry;
  34930. const data = json[ i ];
  34931. switch ( data.type ) {
  34932. case 'BufferGeometry':
  34933. case 'InstancedBufferGeometry':
  34934. geometry = bufferGeometryLoader.parse( data );
  34935. break;
  34936. default:
  34937. if ( data.type in Geometries ) {
  34938. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  34939. } else {
  34940. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  34941. }
  34942. }
  34943. geometry.uuid = data.uuid;
  34944. if ( data.name !== undefined ) geometry.name = data.name;
  34945. if ( data.userData !== undefined ) geometry.userData = data.userData;
  34946. geometries[ data.uuid ] = geometry;
  34947. }
  34948. }
  34949. return geometries;
  34950. }
  34951. parseMaterials( json, textures ) {
  34952. const cache = {}; // MultiMaterial
  34953. const materials = {};
  34954. if ( json !== undefined ) {
  34955. const loader = new MaterialLoader();
  34956. loader.setTextures( textures );
  34957. for ( let i = 0, l = json.length; i < l; i ++ ) {
  34958. const data = json[ i ];
  34959. if ( cache[ data.uuid ] === undefined ) {
  34960. cache[ data.uuid ] = loader.parse( data );
  34961. }
  34962. materials[ data.uuid ] = cache[ data.uuid ];
  34963. }
  34964. }
  34965. return materials;
  34966. }
  34967. parseAnimations( json ) {
  34968. const animations = {};
  34969. if ( json !== undefined ) {
  34970. for ( let i = 0; i < json.length; i ++ ) {
  34971. const data = json[ i ];
  34972. const clip = AnimationClip.parse( data );
  34973. animations[ clip.uuid ] = clip;
  34974. }
  34975. }
  34976. return animations;
  34977. }
  34978. parseImages( json, onLoad ) {
  34979. const scope = this;
  34980. const images = {};
  34981. let loader;
  34982. function loadImage( url ) {
  34983. scope.manager.itemStart( url );
  34984. return loader.load( url, function () {
  34985. scope.manager.itemEnd( url );
  34986. }, undefined, function () {
  34987. scope.manager.itemError( url );
  34988. scope.manager.itemEnd( url );
  34989. } );
  34990. }
  34991. function deserializeImage( image ) {
  34992. if ( typeof image === 'string' ) {
  34993. const url = image;
  34994. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  34995. return loadImage( path );
  34996. } else {
  34997. if ( image.data ) {
  34998. return {
  34999. data: getTypedArray( image.type, image.data ),
  35000. width: image.width,
  35001. height: image.height
  35002. };
  35003. } else {
  35004. return null;
  35005. }
  35006. }
  35007. }
  35008. if ( json !== undefined && json.length > 0 ) {
  35009. const manager = new LoadingManager( onLoad );
  35010. loader = new ImageLoader( manager );
  35011. loader.setCrossOrigin( this.crossOrigin );
  35012. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35013. const image = json[ i ];
  35014. const url = image.url;
  35015. if ( Array.isArray( url ) ) {
  35016. // load array of images e.g CubeTexture
  35017. const imageArray = [];
  35018. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35019. const currentUrl = url[ j ];
  35020. const deserializedImage = deserializeImage( currentUrl );
  35021. if ( deserializedImage !== null ) {
  35022. if ( deserializedImage instanceof HTMLImageElement ) {
  35023. imageArray.push( deserializedImage );
  35024. } else {
  35025. // special case: handle array of data textures for cube textures
  35026. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35027. }
  35028. }
  35029. }
  35030. images[ image.uuid ] = new Source( imageArray );
  35031. } else {
  35032. // load single image
  35033. const deserializedImage = deserializeImage( image.url );
  35034. images[ image.uuid ] = new Source( deserializedImage );
  35035. }
  35036. }
  35037. }
  35038. return images;
  35039. }
  35040. async parseImagesAsync( json ) {
  35041. const scope = this;
  35042. const images = {};
  35043. let loader;
  35044. async function deserializeImage( image ) {
  35045. if ( typeof image === 'string' ) {
  35046. const url = image;
  35047. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35048. return await loader.loadAsync( path );
  35049. } else {
  35050. if ( image.data ) {
  35051. return {
  35052. data: getTypedArray( image.type, image.data ),
  35053. width: image.width,
  35054. height: image.height
  35055. };
  35056. } else {
  35057. return null;
  35058. }
  35059. }
  35060. }
  35061. if ( json !== undefined && json.length > 0 ) {
  35062. loader = new ImageLoader( this.manager );
  35063. loader.setCrossOrigin( this.crossOrigin );
  35064. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35065. const image = json[ i ];
  35066. const url = image.url;
  35067. if ( Array.isArray( url ) ) {
  35068. // load array of images e.g CubeTexture
  35069. const imageArray = [];
  35070. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35071. const currentUrl = url[ j ];
  35072. const deserializedImage = await deserializeImage( currentUrl );
  35073. if ( deserializedImage !== null ) {
  35074. if ( deserializedImage instanceof HTMLImageElement ) {
  35075. imageArray.push( deserializedImage );
  35076. } else {
  35077. // special case: handle array of data textures for cube textures
  35078. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35079. }
  35080. }
  35081. }
  35082. images[ image.uuid ] = new Source( imageArray );
  35083. } else {
  35084. // load single image
  35085. const deserializedImage = await deserializeImage( image.url );
  35086. images[ image.uuid ] = new Source( deserializedImage );
  35087. }
  35088. }
  35089. }
  35090. return images;
  35091. }
  35092. parseTextures( json, images ) {
  35093. function parseConstant( value, type ) {
  35094. if ( typeof value === 'number' ) return value;
  35095. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35096. return type[ value ];
  35097. }
  35098. const textures = {};
  35099. if ( json !== undefined ) {
  35100. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35101. const data = json[ i ];
  35102. if ( data.image === undefined ) {
  35103. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  35104. }
  35105. if ( images[ data.image ] === undefined ) {
  35106. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  35107. }
  35108. const source = images[ data.image ];
  35109. const image = source.data;
  35110. let texture;
  35111. if ( Array.isArray( image ) ) {
  35112. texture = new CubeTexture();
  35113. if ( image.length === 6 ) texture.needsUpdate = true;
  35114. } else {
  35115. if ( image && image.data ) {
  35116. texture = new DataTexture();
  35117. } else {
  35118. texture = new Texture();
  35119. }
  35120. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35121. }
  35122. texture.source = source;
  35123. texture.uuid = data.uuid;
  35124. if ( data.name !== undefined ) texture.name = data.name;
  35125. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35126. if ( data.channel !== undefined ) texture.channel = data.channel;
  35127. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35128. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35129. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35130. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35131. if ( data.wrap !== undefined ) {
  35132. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35133. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35134. }
  35135. if ( data.format !== undefined ) texture.format = data.format;
  35136. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35137. if ( data.type !== undefined ) texture.type = data.type;
  35138. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35139. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35140. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35141. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35142. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35143. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35144. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35145. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35146. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35147. if ( data.userData !== undefined ) texture.userData = data.userData;
  35148. textures[ data.uuid ] = texture;
  35149. }
  35150. }
  35151. return textures;
  35152. }
  35153. parseObject( data, geometries, materials, textures, animations ) {
  35154. let object;
  35155. function getGeometry( name ) {
  35156. if ( geometries[ name ] === undefined ) {
  35157. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  35158. }
  35159. return geometries[ name ];
  35160. }
  35161. function getMaterial( name ) {
  35162. if ( name === undefined ) return undefined;
  35163. if ( Array.isArray( name ) ) {
  35164. const array = [];
  35165. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35166. const uuid = name[ i ];
  35167. if ( materials[ uuid ] === undefined ) {
  35168. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  35169. }
  35170. array.push( materials[ uuid ] );
  35171. }
  35172. return array;
  35173. }
  35174. if ( materials[ name ] === undefined ) {
  35175. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  35176. }
  35177. return materials[ name ];
  35178. }
  35179. function getTexture( uuid ) {
  35180. if ( textures[ uuid ] === undefined ) {
  35181. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  35182. }
  35183. return textures[ uuid ];
  35184. }
  35185. let geometry, material;
  35186. switch ( data.type ) {
  35187. case 'Scene':
  35188. object = new Scene();
  35189. if ( data.background !== undefined ) {
  35190. if ( Number.isInteger( data.background ) ) {
  35191. object.background = new Color( data.background );
  35192. } else {
  35193. object.background = getTexture( data.background );
  35194. }
  35195. }
  35196. if ( data.environment !== undefined ) {
  35197. object.environment = getTexture( data.environment );
  35198. }
  35199. if ( data.fog !== undefined ) {
  35200. if ( data.fog.type === 'Fog' ) {
  35201. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35202. } else if ( data.fog.type === 'FogExp2' ) {
  35203. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35204. }
  35205. if ( data.fog.name !== '' ) {
  35206. object.fog.name = data.fog.name;
  35207. }
  35208. }
  35209. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35210. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35211. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35212. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35213. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35214. break;
  35215. case 'PerspectiveCamera':
  35216. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35217. if ( data.focus !== undefined ) object.focus = data.focus;
  35218. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35219. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35220. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35221. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35222. break;
  35223. case 'OrthographicCamera':
  35224. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35225. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35226. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35227. break;
  35228. case 'AmbientLight':
  35229. object = new AmbientLight( data.color, data.intensity );
  35230. break;
  35231. case 'DirectionalLight':
  35232. object = new DirectionalLight( data.color, data.intensity );
  35233. object.target = data.target || '';
  35234. break;
  35235. case 'PointLight':
  35236. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35237. break;
  35238. case 'RectAreaLight':
  35239. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35240. break;
  35241. case 'SpotLight':
  35242. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35243. object.target = data.target || '';
  35244. break;
  35245. case 'HemisphereLight':
  35246. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35247. break;
  35248. case 'LightProbe':
  35249. object = new LightProbe().fromJSON( data );
  35250. break;
  35251. case 'SkinnedMesh':
  35252. geometry = getGeometry( data.geometry );
  35253. material = getMaterial( data.material );
  35254. object = new SkinnedMesh( geometry, material );
  35255. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35256. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35257. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35258. break;
  35259. case 'Mesh':
  35260. geometry = getGeometry( data.geometry );
  35261. material = getMaterial( data.material );
  35262. object = new Mesh( geometry, material );
  35263. break;
  35264. case 'InstancedMesh':
  35265. geometry = getGeometry( data.geometry );
  35266. material = getMaterial( data.material );
  35267. const count = data.count;
  35268. const instanceMatrix = data.instanceMatrix;
  35269. const instanceColor = data.instanceColor;
  35270. object = new InstancedMesh( geometry, material, count );
  35271. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35272. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35273. break;
  35274. case 'BatchedMesh':
  35275. geometry = getGeometry( data.geometry );
  35276. material = getMaterial( data.material );
  35277. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35278. object.geometry = geometry;
  35279. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35280. object.sortObjects = data.sortObjects;
  35281. object._drawRanges = data.drawRanges;
  35282. object._reservedRanges = data.reservedRanges;
  35283. object._geometryInfo = data.geometryInfo.map( info => {
  35284. let box = null;
  35285. let sphere = null;
  35286. if ( info.boundingBox !== undefined ) {
  35287. box = new Box3().fromJSON( info.boundingBox );
  35288. }
  35289. if ( info.boundingSphere !== undefined ) {
  35290. sphere = new Sphere().fromJSON( info.boundingSphere );
  35291. }
  35292. return {
  35293. ...info,
  35294. boundingBox: box,
  35295. boundingSphere: sphere
  35296. };
  35297. } );
  35298. object._instanceInfo = data.instanceInfo;
  35299. object._availableInstanceIds = data._availableInstanceIds;
  35300. object._availableGeometryIds = data._availableGeometryIds;
  35301. object._nextIndexStart = data.nextIndexStart;
  35302. object._nextVertexStart = data.nextVertexStart;
  35303. object._geometryCount = data.geometryCount;
  35304. object._maxInstanceCount = data.maxInstanceCount;
  35305. object._maxVertexCount = data.maxVertexCount;
  35306. object._maxIndexCount = data.maxIndexCount;
  35307. object._geometryInitialized = data.geometryInitialized;
  35308. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35309. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35310. if ( data.colorsTexture !== undefined ) {
  35311. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35312. }
  35313. if ( data.boundingSphere !== undefined ) {
  35314. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35315. }
  35316. if ( data.boundingBox !== undefined ) {
  35317. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35318. }
  35319. break;
  35320. case 'LOD':
  35321. object = new LOD();
  35322. break;
  35323. case 'Line':
  35324. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35325. break;
  35326. case 'LineLoop':
  35327. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35328. break;
  35329. case 'LineSegments':
  35330. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35331. break;
  35332. case 'PointCloud':
  35333. case 'Points':
  35334. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35335. break;
  35336. case 'Sprite':
  35337. object = new Sprite( getMaterial( data.material ) );
  35338. break;
  35339. case 'Group':
  35340. object = new Group();
  35341. break;
  35342. case 'Bone':
  35343. object = new Bone();
  35344. break;
  35345. default:
  35346. object = new Object3D();
  35347. }
  35348. object.uuid = data.uuid;
  35349. if ( data.name !== undefined ) object.name = data.name;
  35350. if ( data.matrix !== undefined ) {
  35351. object.matrix.fromArray( data.matrix );
  35352. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35353. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35354. } else {
  35355. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35356. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35357. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35358. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35359. }
  35360. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35361. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35362. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35363. if ( data.shadow ) {
  35364. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35365. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35366. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35367. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35368. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35369. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35370. }
  35371. if ( data.visible !== undefined ) object.visible = data.visible;
  35372. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35373. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35374. if ( data.userData !== undefined ) object.userData = data.userData;
  35375. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35376. if ( data.children !== undefined ) {
  35377. const children = data.children;
  35378. for ( let i = 0; i < children.length; i ++ ) {
  35379. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35380. }
  35381. }
  35382. if ( data.animations !== undefined ) {
  35383. const objectAnimations = data.animations;
  35384. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35385. const uuid = objectAnimations[ i ];
  35386. object.animations.push( animations[ uuid ] );
  35387. }
  35388. }
  35389. if ( data.type === 'LOD' ) {
  35390. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35391. const levels = data.levels;
  35392. for ( let l = 0; l < levels.length; l ++ ) {
  35393. const level = levels[ l ];
  35394. const child = object.getObjectByProperty( 'uuid', level.object );
  35395. if ( child !== undefined ) {
  35396. object.addLevel( child, level.distance, level.hysteresis );
  35397. }
  35398. }
  35399. }
  35400. return object;
  35401. }
  35402. bindSkeletons( object, skeletons ) {
  35403. if ( Object.keys( skeletons ).length === 0 ) return;
  35404. object.traverse( function ( child ) {
  35405. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35406. const skeleton = skeletons[ child.skeleton ];
  35407. if ( skeleton === undefined ) {
  35408. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35409. } else {
  35410. child.bind( skeleton, child.bindMatrix );
  35411. }
  35412. }
  35413. } );
  35414. }
  35415. bindLightTargets( object ) {
  35416. object.traverse( function ( child ) {
  35417. if ( child.isDirectionalLight || child.isSpotLight ) {
  35418. const uuid = child.target;
  35419. const target = object.getObjectByProperty( 'uuid', uuid );
  35420. if ( target !== undefined ) {
  35421. child.target = target;
  35422. } else {
  35423. child.target = new Object3D();
  35424. }
  35425. }
  35426. } );
  35427. }
  35428. }
  35429. const TEXTURE_MAPPING = {
  35430. UVMapping: UVMapping,
  35431. CubeReflectionMapping: CubeReflectionMapping,
  35432. CubeRefractionMapping: CubeRefractionMapping,
  35433. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35434. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35435. CubeUVReflectionMapping: CubeUVReflectionMapping
  35436. };
  35437. const TEXTURE_WRAPPING = {
  35438. RepeatWrapping: RepeatWrapping,
  35439. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35440. MirroredRepeatWrapping: MirroredRepeatWrapping
  35441. };
  35442. const TEXTURE_FILTER = {
  35443. NearestFilter: NearestFilter,
  35444. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35445. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35446. LinearFilter: LinearFilter,
  35447. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35448. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35449. };
  35450. const _errorMap = new WeakMap();
  35451. /**
  35452. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35453. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35454. * textures for rendering.
  35455. *
  35456. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35457. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35458. *
  35459. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35460. *
  35461. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35462. *
  35463. * ```js
  35464. * const loader = new THREE.ImageBitmapLoader();
  35465. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35466. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35467. *
  35468. * const texture = new THREE.Texture( imageBitmap );
  35469. * texture.needsUpdate = true;
  35470. * ```
  35471. *
  35472. * @augments Loader
  35473. */
  35474. class ImageBitmapLoader extends Loader {
  35475. /**
  35476. * Constructs a new image bitmap loader.
  35477. *
  35478. * @param {LoadingManager} [manager] - The loading manager.
  35479. */
  35480. constructor( manager ) {
  35481. super( manager );
  35482. /**
  35483. * This flag can be used for type testing.
  35484. *
  35485. * @type {boolean}
  35486. * @readonly
  35487. * @default true
  35488. */
  35489. this.isImageBitmapLoader = true;
  35490. if ( typeof createImageBitmap === 'undefined' ) {
  35491. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  35492. }
  35493. if ( typeof fetch === 'undefined' ) {
  35494. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  35495. }
  35496. /**
  35497. * Represents the loader options.
  35498. *
  35499. * @type {Object}
  35500. * @default {premultiplyAlpha:'none'}
  35501. */
  35502. this.options = { premultiplyAlpha: 'none' };
  35503. /**
  35504. * Used for aborting requests.
  35505. *
  35506. * @private
  35507. * @type {AbortController}
  35508. */
  35509. this._abortController = new AbortController();
  35510. }
  35511. /**
  35512. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35513. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35514. *
  35515. * @param {Object} options - The loader options to set.
  35516. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35517. */
  35518. setOptions( options ) {
  35519. this.options = options;
  35520. return this;
  35521. }
  35522. /**
  35523. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35524. *
  35525. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35526. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35527. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35528. * @param {onErrorCallback} onError - Executed when errors occur.
  35529. * @return {ImageBitmap|undefined} The image bitmap.
  35530. */
  35531. load( url, onLoad, onProgress, onError ) {
  35532. if ( url === undefined ) url = '';
  35533. if ( this.path !== undefined ) url = this.path + url;
  35534. url = this.manager.resolveURL( url );
  35535. const scope = this;
  35536. const cached = Cache.get( `image-bitmap:${url}` );
  35537. if ( cached !== undefined ) {
  35538. scope.manager.itemStart( url );
  35539. // If cached is a promise, wait for it to resolve
  35540. if ( cached.then ) {
  35541. cached.then( imageBitmap => {
  35542. // check if there is an error for the cached promise
  35543. if ( _errorMap.has( cached ) === true ) {
  35544. if ( onError ) onError( _errorMap.get( cached ) );
  35545. scope.manager.itemError( url );
  35546. scope.manager.itemEnd( url );
  35547. } else {
  35548. if ( onLoad ) onLoad( imageBitmap );
  35549. scope.manager.itemEnd( url );
  35550. return imageBitmap;
  35551. }
  35552. } );
  35553. return;
  35554. }
  35555. // If cached is not a promise (i.e., it's already an imageBitmap)
  35556. setTimeout( function () {
  35557. if ( onLoad ) onLoad( cached );
  35558. scope.manager.itemEnd( url );
  35559. }, 0 );
  35560. return cached;
  35561. }
  35562. const fetchOptions = {};
  35563. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35564. fetchOptions.headers = this.requestHeader;
  35565. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35566. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35567. return res.blob();
  35568. } ).then( function ( blob ) {
  35569. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35570. } ).then( function ( imageBitmap ) {
  35571. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35572. if ( onLoad ) onLoad( imageBitmap );
  35573. scope.manager.itemEnd( url );
  35574. return imageBitmap;
  35575. } ).catch( function ( e ) {
  35576. if ( onError ) onError( e );
  35577. _errorMap.set( promise, e );
  35578. Cache.remove( `image-bitmap:${url}` );
  35579. scope.manager.itemError( url );
  35580. scope.manager.itemEnd( url );
  35581. } );
  35582. Cache.add( `image-bitmap:${url}`, promise );
  35583. scope.manager.itemStart( url );
  35584. }
  35585. /**
  35586. * Aborts ongoing fetch requests.
  35587. *
  35588. * @return {ImageBitmapLoader} A reference to this instance.
  35589. */
  35590. abort() {
  35591. this._abortController.abort();
  35592. this._abortController = new AbortController();
  35593. return this;
  35594. }
  35595. }
  35596. let _context;
  35597. /**
  35598. * Manages the global audio context in the engine.
  35599. *
  35600. * @hideconstructor
  35601. */
  35602. class AudioContext {
  35603. /**
  35604. * Returns the global native audio context.
  35605. *
  35606. * @return {AudioContext} The native audio context.
  35607. */
  35608. static getContext() {
  35609. if ( _context === undefined ) {
  35610. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35611. }
  35612. return _context;
  35613. }
  35614. /**
  35615. * Allows to set the global native audio context from outside.
  35616. *
  35617. * @param {AudioContext} value - The native context to set.
  35618. */
  35619. static setContext( value ) {
  35620. _context = value;
  35621. }
  35622. }
  35623. /**
  35624. * Class for loading audio buffers. Audios are internally
  35625. * loaded via {@link FileLoader}.
  35626. *
  35627. * ```js
  35628. * const audioListener = new THREE.AudioListener();
  35629. * const ambientSound = new THREE.Audio( audioListener );
  35630. *
  35631. * const loader = new THREE.AudioLoader();
  35632. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35633. *
  35634. * ambientSound.setBuffer( audioBuffer );
  35635. * ambientSound.play();
  35636. * ```
  35637. *
  35638. * @augments Loader
  35639. */
  35640. class AudioLoader extends Loader {
  35641. /**
  35642. * Constructs a new audio loader.
  35643. *
  35644. * @param {LoadingManager} [manager] - The loading manager.
  35645. */
  35646. constructor( manager ) {
  35647. super( manager );
  35648. }
  35649. /**
  35650. * Starts loading from the given URL and passes the loaded audio buffer
  35651. * to the `onLoad()` callback.
  35652. *
  35653. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35654. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35655. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35656. * @param {onErrorCallback} onError - Executed when errors occur.
  35657. */
  35658. load( url, onLoad, onProgress, onError ) {
  35659. const scope = this;
  35660. const loader = new FileLoader( this.manager );
  35661. loader.setResponseType( 'arraybuffer' );
  35662. loader.setPath( this.path );
  35663. loader.setRequestHeader( this.requestHeader );
  35664. loader.setWithCredentials( this.withCredentials );
  35665. loader.load( url, function ( buffer ) {
  35666. try {
  35667. // Create a copy of the buffer. The `decodeAudioData` method
  35668. // detaches the buffer when complete, preventing reuse.
  35669. const bufferCopy = buffer.slice( 0 );
  35670. const context = AudioContext.getContext();
  35671. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35672. onLoad( audioBuffer );
  35673. } ).catch( handleError );
  35674. } catch ( e ) {
  35675. handleError( e );
  35676. }
  35677. }, onProgress, onError );
  35678. function handleError( e ) {
  35679. if ( onError ) {
  35680. onError( e );
  35681. } else {
  35682. console.error( e );
  35683. }
  35684. scope.manager.itemError( url );
  35685. }
  35686. }
  35687. }
  35688. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35689. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35690. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35691. /**
  35692. * A special type of camera that uses two perspective cameras with
  35693. * stereoscopic projection. Can be used for rendering stereo effects
  35694. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35695. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35696. */
  35697. class StereoCamera {
  35698. /**
  35699. * Constructs a new stereo camera.
  35700. */
  35701. constructor() {
  35702. /**
  35703. * The type property is used for detecting the object type
  35704. * in context of serialization/deserialization.
  35705. *
  35706. * @type {string}
  35707. * @readonly
  35708. */
  35709. this.type = 'StereoCamera';
  35710. /**
  35711. * The aspect.
  35712. *
  35713. * @type {number}
  35714. * @default 1
  35715. */
  35716. this.aspect = 1;
  35717. /**
  35718. * The eye separation which represents the distance
  35719. * between the left and right camera.
  35720. *
  35721. * @type {number}
  35722. * @default 0.064
  35723. */
  35724. this.eyeSep = 0.064;
  35725. /**
  35726. * The camera representing the left eye. This is added to layer `1` so objects to be
  35727. * rendered by the left camera must also be added to this layer.
  35728. *
  35729. * @type {PerspectiveCamera}
  35730. */
  35731. this.cameraL = new PerspectiveCamera();
  35732. this.cameraL.layers.enable( 1 );
  35733. this.cameraL.matrixAutoUpdate = false;
  35734. /**
  35735. * The camera representing the right eye. This is added to layer `2` so objects to be
  35736. * rendered by the right camera must also be added to this layer.
  35737. *
  35738. * @type {PerspectiveCamera}
  35739. */
  35740. this.cameraR = new PerspectiveCamera();
  35741. this.cameraR.layers.enable( 2 );
  35742. this.cameraR.matrixAutoUpdate = false;
  35743. this._cache = {
  35744. focus: null,
  35745. fov: null,
  35746. aspect: null,
  35747. near: null,
  35748. far: null,
  35749. zoom: null,
  35750. eyeSep: null
  35751. };
  35752. }
  35753. /**
  35754. * Updates the stereo camera based on the given perspective camera.
  35755. *
  35756. * @param {PerspectiveCamera} camera - The perspective camera.
  35757. */
  35758. update( camera ) {
  35759. const cache = this._cache;
  35760. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35761. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35762. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35763. if ( needsUpdate ) {
  35764. cache.focus = camera.focus;
  35765. cache.fov = camera.fov;
  35766. cache.aspect = camera.aspect * this.aspect;
  35767. cache.near = camera.near;
  35768. cache.far = camera.far;
  35769. cache.zoom = camera.zoom;
  35770. cache.eyeSep = this.eyeSep;
  35771. // Off-axis stereoscopic effect based on
  35772. // http://paulbourke.net/stereographics/stereorender/
  35773. _projectionMatrix.copy( camera.projectionMatrix );
  35774. const eyeSepHalf = cache.eyeSep / 2;
  35775. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35776. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35777. let xmin, xmax;
  35778. // translate xOffset
  35779. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35780. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35781. // for left eye
  35782. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35783. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35784. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35785. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35786. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35787. // for right eye
  35788. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35789. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35790. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35791. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35792. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35793. }
  35794. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35795. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35796. }
  35797. }
  35798. /**
  35799. * This type of camera can be used in order to efficiently render a scene with a
  35800. * predefined set of cameras. This is an important performance aspect for
  35801. * rendering VR scenes.
  35802. *
  35803. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35804. * to define for each sub camera the `viewport` property which determines the
  35805. * part of the viewport that is rendered with this camera.
  35806. *
  35807. * @augments PerspectiveCamera
  35808. */
  35809. class ArrayCamera extends PerspectiveCamera {
  35810. /**
  35811. * Constructs a new array camera.
  35812. *
  35813. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35814. */
  35815. constructor( array = [] ) {
  35816. super();
  35817. /**
  35818. * This flag can be used for type testing.
  35819. *
  35820. * @type {boolean}
  35821. * @readonly
  35822. * @default true
  35823. */
  35824. this.isArrayCamera = true;
  35825. /**
  35826. * Whether this camera is used with multiview rendering or not.
  35827. *
  35828. * @type {boolean}
  35829. * @readonly
  35830. * @default false
  35831. */
  35832. this.isMultiViewCamera = false;
  35833. /**
  35834. * An array of perspective sub cameras.
  35835. *
  35836. * @type {Array<PerspectiveCamera>}
  35837. */
  35838. this.cameras = array;
  35839. }
  35840. }
  35841. /**
  35842. * Class for keeping track of time.
  35843. */
  35844. class Clock {
  35845. /**
  35846. * Constructs a new clock.
  35847. *
  35848. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35849. * `getDelta()` is called for the first time.
  35850. */
  35851. constructor( autoStart = true ) {
  35852. /**
  35853. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35854. * for the first time.
  35855. *
  35856. * @type {boolean}
  35857. * @default true
  35858. */
  35859. this.autoStart = autoStart;
  35860. /**
  35861. * Holds the time at which the clock's `start()` method was last called.
  35862. *
  35863. * @type {number}
  35864. * @default 0
  35865. */
  35866. this.startTime = 0;
  35867. /**
  35868. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35869. * `getDelta()` methods were last called.
  35870. *
  35871. * @type {number}
  35872. * @default 0
  35873. */
  35874. this.oldTime = 0;
  35875. /**
  35876. * Keeps track of the total time that the clock has been running.
  35877. *
  35878. * @type {number}
  35879. * @default 0
  35880. */
  35881. this.elapsedTime = 0;
  35882. /**
  35883. * Whether the clock is running or not.
  35884. *
  35885. * @type {boolean}
  35886. * @default true
  35887. */
  35888. this.running = false;
  35889. }
  35890. /**
  35891. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  35892. * called by the class.
  35893. */
  35894. start() {
  35895. this.startTime = performance.now();
  35896. this.oldTime = this.startTime;
  35897. this.elapsedTime = 0;
  35898. this.running = true;
  35899. }
  35900. /**
  35901. * Stops the clock.
  35902. */
  35903. stop() {
  35904. this.getElapsedTime();
  35905. this.running = false;
  35906. this.autoStart = false;
  35907. }
  35908. /**
  35909. * Returns the elapsed time in seconds.
  35910. *
  35911. * @return {number} The elapsed time.
  35912. */
  35913. getElapsedTime() {
  35914. this.getDelta();
  35915. return this.elapsedTime;
  35916. }
  35917. /**
  35918. * Returns the delta time in seconds.
  35919. *
  35920. * @return {number} The delta time.
  35921. */
  35922. getDelta() {
  35923. let diff = 0;
  35924. if ( this.autoStart && ! this.running ) {
  35925. this.start();
  35926. return 0;
  35927. }
  35928. if ( this.running ) {
  35929. const newTime = performance.now();
  35930. diff = ( newTime - this.oldTime ) / 1000;
  35931. this.oldTime = newTime;
  35932. this.elapsedTime += diff;
  35933. }
  35934. return diff;
  35935. }
  35936. }
  35937. const _position$1 = /*@__PURE__*/ new Vector3();
  35938. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  35939. const _scale$1 = /*@__PURE__*/ new Vector3();
  35940. const _forward = /*@__PURE__*/ new Vector3();
  35941. const _up = /*@__PURE__*/ new Vector3();
  35942. /**
  35943. * The class represents a virtual listener of the all positional and non-positional audio effects
  35944. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  35945. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  35946. *
  35947. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  35948. * camera represents the 3D transformation of the listener.
  35949. *
  35950. * @augments Object3D
  35951. */
  35952. class AudioListener extends Object3D {
  35953. /**
  35954. * Constructs a new audio listener.
  35955. */
  35956. constructor() {
  35957. super();
  35958. this.type = 'AudioListener';
  35959. /**
  35960. * The native audio context.
  35961. *
  35962. * @type {AudioContext}
  35963. * @readonly
  35964. */
  35965. this.context = AudioContext.getContext();
  35966. /**
  35967. * The gain node used for volume control.
  35968. *
  35969. * @type {GainNode}
  35970. * @readonly
  35971. */
  35972. this.gain = this.context.createGain();
  35973. this.gain.connect( this.context.destination );
  35974. /**
  35975. * An optional filter.
  35976. *
  35977. * Defined via {@link AudioListener#setFilter}.
  35978. *
  35979. * @type {?AudioNode}
  35980. * @default null
  35981. * @readonly
  35982. */
  35983. this.filter = null;
  35984. /**
  35985. * Time delta values required for `linearRampToValueAtTime()` usage.
  35986. *
  35987. * @type {number}
  35988. * @default 0
  35989. * @readonly
  35990. */
  35991. this.timeDelta = 0;
  35992. // private
  35993. this._clock = new Clock();
  35994. }
  35995. /**
  35996. * Returns the listener's input node.
  35997. *
  35998. * This method is used by other audio nodes to connect to this listener.
  35999. *
  36000. * @return {GainNode} The input node.
  36001. */
  36002. getInput() {
  36003. return this.gain;
  36004. }
  36005. /**
  36006. * Removes the current filter from this listener.
  36007. *
  36008. * @return {AudioListener} A reference to this listener.
  36009. */
  36010. removeFilter() {
  36011. if ( this.filter !== null ) {
  36012. this.gain.disconnect( this.filter );
  36013. this.filter.disconnect( this.context.destination );
  36014. this.gain.connect( this.context.destination );
  36015. this.filter = null;
  36016. }
  36017. return this;
  36018. }
  36019. /**
  36020. * Returns the current set filter.
  36021. *
  36022. * @return {?AudioNode} The filter.
  36023. */
  36024. getFilter() {
  36025. return this.filter;
  36026. }
  36027. /**
  36028. * Sets the given filter to this listener.
  36029. *
  36030. * @param {AudioNode} value - The filter to set.
  36031. * @return {AudioListener} A reference to this listener.
  36032. */
  36033. setFilter( value ) {
  36034. if ( this.filter !== null ) {
  36035. this.gain.disconnect( this.filter );
  36036. this.filter.disconnect( this.context.destination );
  36037. } else {
  36038. this.gain.disconnect( this.context.destination );
  36039. }
  36040. this.filter = value;
  36041. this.gain.connect( this.filter );
  36042. this.filter.connect( this.context.destination );
  36043. return this;
  36044. }
  36045. /**
  36046. * Returns the applications master volume.
  36047. *
  36048. * @return {number} The master volume.
  36049. */
  36050. getMasterVolume() {
  36051. return this.gain.gain.value;
  36052. }
  36053. /**
  36054. * Sets the applications master volume. This volume setting affects
  36055. * all audio nodes in the scene.
  36056. *
  36057. * @param {number} value - The master volume to set.
  36058. * @return {AudioListener} A reference to this listener.
  36059. */
  36060. setMasterVolume( value ) {
  36061. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36062. return this;
  36063. }
  36064. updateMatrixWorld( force ) {
  36065. super.updateMatrixWorld( force );
  36066. const listener = this.context.listener;
  36067. this.timeDelta = this._clock.getDelta();
  36068. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36069. // the initial forward and up directions must be orthogonal
  36070. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36071. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36072. if ( listener.positionX ) {
  36073. // code path for Chrome (see #14393)
  36074. const endTime = this.context.currentTime + this.timeDelta;
  36075. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36076. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36077. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36078. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36079. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36080. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36081. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36082. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36083. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36084. } else {
  36085. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36086. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36087. }
  36088. }
  36089. }
  36090. /**
  36091. * Represents a non-positional ( global ) audio object.
  36092. *
  36093. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36094. *
  36095. * ```js
  36096. * // create an AudioListener and add it to the camera
  36097. * const listener = new THREE.AudioListener();
  36098. * camera.add( listener );
  36099. *
  36100. * // create a global audio source
  36101. * const sound = new THREE.Audio( listener );
  36102. *
  36103. * // load a sound and set it as the Audio object's buffer
  36104. * const audioLoader = new THREE.AudioLoader();
  36105. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36106. * sound.setBuffer( buffer );
  36107. * sound.setLoop( true );
  36108. * sound.setVolume( 0.5 );
  36109. * sound.play();
  36110. * });
  36111. * ```
  36112. *
  36113. * @augments Object3D
  36114. */
  36115. class Audio extends Object3D {
  36116. /**
  36117. * Constructs a new audio.
  36118. *
  36119. * @param {AudioListener} listener - The global audio listener.
  36120. */
  36121. constructor( listener ) {
  36122. super();
  36123. this.type = 'Audio';
  36124. /**
  36125. * The global audio listener.
  36126. *
  36127. * @type {AudioListener}
  36128. * @readonly
  36129. */
  36130. this.listener = listener;
  36131. /**
  36132. * The audio context.
  36133. *
  36134. * @type {AudioContext}
  36135. * @readonly
  36136. */
  36137. this.context = listener.context;
  36138. /**
  36139. * The gain node used for volume control.
  36140. *
  36141. * @type {GainNode}
  36142. * @readonly
  36143. */
  36144. this.gain = this.context.createGain();
  36145. this.gain.connect( listener.getInput() );
  36146. /**
  36147. * Whether to start playback automatically or not.
  36148. *
  36149. * @type {boolean}
  36150. * @default false
  36151. */
  36152. this.autoplay = false;
  36153. /**
  36154. * A reference to an audio buffer.
  36155. *
  36156. * Defined via {@link Audio#setBuffer}.
  36157. *
  36158. * @type {?AudioBuffer}
  36159. * @default null
  36160. * @readonly
  36161. */
  36162. this.buffer = null;
  36163. /**
  36164. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36165. * +/- 1200 is an octave.
  36166. *
  36167. * Defined via {@link Audio#setDetune}.
  36168. *
  36169. * @type {number}
  36170. * @default 0
  36171. * @readonly
  36172. */
  36173. this.detune = 0;
  36174. /**
  36175. * Whether the audio should loop or not.
  36176. *
  36177. * Defined via {@link Audio#setLoop}.
  36178. *
  36179. * @type {boolean}
  36180. * @default false
  36181. * @readonly
  36182. */
  36183. this.loop = false;
  36184. /**
  36185. * Defines where in the audio buffer the replay should
  36186. * start, in seconds.
  36187. *
  36188. * @type {number}
  36189. * @default 0
  36190. */
  36191. this.loopStart = 0;
  36192. /**
  36193. * Defines where in the audio buffer the replay should
  36194. * stop, in seconds.
  36195. *
  36196. * @type {number}
  36197. * @default 0
  36198. */
  36199. this.loopEnd = 0;
  36200. /**
  36201. * An offset to the time within the audio buffer the playback
  36202. * should begin, in seconds.
  36203. *
  36204. * @type {number}
  36205. * @default 0
  36206. */
  36207. this.offset = 0;
  36208. /**
  36209. * Overrides the default duration of the audio.
  36210. *
  36211. * @type {undefined|number}
  36212. * @default undefined
  36213. */
  36214. this.duration = undefined;
  36215. /**
  36216. * The playback speed.
  36217. *
  36218. * Defined via {@link Audio#setPlaybackRate}.
  36219. *
  36220. * @type {number}
  36221. * @readonly
  36222. * @default 1
  36223. */
  36224. this.playbackRate = 1;
  36225. /**
  36226. * Indicates whether the audio is playing or not.
  36227. *
  36228. * This flag will be automatically set when using {@link Audio#play},
  36229. * {@link Audio#pause}, {@link Audio#stop}.
  36230. *
  36231. * @type {boolean}
  36232. * @readonly
  36233. * @default false
  36234. */
  36235. this.isPlaying = false;
  36236. /**
  36237. * Indicates whether the audio playback can be controlled
  36238. * with method like {@link Audio#play} or {@link Audio#pause}.
  36239. *
  36240. * This flag will be automatically set when audio sources are
  36241. * defined.
  36242. *
  36243. * @type {boolean}
  36244. * @readonly
  36245. * @default true
  36246. */
  36247. this.hasPlaybackControl = true;
  36248. /**
  36249. * Holds a reference to the current audio source.
  36250. *
  36251. * The property is automatically by one of the `set*()` methods.
  36252. *
  36253. * @type {?AudioNode}
  36254. * @readonly
  36255. * @default null
  36256. */
  36257. this.source = null;
  36258. /**
  36259. * Defines the source type.
  36260. *
  36261. * The property is automatically by one of the `set*()` methods.
  36262. *
  36263. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36264. * @readonly
  36265. * @default 'empty'
  36266. */
  36267. this.sourceType = 'empty';
  36268. this._startedAt = 0;
  36269. this._progress = 0;
  36270. this._connected = false;
  36271. /**
  36272. * Can be used to apply a variety of low-order filters to create
  36273. * more complex sound effects e.g. via `BiquadFilterNode`.
  36274. *
  36275. * The property is automatically set by {@link Audio#setFilters}.
  36276. *
  36277. * @type {Array<AudioNode>}
  36278. * @readonly
  36279. */
  36280. this.filters = [];
  36281. }
  36282. /**
  36283. * Returns the output audio node.
  36284. *
  36285. * @return {GainNode} The output node.
  36286. */
  36287. getOutput() {
  36288. return this.gain;
  36289. }
  36290. /**
  36291. * Sets the given audio node as the source of this instance.
  36292. *
  36293. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36294. *
  36295. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36296. * @return {Audio} A reference to this instance.
  36297. */
  36298. setNodeSource( audioNode ) {
  36299. this.hasPlaybackControl = false;
  36300. this.sourceType = 'audioNode';
  36301. this.source = audioNode;
  36302. this.connect();
  36303. return this;
  36304. }
  36305. /**
  36306. * Sets the given media element as the source of this instance.
  36307. *
  36308. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36309. *
  36310. * @param {HTMLMediaElement} mediaElement - The media element.
  36311. * @return {Audio} A reference to this instance.
  36312. */
  36313. setMediaElementSource( mediaElement ) {
  36314. this.hasPlaybackControl = false;
  36315. this.sourceType = 'mediaNode';
  36316. this.source = this.context.createMediaElementSource( mediaElement );
  36317. this.connect();
  36318. return this;
  36319. }
  36320. /**
  36321. * Sets the given media stream as the source of this instance.
  36322. *
  36323. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36324. *
  36325. * @param {MediaStream} mediaStream - The media stream.
  36326. * @return {Audio} A reference to this instance.
  36327. */
  36328. setMediaStreamSource( mediaStream ) {
  36329. this.hasPlaybackControl = false;
  36330. this.sourceType = 'mediaStreamNode';
  36331. this.source = this.context.createMediaStreamSource( mediaStream );
  36332. this.connect();
  36333. return this;
  36334. }
  36335. /**
  36336. * Sets the given audio buffer as the source of this instance.
  36337. *
  36338. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36339. *
  36340. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36341. * @return {Audio} A reference to this instance.
  36342. */
  36343. setBuffer( audioBuffer ) {
  36344. this.buffer = audioBuffer;
  36345. this.sourceType = 'buffer';
  36346. if ( this.autoplay ) this.play();
  36347. return this;
  36348. }
  36349. /**
  36350. * Starts the playback of the audio.
  36351. *
  36352. * Can only be used with compatible audio sources that allow playback control.
  36353. *
  36354. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36355. * @return {Audio|undefined} A reference to this instance.
  36356. */
  36357. play( delay = 0 ) {
  36358. if ( this.isPlaying === true ) {
  36359. console.warn( 'THREE.Audio: Audio is already playing.' );
  36360. return;
  36361. }
  36362. if ( this.hasPlaybackControl === false ) {
  36363. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36364. return;
  36365. }
  36366. this._startedAt = this.context.currentTime + delay;
  36367. const source = this.context.createBufferSource();
  36368. source.buffer = this.buffer;
  36369. source.loop = this.loop;
  36370. source.loopStart = this.loopStart;
  36371. source.loopEnd = this.loopEnd;
  36372. source.onended = this.onEnded.bind( this );
  36373. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36374. this.isPlaying = true;
  36375. this.source = source;
  36376. this.setDetune( this.detune );
  36377. this.setPlaybackRate( this.playbackRate );
  36378. return this.connect();
  36379. }
  36380. /**
  36381. * Pauses the playback of the audio.
  36382. *
  36383. * Can only be used with compatible audio sources that allow playback control.
  36384. *
  36385. * @return {Audio|undefined} A reference to this instance.
  36386. */
  36387. pause() {
  36388. if ( this.hasPlaybackControl === false ) {
  36389. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36390. return;
  36391. }
  36392. if ( this.isPlaying === true ) {
  36393. // update current progress
  36394. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36395. if ( this.loop === true ) {
  36396. // ensure _progress does not exceed duration with looped audios
  36397. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36398. }
  36399. this.source.stop();
  36400. this.source.onended = null;
  36401. this.isPlaying = false;
  36402. }
  36403. return this;
  36404. }
  36405. /**
  36406. * Stops the playback of the audio.
  36407. *
  36408. * Can only be used with compatible audio sources that allow playback control.
  36409. *
  36410. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36411. * @return {Audio|undefined} A reference to this instance.
  36412. */
  36413. stop( delay = 0 ) {
  36414. if ( this.hasPlaybackControl === false ) {
  36415. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36416. return;
  36417. }
  36418. this._progress = 0;
  36419. if ( this.source !== null ) {
  36420. this.source.stop( this.context.currentTime + delay );
  36421. this.source.onended = null;
  36422. }
  36423. this.isPlaying = false;
  36424. return this;
  36425. }
  36426. /**
  36427. * Connects to the audio source. This is used internally on
  36428. * initialisation and when setting / removing filters.
  36429. *
  36430. * @return {Audio} A reference to this instance.
  36431. */
  36432. connect() {
  36433. if ( this.filters.length > 0 ) {
  36434. this.source.connect( this.filters[ 0 ] );
  36435. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36436. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36437. }
  36438. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36439. } else {
  36440. this.source.connect( this.getOutput() );
  36441. }
  36442. this._connected = true;
  36443. return this;
  36444. }
  36445. /**
  36446. * Disconnects to the audio source. This is used internally on
  36447. * initialisation and when setting / removing filters.
  36448. *
  36449. * @return {Audio|undefined} A reference to this instance.
  36450. */
  36451. disconnect() {
  36452. if ( this._connected === false ) {
  36453. return;
  36454. }
  36455. if ( this.filters.length > 0 ) {
  36456. this.source.disconnect( this.filters[ 0 ] );
  36457. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36458. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36459. }
  36460. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36461. } else {
  36462. this.source.disconnect( this.getOutput() );
  36463. }
  36464. this._connected = false;
  36465. return this;
  36466. }
  36467. /**
  36468. * Returns the current set filters.
  36469. *
  36470. * @return {Array<AudioNode>} The list of filters.
  36471. */
  36472. getFilters() {
  36473. return this.filters;
  36474. }
  36475. /**
  36476. * Sets an array of filters and connects them with the audio source.
  36477. *
  36478. * @param {Array<AudioNode>} [value] - A list of filters.
  36479. * @return {Audio} A reference to this instance.
  36480. */
  36481. setFilters( value ) {
  36482. if ( ! value ) value = [];
  36483. if ( this._connected === true ) {
  36484. this.disconnect();
  36485. this.filters = value.slice();
  36486. this.connect();
  36487. } else {
  36488. this.filters = value.slice();
  36489. }
  36490. return this;
  36491. }
  36492. /**
  36493. * Defines the detuning of oscillation in cents.
  36494. *
  36495. * @param {number} value - The detuning of oscillation in cents.
  36496. * @return {Audio} A reference to this instance.
  36497. */
  36498. setDetune( value ) {
  36499. this.detune = value;
  36500. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36501. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36502. }
  36503. return this;
  36504. }
  36505. /**
  36506. * Returns the detuning of oscillation in cents.
  36507. *
  36508. * @return {number} The detuning of oscillation in cents.
  36509. */
  36510. getDetune() {
  36511. return this.detune;
  36512. }
  36513. /**
  36514. * Returns the first filter in the list of filters.
  36515. *
  36516. * @return {AudioNode|undefined} The first filter in the list of filters.
  36517. */
  36518. getFilter() {
  36519. return this.getFilters()[ 0 ];
  36520. }
  36521. /**
  36522. * Applies a single filter node to the audio.
  36523. *
  36524. * @param {AudioNode} [filter] - The filter to set.
  36525. * @return {Audio} A reference to this instance.
  36526. */
  36527. setFilter( filter ) {
  36528. return this.setFilters( filter ? [ filter ] : [] );
  36529. }
  36530. /**
  36531. * Sets the playback rate.
  36532. *
  36533. * Can only be used with compatible audio sources that allow playback control.
  36534. *
  36535. * @param {number} [value] - The playback rate to set.
  36536. * @return {Audio|undefined} A reference to this instance.
  36537. */
  36538. setPlaybackRate( value ) {
  36539. if ( this.hasPlaybackControl === false ) {
  36540. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36541. return;
  36542. }
  36543. this.playbackRate = value;
  36544. if ( this.isPlaying === true ) {
  36545. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36546. }
  36547. return this;
  36548. }
  36549. /**
  36550. * Returns the current playback rate.
  36551. * @return {number} The playback rate.
  36552. */
  36553. getPlaybackRate() {
  36554. return this.playbackRate;
  36555. }
  36556. /**
  36557. * Automatically called when playback finished.
  36558. */
  36559. onEnded() {
  36560. this.isPlaying = false;
  36561. this._progress = 0;
  36562. }
  36563. /**
  36564. * Returns the loop flag.
  36565. *
  36566. * Can only be used with compatible audio sources that allow playback control.
  36567. *
  36568. * @return {boolean} Whether the audio should loop or not.
  36569. */
  36570. getLoop() {
  36571. if ( this.hasPlaybackControl === false ) {
  36572. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36573. return false;
  36574. }
  36575. return this.loop;
  36576. }
  36577. /**
  36578. * Sets the loop flag.
  36579. *
  36580. * Can only be used with compatible audio sources that allow playback control.
  36581. *
  36582. * @param {boolean} value - Whether the audio should loop or not.
  36583. * @return {Audio|undefined} A reference to this instance.
  36584. */
  36585. setLoop( value ) {
  36586. if ( this.hasPlaybackControl === false ) {
  36587. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  36588. return;
  36589. }
  36590. this.loop = value;
  36591. if ( this.isPlaying === true ) {
  36592. this.source.loop = this.loop;
  36593. }
  36594. return this;
  36595. }
  36596. /**
  36597. * Sets the loop start value which defines where in the audio buffer the replay should
  36598. * start, in seconds.
  36599. *
  36600. * @param {number} value - The loop start value.
  36601. * @return {Audio} A reference to this instance.
  36602. */
  36603. setLoopStart( value ) {
  36604. this.loopStart = value;
  36605. return this;
  36606. }
  36607. /**
  36608. * Sets the loop end value which defines where in the audio buffer the replay should
  36609. * stop, in seconds.
  36610. *
  36611. * @param {number} value - The loop end value.
  36612. * @return {Audio} A reference to this instance.
  36613. */
  36614. setLoopEnd( value ) {
  36615. this.loopEnd = value;
  36616. return this;
  36617. }
  36618. /**
  36619. * Returns the volume.
  36620. *
  36621. * @return {number} The volume.
  36622. */
  36623. getVolume() {
  36624. return this.gain.gain.value;
  36625. }
  36626. /**
  36627. * Sets the volume.
  36628. *
  36629. * @param {number} value - The volume to set.
  36630. * @return {Audio} A reference to this instance.
  36631. */
  36632. setVolume( value ) {
  36633. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36634. return this;
  36635. }
  36636. copy( source, recursive ) {
  36637. super.copy( source, recursive );
  36638. if ( source.sourceType !== 'buffer' ) {
  36639. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  36640. return this;
  36641. }
  36642. this.autoplay = source.autoplay;
  36643. this.buffer = source.buffer;
  36644. this.detune = source.detune;
  36645. this.loop = source.loop;
  36646. this.loopStart = source.loopStart;
  36647. this.loopEnd = source.loopEnd;
  36648. this.offset = source.offset;
  36649. this.duration = source.duration;
  36650. this.playbackRate = source.playbackRate;
  36651. this.hasPlaybackControl = source.hasPlaybackControl;
  36652. this.sourceType = source.sourceType;
  36653. this.filters = source.filters.slice();
  36654. return this;
  36655. }
  36656. clone( recursive ) {
  36657. return new this.constructor( this.listener ).copy( this, recursive );
  36658. }
  36659. }
  36660. const _position = /*@__PURE__*/ new Vector3();
  36661. const _quaternion = /*@__PURE__*/ new Quaternion();
  36662. const _scale = /*@__PURE__*/ new Vector3();
  36663. const _orientation = /*@__PURE__*/ new Vector3();
  36664. /**
  36665. * Represents a positional audio object.
  36666. *
  36667. * ```js
  36668. * // create an AudioListener and add it to the camera
  36669. * const listener = new THREE.AudioListener();
  36670. * camera.add( listener );
  36671. *
  36672. * // create the PositionalAudio object (passing in the listener)
  36673. * const sound = new THREE.PositionalAudio( listener );
  36674. *
  36675. * // load a sound and set it as the PositionalAudio object's buffer
  36676. * const audioLoader = new THREE.AudioLoader();
  36677. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36678. * sound.setBuffer( buffer );
  36679. * sound.setRefDistance( 20 );
  36680. * sound.play();
  36681. * });
  36682. *
  36683. * // create an object for the sound to play from
  36684. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36685. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36686. * const mesh = new THREE.Mesh( sphere, material );
  36687. * scene.add( mesh );
  36688. *
  36689. * // finally add the sound to the mesh
  36690. * mesh.add( sound );
  36691. *
  36692. * @augments Audio
  36693. */
  36694. class PositionalAudio extends Audio {
  36695. /**
  36696. * Constructs a positional audio.
  36697. *
  36698. * @param {AudioListener} listener - The global audio listener.
  36699. */
  36700. constructor( listener ) {
  36701. super( listener );
  36702. /**
  36703. * The panner node represents the location, direction, and behavior of an audio
  36704. * source in 3D space.
  36705. *
  36706. * @type {PannerNode}
  36707. * @readonly
  36708. */
  36709. this.panner = this.context.createPanner();
  36710. this.panner.panningModel = 'HRTF';
  36711. this.panner.connect( this.gain );
  36712. }
  36713. connect() {
  36714. super.connect();
  36715. this.panner.connect( this.gain );
  36716. return this;
  36717. }
  36718. disconnect() {
  36719. super.disconnect();
  36720. this.panner.disconnect( this.gain );
  36721. return this;
  36722. }
  36723. getOutput() {
  36724. return this.panner;
  36725. }
  36726. /**
  36727. * Returns the current reference distance.
  36728. *
  36729. * @return {number} The reference distance.
  36730. */
  36731. getRefDistance() {
  36732. return this.panner.refDistance;
  36733. }
  36734. /**
  36735. * Defines the reference distance for reducing volume as the audio source moves
  36736. * further from the listener – i.e. the distance at which the volume reduction
  36737. * starts taking effect.
  36738. *
  36739. * @param {number} value - The reference distance to set.
  36740. * @return {PositionalAudio} A reference to this instance.
  36741. */
  36742. setRefDistance( value ) {
  36743. this.panner.refDistance = value;
  36744. return this;
  36745. }
  36746. /**
  36747. * Returns the current rolloff factor.
  36748. *
  36749. * @return {number} The rolloff factor.
  36750. */
  36751. getRolloffFactor() {
  36752. return this.panner.rolloffFactor;
  36753. }
  36754. /**
  36755. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36756. *
  36757. * @param {number} value - The rolloff factor.
  36758. * @return {PositionalAudio} A reference to this instance.
  36759. */
  36760. setRolloffFactor( value ) {
  36761. this.panner.rolloffFactor = value;
  36762. return this;
  36763. }
  36764. /**
  36765. * Returns the current distance model.
  36766. *
  36767. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36768. */
  36769. getDistanceModel() {
  36770. return this.panner.distanceModel;
  36771. }
  36772. /**
  36773. * Defines which algorithm to use to reduce the volume of the audio source
  36774. * as it moves away from the listener.
  36775. *
  36776. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36777. * for more details.
  36778. *
  36779. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36780. * @return {PositionalAudio} A reference to this instance.
  36781. */
  36782. setDistanceModel( value ) {
  36783. this.panner.distanceModel = value;
  36784. return this;
  36785. }
  36786. /**
  36787. * Returns the current max distance.
  36788. *
  36789. * @return {number} The max distance.
  36790. */
  36791. getMaxDistance() {
  36792. return this.panner.maxDistance;
  36793. }
  36794. /**
  36795. * Defines the maximum distance between the audio source and the listener,
  36796. * after which the volume is not reduced any further.
  36797. *
  36798. * This value is used only by the `linear` distance model.
  36799. *
  36800. * @param {number} value - The max distance.
  36801. * @return {PositionalAudio} A reference to this instance.
  36802. */
  36803. setMaxDistance( value ) {
  36804. this.panner.maxDistance = value;
  36805. return this;
  36806. }
  36807. /**
  36808. * Sets the directional cone in which the audio can be listened.
  36809. *
  36810. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36811. * @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.
  36812. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36813. * @return {PositionalAudio} A reference to this instance.
  36814. */
  36815. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36816. this.panner.coneInnerAngle = coneInnerAngle;
  36817. this.panner.coneOuterAngle = coneOuterAngle;
  36818. this.panner.coneOuterGain = coneOuterGain;
  36819. return this;
  36820. }
  36821. updateMatrixWorld( force ) {
  36822. super.updateMatrixWorld( force );
  36823. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36824. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36825. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36826. const panner = this.panner;
  36827. if ( panner.positionX ) {
  36828. // code path for Chrome and Firefox (see #14393)
  36829. const endTime = this.context.currentTime + this.listener.timeDelta;
  36830. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36831. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36832. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36833. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36834. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36835. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36836. } else {
  36837. panner.setPosition( _position.x, _position.y, _position.z );
  36838. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36839. }
  36840. }
  36841. }
  36842. /**
  36843. * This class can be used to analyse audio data.
  36844. *
  36845. * ```js
  36846. * // create an AudioListener and add it to the camera
  36847. * const listener = new THREE.AudioListener();
  36848. * camera.add( listener );
  36849. *
  36850. * // create an Audio source
  36851. * const sound = new THREE.Audio( listener );
  36852. *
  36853. * // load a sound and set it as the Audio object's buffer
  36854. * const audioLoader = new THREE.AudioLoader();
  36855. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36856. * sound.setBuffer( buffer );
  36857. * sound.setLoop(true);
  36858. * sound.setVolume(0.5);
  36859. * sound.play();
  36860. * });
  36861. *
  36862. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36863. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36864. *
  36865. * // get the average frequency of the sound
  36866. * const data = analyser.getAverageFrequency();
  36867. * ```
  36868. */
  36869. class AudioAnalyser {
  36870. /**
  36871. * Constructs a new audio analyzer.
  36872. *
  36873. * @param {Audio} audio - The audio to analyze.
  36874. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36875. */
  36876. constructor( audio, fftSize = 2048 ) {
  36877. /**
  36878. * The global audio listener.
  36879. *
  36880. * @type {AnalyserNode}
  36881. */
  36882. this.analyser = audio.context.createAnalyser();
  36883. this.analyser.fftSize = fftSize;
  36884. /**
  36885. * Holds the analyzed data.
  36886. *
  36887. * @type {Uint8Array}
  36888. */
  36889. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  36890. audio.getOutput().connect( this.analyser );
  36891. }
  36892. /**
  36893. * Returns an array with frequency data of the audio.
  36894. *
  36895. * Each item in the array represents the decibel value for a specific frequency.
  36896. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  36897. * For example, for 48000 sample rate, the last item of the array will represent
  36898. * the decibel value for 24000 Hz.
  36899. *
  36900. * @return {Uint8Array} The frequency data.
  36901. */
  36902. getFrequencyData() {
  36903. this.analyser.getByteFrequencyData( this.data );
  36904. return this.data;
  36905. }
  36906. /**
  36907. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  36908. *
  36909. * @return {number} The average frequency.
  36910. */
  36911. getAverageFrequency() {
  36912. let value = 0;
  36913. const data = this.getFrequencyData();
  36914. for ( let i = 0; i < data.length; i ++ ) {
  36915. value += data[ i ];
  36916. }
  36917. return value / data.length;
  36918. }
  36919. }
  36920. /**
  36921. * Buffered scene graph property that allows weighted accumulation; used internally.
  36922. */
  36923. class PropertyMixer {
  36924. /**
  36925. * Constructs a new property mixer.
  36926. *
  36927. * @param {PropertyBinding} binding - The property binding.
  36928. * @param {string} typeName - The keyframe track type name.
  36929. * @param {number} valueSize - The keyframe track value size.
  36930. */
  36931. constructor( binding, typeName, valueSize ) {
  36932. /**
  36933. * The property binding.
  36934. *
  36935. * @type {PropertyBinding}
  36936. */
  36937. this.binding = binding;
  36938. /**
  36939. * The keyframe track value size.
  36940. *
  36941. * @type {number}
  36942. */
  36943. this.valueSize = valueSize;
  36944. let mixFunction,
  36945. mixFunctionAdditive,
  36946. setIdentity;
  36947. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  36948. //
  36949. // interpolators can use .buffer as their .result
  36950. // the data then goes to 'incoming'
  36951. //
  36952. // 'accu0' and 'accu1' are used frame-interleaved for
  36953. // the cumulative result and are compared to detect
  36954. // changes
  36955. //
  36956. // 'orig' stores the original state of the property
  36957. //
  36958. // 'add' is used for additive cumulative results
  36959. //
  36960. // 'work' is optional and is only present for quaternion types. It is used
  36961. // to store intermediate quaternion multiplication results
  36962. switch ( typeName ) {
  36963. case 'quaternion':
  36964. mixFunction = this._slerp;
  36965. mixFunctionAdditive = this._slerpAdditive;
  36966. setIdentity = this._setAdditiveIdentityQuaternion;
  36967. this.buffer = new Float64Array( valueSize * 6 );
  36968. this._workIndex = 5;
  36969. break;
  36970. case 'string':
  36971. case 'bool':
  36972. mixFunction = this._select;
  36973. // Use the regular mix function and for additive on these types,
  36974. // additive is not relevant for non-numeric types
  36975. mixFunctionAdditive = this._select;
  36976. setIdentity = this._setAdditiveIdentityOther;
  36977. this.buffer = new Array( valueSize * 5 );
  36978. break;
  36979. default:
  36980. mixFunction = this._lerp;
  36981. mixFunctionAdditive = this._lerpAdditive;
  36982. setIdentity = this._setAdditiveIdentityNumeric;
  36983. this.buffer = new Float64Array( valueSize * 5 );
  36984. }
  36985. this._mixBufferRegion = mixFunction;
  36986. this._mixBufferRegionAdditive = mixFunctionAdditive;
  36987. this._setIdentity = setIdentity;
  36988. this._origIndex = 3;
  36989. this._addIndex = 4;
  36990. /**
  36991. * TODO
  36992. *
  36993. * @type {number}
  36994. * @default 0
  36995. */
  36996. this.cumulativeWeight = 0;
  36997. /**
  36998. * TODO
  36999. *
  37000. * @type {number}
  37001. * @default 0
  37002. */
  37003. this.cumulativeWeightAdditive = 0;
  37004. /**
  37005. * TODO
  37006. *
  37007. * @type {number}
  37008. * @default 0
  37009. */
  37010. this.useCount = 0;
  37011. /**
  37012. * TODO
  37013. *
  37014. * @type {number}
  37015. * @default 0
  37016. */
  37017. this.referenceCount = 0;
  37018. }
  37019. /**
  37020. * Accumulates data in the `incoming` region into `accu<i>`.
  37021. *
  37022. * @param {number} accuIndex - The accumulation index.
  37023. * @param {number} weight - The weight.
  37024. */
  37025. accumulate( accuIndex, weight ) {
  37026. // note: happily accumulating nothing when weight = 0, the caller knows
  37027. // the weight and shouldn't have made the call in the first place
  37028. const buffer = this.buffer,
  37029. stride = this.valueSize,
  37030. offset = accuIndex * stride + stride;
  37031. let currentWeight = this.cumulativeWeight;
  37032. if ( currentWeight === 0 ) {
  37033. // accuN := incoming * weight
  37034. for ( let i = 0; i !== stride; ++ i ) {
  37035. buffer[ offset + i ] = buffer[ i ];
  37036. }
  37037. currentWeight = weight;
  37038. } else {
  37039. // accuN := accuN + incoming * weight
  37040. currentWeight += weight;
  37041. const mix = weight / currentWeight;
  37042. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37043. }
  37044. this.cumulativeWeight = currentWeight;
  37045. }
  37046. /**
  37047. * Accumulates data in the `incoming` region into `add`.
  37048. *
  37049. * @param {number} weight - The weight.
  37050. */
  37051. accumulateAdditive( weight ) {
  37052. const buffer = this.buffer,
  37053. stride = this.valueSize,
  37054. offset = stride * this._addIndex;
  37055. if ( this.cumulativeWeightAdditive === 0 ) {
  37056. // add = identity
  37057. this._setIdentity();
  37058. }
  37059. // add := add + incoming * weight
  37060. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37061. this.cumulativeWeightAdditive += weight;
  37062. }
  37063. /**
  37064. * Applies the state of `accu<i>` to the binding when accus differ.
  37065. *
  37066. * @param {number} accuIndex - The accumulation index.
  37067. */
  37068. apply( accuIndex ) {
  37069. const stride = this.valueSize,
  37070. buffer = this.buffer,
  37071. offset = accuIndex * stride + stride,
  37072. weight = this.cumulativeWeight,
  37073. weightAdditive = this.cumulativeWeightAdditive,
  37074. binding = this.binding;
  37075. this.cumulativeWeight = 0;
  37076. this.cumulativeWeightAdditive = 0;
  37077. if ( weight < 1 ) {
  37078. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37079. const originalValueOffset = stride * this._origIndex;
  37080. this._mixBufferRegion(
  37081. buffer, offset, originalValueOffset, 1 - weight, stride );
  37082. }
  37083. if ( weightAdditive > 0 ) {
  37084. // accuN := accuN + additive accuN
  37085. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37086. }
  37087. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37088. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37089. // value has changed -> update scene graph
  37090. binding.setValue( buffer, offset );
  37091. break;
  37092. }
  37093. }
  37094. }
  37095. /**
  37096. * Remembers the state of the bound property and copy it to both accus.
  37097. */
  37098. saveOriginalState() {
  37099. const binding = this.binding;
  37100. const buffer = this.buffer,
  37101. stride = this.valueSize,
  37102. originalValueOffset = stride * this._origIndex;
  37103. binding.getValue( buffer, originalValueOffset );
  37104. // accu[0..1] := orig -- initially detect changes against the original
  37105. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37106. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37107. }
  37108. // Add to identity for additive
  37109. this._setIdentity();
  37110. this.cumulativeWeight = 0;
  37111. this.cumulativeWeightAdditive = 0;
  37112. }
  37113. /**
  37114. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37115. */
  37116. restoreOriginalState() {
  37117. const originalValueOffset = this.valueSize * 3;
  37118. this.binding.setValue( this.buffer, originalValueOffset );
  37119. }
  37120. // internals
  37121. _setAdditiveIdentityNumeric() {
  37122. const startIndex = this._addIndex * this.valueSize;
  37123. const endIndex = startIndex + this.valueSize;
  37124. for ( let i = startIndex; i < endIndex; i ++ ) {
  37125. this.buffer[ i ] = 0;
  37126. }
  37127. }
  37128. _setAdditiveIdentityQuaternion() {
  37129. this._setAdditiveIdentityNumeric();
  37130. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37131. }
  37132. _setAdditiveIdentityOther() {
  37133. const startIndex = this._origIndex * this.valueSize;
  37134. const targetIndex = this._addIndex * this.valueSize;
  37135. for ( let i = 0; i < this.valueSize; i ++ ) {
  37136. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37137. }
  37138. }
  37139. // mix functions
  37140. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37141. if ( t >= 0.5 ) {
  37142. for ( let i = 0; i !== stride; ++ i ) {
  37143. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37144. }
  37145. }
  37146. }
  37147. _slerp( buffer, dstOffset, srcOffset, t ) {
  37148. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37149. }
  37150. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37151. const workOffset = this._workIndex * stride;
  37152. // Store result in intermediate buffer offset
  37153. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37154. // Slerp to the intermediate result
  37155. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37156. }
  37157. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37158. const s = 1 - t;
  37159. for ( let i = 0; i !== stride; ++ i ) {
  37160. const j = dstOffset + i;
  37161. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37162. }
  37163. }
  37164. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37165. for ( let i = 0; i !== stride; ++ i ) {
  37166. const j = dstOffset + i;
  37167. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37168. }
  37169. }
  37170. }
  37171. // Characters [].:/ are reserved for track binding syntax.
  37172. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37173. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37174. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37175. // only latin characters, and the unicode \p{L} is not yet supported. So
  37176. // instead, we exclude reserved characters and match everything else.
  37177. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37178. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37179. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37180. // be matched to parse the rest of the track name.
  37181. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37182. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37183. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37184. // Object on target node, and accessor. May not contain reserved
  37185. // characters. Accessor may contain any character except closing bracket.
  37186. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37187. // Property and accessor. May not contain reserved characters. Accessor may
  37188. // contain any non-bracket characters.
  37189. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37190. const _trackRe = new RegExp( ''
  37191. + '^'
  37192. + _directoryRe
  37193. + _nodeRe
  37194. + _objectRe
  37195. + _propertyRe
  37196. + '$'
  37197. );
  37198. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37199. class Composite {
  37200. constructor( targetGroup, path, optionalParsedPath ) {
  37201. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37202. this._targetGroup = targetGroup;
  37203. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37204. }
  37205. getValue( array, offset ) {
  37206. this.bind(); // bind all binding
  37207. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37208. binding = this._bindings[ firstValidIndex ];
  37209. // and only call .getValue on the first
  37210. if ( binding !== undefined ) binding.getValue( array, offset );
  37211. }
  37212. setValue( array, offset ) {
  37213. const bindings = this._bindings;
  37214. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37215. bindings[ i ].setValue( array, offset );
  37216. }
  37217. }
  37218. bind() {
  37219. const bindings = this._bindings;
  37220. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37221. bindings[ i ].bind();
  37222. }
  37223. }
  37224. unbind() {
  37225. const bindings = this._bindings;
  37226. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37227. bindings[ i ].unbind();
  37228. }
  37229. }
  37230. }
  37231. // Note: This class uses a State pattern on a per-method basis:
  37232. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37233. // prototype version of these methods with one that represents
  37234. // the bound state. When the property is not found, the methods
  37235. // become no-ops.
  37236. /**
  37237. * This holds a reference to a real property in the scene graph; used internally.
  37238. */
  37239. class PropertyBinding {
  37240. /**
  37241. * Constructs a new property binding.
  37242. *
  37243. * @param {Object} rootNode - The root node.
  37244. * @param {string} path - The path.
  37245. * @param {?Object} [parsedPath] - The parsed path.
  37246. */
  37247. constructor( rootNode, path, parsedPath ) {
  37248. /**
  37249. * The object path to the animated property.
  37250. *
  37251. * @type {string}
  37252. */
  37253. this.path = path;
  37254. /**
  37255. * An object holding information about the path.
  37256. *
  37257. * @type {Object}
  37258. */
  37259. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37260. /**
  37261. * The object owns the animated property.
  37262. *
  37263. * @type {?Object}
  37264. */
  37265. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37266. /**
  37267. * The root node.
  37268. *
  37269. * @type {Object3D|Skeleton}
  37270. */
  37271. this.rootNode = rootNode;
  37272. // initial state of these methods that calls 'bind'
  37273. this.getValue = this._getValue_unbound;
  37274. this.setValue = this._setValue_unbound;
  37275. }
  37276. /**
  37277. * Factory method for creating a property binding from the given parameters.
  37278. *
  37279. * @static
  37280. * @param {Object} root - The root node.
  37281. * @param {string} path - The path.
  37282. * @param {?Object} [parsedPath] - The parsed path.
  37283. * @return {PropertyBinding|Composite} The created property binding or composite.
  37284. */
  37285. static create( root, path, parsedPath ) {
  37286. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37287. return new PropertyBinding( root, path, parsedPath );
  37288. } else {
  37289. return new PropertyBinding.Composite( root, path, parsedPath );
  37290. }
  37291. }
  37292. /**
  37293. * Replaces spaces with underscores and removes unsupported characters from
  37294. * node names, to ensure compatibility with parseTrackName().
  37295. *
  37296. * @param {string} name - Node name to be sanitized.
  37297. * @return {string} The sanitized node name.
  37298. */
  37299. static sanitizeNodeName( name ) {
  37300. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37301. }
  37302. /**
  37303. * Parses the given track name (an object path to an animated property) and
  37304. * returns an object with information about the path. Matches strings in the following forms:
  37305. *
  37306. * - nodeName.property
  37307. * - nodeName.property[accessor]
  37308. * - nodeName.material.property[accessor]
  37309. * - uuid.property[accessor]
  37310. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37311. * - parentName/nodeName.property
  37312. * - parentName/parentName/nodeName.property[index]
  37313. * - .bone[Armature.DEF_cog].position
  37314. * - scene:helium_balloon_model:helium_balloon_model.position
  37315. *
  37316. * @static
  37317. * @param {string} trackName - The track name to parse.
  37318. * @return {Object} The parsed track name as an object.
  37319. */
  37320. static parseTrackName( trackName ) {
  37321. const matches = _trackRe.exec( trackName );
  37322. if ( matches === null ) {
  37323. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37324. }
  37325. const results = {
  37326. // directoryName: matches[ 1 ], // (tschw) currently unused
  37327. nodeName: matches[ 2 ],
  37328. objectName: matches[ 3 ],
  37329. objectIndex: matches[ 4 ],
  37330. propertyName: matches[ 5 ], // required
  37331. propertyIndex: matches[ 6 ]
  37332. };
  37333. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37334. if ( lastDot !== undefined && lastDot !== -1 ) {
  37335. const objectName = results.nodeName.substring( lastDot + 1 );
  37336. // Object names must be checked against an allowlist. Otherwise, there
  37337. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37338. // 'bar' could be the objectName, or part of a nodeName (which can
  37339. // include '.' characters).
  37340. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37341. results.nodeName = results.nodeName.substring( 0, lastDot );
  37342. results.objectName = objectName;
  37343. }
  37344. }
  37345. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37346. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37347. }
  37348. return results;
  37349. }
  37350. /**
  37351. * Searches for a node in the hierarchy of the given root object by the given
  37352. * node name.
  37353. *
  37354. * @static
  37355. * @param {Object} root - The root object.
  37356. * @param {string|number} nodeName - The name of the node.
  37357. * @return {?Object} The found node. Returns `null` if no object was found.
  37358. */
  37359. static findNode( root, nodeName ) {
  37360. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37361. return root;
  37362. }
  37363. // search into skeleton bones.
  37364. if ( root.skeleton ) {
  37365. const bone = root.skeleton.getBoneByName( nodeName );
  37366. if ( bone !== undefined ) {
  37367. return bone;
  37368. }
  37369. }
  37370. // search into node subtree.
  37371. if ( root.children ) {
  37372. const searchNodeSubtree = function ( children ) {
  37373. for ( let i = 0; i < children.length; i ++ ) {
  37374. const childNode = children[ i ];
  37375. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37376. return childNode;
  37377. }
  37378. const result = searchNodeSubtree( childNode.children );
  37379. if ( result ) return result;
  37380. }
  37381. return null;
  37382. };
  37383. const subTreeNode = searchNodeSubtree( root.children );
  37384. if ( subTreeNode ) {
  37385. return subTreeNode;
  37386. }
  37387. }
  37388. return null;
  37389. }
  37390. // these are used to "bind" a nonexistent property
  37391. _getValue_unavailable() {}
  37392. _setValue_unavailable() {}
  37393. // Getters
  37394. _getValue_direct( buffer, offset ) {
  37395. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37396. }
  37397. _getValue_array( buffer, offset ) {
  37398. const source = this.resolvedProperty;
  37399. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37400. buffer[ offset ++ ] = source[ i ];
  37401. }
  37402. }
  37403. _getValue_arrayElement( buffer, offset ) {
  37404. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37405. }
  37406. _getValue_toArray( buffer, offset ) {
  37407. this.resolvedProperty.toArray( buffer, offset );
  37408. }
  37409. // Direct
  37410. _setValue_direct( buffer, offset ) {
  37411. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37412. }
  37413. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37414. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37415. this.targetObject.needsUpdate = true;
  37416. }
  37417. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37418. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37419. this.targetObject.matrixWorldNeedsUpdate = true;
  37420. }
  37421. // EntireArray
  37422. _setValue_array( buffer, offset ) {
  37423. const dest = this.resolvedProperty;
  37424. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37425. dest[ i ] = buffer[ offset ++ ];
  37426. }
  37427. }
  37428. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37429. const dest = this.resolvedProperty;
  37430. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37431. dest[ i ] = buffer[ offset ++ ];
  37432. }
  37433. this.targetObject.needsUpdate = true;
  37434. }
  37435. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37436. const dest = this.resolvedProperty;
  37437. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37438. dest[ i ] = buffer[ offset ++ ];
  37439. }
  37440. this.targetObject.matrixWorldNeedsUpdate = true;
  37441. }
  37442. // ArrayElement
  37443. _setValue_arrayElement( buffer, offset ) {
  37444. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37445. }
  37446. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37447. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37448. this.targetObject.needsUpdate = true;
  37449. }
  37450. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37451. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37452. this.targetObject.matrixWorldNeedsUpdate = true;
  37453. }
  37454. // HasToFromArray
  37455. _setValue_fromArray( buffer, offset ) {
  37456. this.resolvedProperty.fromArray( buffer, offset );
  37457. }
  37458. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37459. this.resolvedProperty.fromArray( buffer, offset );
  37460. this.targetObject.needsUpdate = true;
  37461. }
  37462. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37463. this.resolvedProperty.fromArray( buffer, offset );
  37464. this.targetObject.matrixWorldNeedsUpdate = true;
  37465. }
  37466. _getValue_unbound( targetArray, offset ) {
  37467. this.bind();
  37468. this.getValue( targetArray, offset );
  37469. }
  37470. _setValue_unbound( sourceArray, offset ) {
  37471. this.bind();
  37472. this.setValue( sourceArray, offset );
  37473. }
  37474. /**
  37475. * Creates a getter / setter pair for the property tracked by this binding.
  37476. */
  37477. bind() {
  37478. let targetObject = this.node;
  37479. const parsedPath = this.parsedPath;
  37480. const objectName = parsedPath.objectName;
  37481. const propertyName = parsedPath.propertyName;
  37482. let propertyIndex = parsedPath.propertyIndex;
  37483. if ( ! targetObject ) {
  37484. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37485. this.node = targetObject;
  37486. }
  37487. // set fail state so we can just 'return' on error
  37488. this.getValue = this._getValue_unavailable;
  37489. this.setValue = this._setValue_unavailable;
  37490. // ensure there is a value node
  37491. if ( ! targetObject ) {
  37492. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  37493. return;
  37494. }
  37495. if ( objectName ) {
  37496. let objectIndex = parsedPath.objectIndex;
  37497. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37498. switch ( objectName ) {
  37499. case 'materials':
  37500. if ( ! targetObject.material ) {
  37501. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37502. return;
  37503. }
  37504. if ( ! targetObject.material.materials ) {
  37505. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37506. return;
  37507. }
  37508. targetObject = targetObject.material.materials;
  37509. break;
  37510. case 'bones':
  37511. if ( ! targetObject.skeleton ) {
  37512. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37513. return;
  37514. }
  37515. // potential future optimization: skip this if propertyIndex is already an integer
  37516. // and convert the integer string to a true integer.
  37517. targetObject = targetObject.skeleton.bones;
  37518. // support resolving morphTarget names into indices.
  37519. for ( let i = 0; i < targetObject.length; i ++ ) {
  37520. if ( targetObject[ i ].name === objectIndex ) {
  37521. objectIndex = i;
  37522. break;
  37523. }
  37524. }
  37525. break;
  37526. case 'map':
  37527. if ( 'map' in targetObject ) {
  37528. targetObject = targetObject.map;
  37529. break;
  37530. }
  37531. if ( ! targetObject.material ) {
  37532. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  37533. return;
  37534. }
  37535. if ( ! targetObject.material.map ) {
  37536. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37537. return;
  37538. }
  37539. targetObject = targetObject.material.map;
  37540. break;
  37541. default:
  37542. if ( targetObject[ objectName ] === undefined ) {
  37543. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  37544. return;
  37545. }
  37546. targetObject = targetObject[ objectName ];
  37547. }
  37548. if ( objectIndex !== undefined ) {
  37549. if ( targetObject[ objectIndex ] === undefined ) {
  37550. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37551. return;
  37552. }
  37553. targetObject = targetObject[ objectIndex ];
  37554. }
  37555. }
  37556. // resolve property
  37557. const nodeProperty = targetObject[ propertyName ];
  37558. if ( nodeProperty === undefined ) {
  37559. const nodeName = parsedPath.nodeName;
  37560. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  37561. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37562. return;
  37563. }
  37564. // determine versioning scheme
  37565. let versioning = this.Versioning.None;
  37566. this.targetObject = targetObject;
  37567. if ( targetObject.isMaterial === true ) {
  37568. versioning = this.Versioning.NeedsUpdate;
  37569. } else if ( targetObject.isObject3D === true ) {
  37570. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37571. }
  37572. // determine how the property gets bound
  37573. let bindingType = this.BindingType.Direct;
  37574. if ( propertyIndex !== undefined ) {
  37575. // access a sub element of the property array (only primitives are supported right now)
  37576. if ( propertyName === 'morphTargetInfluences' ) {
  37577. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37578. // support resolving morphTarget names into indices.
  37579. if ( ! targetObject.geometry ) {
  37580. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37581. return;
  37582. }
  37583. if ( ! targetObject.geometry.morphAttributes ) {
  37584. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37585. return;
  37586. }
  37587. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37588. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37589. }
  37590. }
  37591. bindingType = this.BindingType.ArrayElement;
  37592. this.resolvedProperty = nodeProperty;
  37593. this.propertyIndex = propertyIndex;
  37594. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37595. // must use copy for Object3D.Euler/Quaternion
  37596. bindingType = this.BindingType.HasFromToArray;
  37597. this.resolvedProperty = nodeProperty;
  37598. } else if ( Array.isArray( nodeProperty ) ) {
  37599. bindingType = this.BindingType.EntireArray;
  37600. this.resolvedProperty = nodeProperty;
  37601. } else {
  37602. this.propertyName = propertyName;
  37603. }
  37604. // select getter / setter
  37605. this.getValue = this.GetterByBindingType[ bindingType ];
  37606. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37607. }
  37608. /**
  37609. * Unbinds the property.
  37610. */
  37611. unbind() {
  37612. this.node = null;
  37613. // back to the prototype version of getValue / setValue
  37614. // note: avoiding to mutate the shape of 'this' via 'delete'
  37615. this.getValue = this._getValue_unbound;
  37616. this.setValue = this._setValue_unbound;
  37617. }
  37618. }
  37619. PropertyBinding.Composite = Composite;
  37620. PropertyBinding.prototype.BindingType = {
  37621. Direct: 0,
  37622. EntireArray: 1,
  37623. ArrayElement: 2,
  37624. HasFromToArray: 3
  37625. };
  37626. PropertyBinding.prototype.Versioning = {
  37627. None: 0,
  37628. NeedsUpdate: 1,
  37629. MatrixWorldNeedsUpdate: 2
  37630. };
  37631. PropertyBinding.prototype.GetterByBindingType = [
  37632. PropertyBinding.prototype._getValue_direct,
  37633. PropertyBinding.prototype._getValue_array,
  37634. PropertyBinding.prototype._getValue_arrayElement,
  37635. PropertyBinding.prototype._getValue_toArray,
  37636. ];
  37637. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37638. [
  37639. // Direct
  37640. PropertyBinding.prototype._setValue_direct,
  37641. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37642. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37643. ], [
  37644. // EntireArray
  37645. PropertyBinding.prototype._setValue_array,
  37646. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37647. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37648. ], [
  37649. // ArrayElement
  37650. PropertyBinding.prototype._setValue_arrayElement,
  37651. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37652. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37653. ], [
  37654. // HasToFromArray
  37655. PropertyBinding.prototype._setValue_fromArray,
  37656. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37657. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37658. ]
  37659. ];
  37660. /**
  37661. * A group of objects that receives a shared animation state.
  37662. *
  37663. * Usage:
  37664. *
  37665. * - Add objects you would otherwise pass as 'root' to the
  37666. * constructor or the .clipAction method of AnimationMixer.
  37667. * - Instead pass this object as 'root'.
  37668. * - You can also add and remove objects later when the mixer is running.
  37669. *
  37670. * Note:
  37671. *
  37672. * - Objects of this class appear as one object to the mixer,
  37673. * so cache control of the individual objects must be done on the group.
  37674. *
  37675. * Limitation:
  37676. *
  37677. * - The animated properties must be compatible among the all objects in the group.
  37678. * - A single property can either be controlled through a target group or directly, but not both.
  37679. */
  37680. class AnimationObjectGroup {
  37681. /**
  37682. * Constructs a new animation group.
  37683. *
  37684. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37685. */
  37686. constructor() {
  37687. /**
  37688. * This flag can be used for type testing.
  37689. *
  37690. * @type {boolean}
  37691. * @readonly
  37692. * @default true
  37693. */
  37694. this.isAnimationObjectGroup = true;
  37695. /**
  37696. * The UUID of the 3D object.
  37697. *
  37698. * @type {string}
  37699. * @readonly
  37700. */
  37701. this.uuid = generateUUID();
  37702. // cached objects followed by the active ones
  37703. this._objects = Array.prototype.slice.call( arguments );
  37704. this.nCachedObjects_ = 0; // threshold
  37705. // note: read by PropertyBinding.Composite
  37706. const indices = {};
  37707. this._indicesByUUID = indices; // for bookkeeping
  37708. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37709. indices[ arguments[ i ].uuid ] = i;
  37710. }
  37711. this._paths = []; // inside: string
  37712. this._parsedPaths = []; // inside: { we don't care, here }
  37713. this._bindings = []; // inside: Array< PropertyBinding >
  37714. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37715. const scope = this;
  37716. this.stats = {
  37717. objects: {
  37718. get total() {
  37719. return scope._objects.length;
  37720. },
  37721. get inUse() {
  37722. return this.total - scope.nCachedObjects_;
  37723. }
  37724. },
  37725. get bindingsPerObject() {
  37726. return scope._bindings.length;
  37727. }
  37728. };
  37729. }
  37730. /**
  37731. * Adds an arbitrary number of objects to this animation group.
  37732. *
  37733. * @param {...Object3D} arguments - The 3D objects to add.
  37734. */
  37735. add() {
  37736. const objects = this._objects,
  37737. indicesByUUID = this._indicesByUUID,
  37738. paths = this._paths,
  37739. parsedPaths = this._parsedPaths,
  37740. bindings = this._bindings,
  37741. nBindings = bindings.length;
  37742. let knownObject = undefined,
  37743. nObjects = objects.length,
  37744. nCachedObjects = this.nCachedObjects_;
  37745. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37746. const object = arguments[ i ],
  37747. uuid = object.uuid;
  37748. let index = indicesByUUID[ uuid ];
  37749. if ( index === undefined ) {
  37750. // unknown object -> add it to the ACTIVE region
  37751. index = nObjects ++;
  37752. indicesByUUID[ uuid ] = index;
  37753. objects.push( object );
  37754. // accounting is done, now do the same for all bindings
  37755. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37756. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37757. }
  37758. } else if ( index < nCachedObjects ) {
  37759. knownObject = objects[ index ];
  37760. // move existing object to the ACTIVE region
  37761. const firstActiveIndex = -- nCachedObjects,
  37762. lastCachedObject = objects[ firstActiveIndex ];
  37763. indicesByUUID[ lastCachedObject.uuid ] = index;
  37764. objects[ index ] = lastCachedObject;
  37765. indicesByUUID[ uuid ] = firstActiveIndex;
  37766. objects[ firstActiveIndex ] = object;
  37767. // accounting is done, now do the same for all bindings
  37768. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37769. const bindingsForPath = bindings[ j ],
  37770. lastCached = bindingsForPath[ firstActiveIndex ];
  37771. let binding = bindingsForPath[ index ];
  37772. bindingsForPath[ index ] = lastCached;
  37773. if ( binding === undefined ) {
  37774. // since we do not bother to create new bindings
  37775. // for objects that are cached, the binding may
  37776. // or may not exist
  37777. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37778. }
  37779. bindingsForPath[ firstActiveIndex ] = binding;
  37780. }
  37781. } else if ( objects[ index ] !== knownObject ) {
  37782. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  37783. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37784. } // else the object is already where we want it to be
  37785. } // for arguments
  37786. this.nCachedObjects_ = nCachedObjects;
  37787. }
  37788. /**
  37789. * Removes an arbitrary number of objects to this animation group
  37790. *
  37791. * @param {...Object3D} arguments - The 3D objects to remove.
  37792. */
  37793. remove() {
  37794. const objects = this._objects,
  37795. indicesByUUID = this._indicesByUUID,
  37796. bindings = this._bindings,
  37797. nBindings = bindings.length;
  37798. let nCachedObjects = this.nCachedObjects_;
  37799. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37800. const object = arguments[ i ],
  37801. uuid = object.uuid,
  37802. index = indicesByUUID[ uuid ];
  37803. if ( index !== undefined && index >= nCachedObjects ) {
  37804. // move existing object into the CACHED region
  37805. const lastCachedIndex = nCachedObjects ++,
  37806. firstActiveObject = objects[ lastCachedIndex ];
  37807. indicesByUUID[ firstActiveObject.uuid ] = index;
  37808. objects[ index ] = firstActiveObject;
  37809. indicesByUUID[ uuid ] = lastCachedIndex;
  37810. objects[ lastCachedIndex ] = object;
  37811. // accounting is done, now do the same for all bindings
  37812. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37813. const bindingsForPath = bindings[ j ],
  37814. firstActive = bindingsForPath[ lastCachedIndex ],
  37815. binding = bindingsForPath[ index ];
  37816. bindingsForPath[ index ] = firstActive;
  37817. bindingsForPath[ lastCachedIndex ] = binding;
  37818. }
  37819. }
  37820. } // for arguments
  37821. this.nCachedObjects_ = nCachedObjects;
  37822. }
  37823. /**
  37824. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37825. *
  37826. * @param {...Object3D} arguments - The 3D objects to uncache.
  37827. */
  37828. uncache() {
  37829. const objects = this._objects,
  37830. indicesByUUID = this._indicesByUUID,
  37831. bindings = this._bindings,
  37832. nBindings = bindings.length;
  37833. let nCachedObjects = this.nCachedObjects_,
  37834. nObjects = objects.length;
  37835. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37836. const object = arguments[ i ],
  37837. uuid = object.uuid,
  37838. index = indicesByUUID[ uuid ];
  37839. if ( index !== undefined ) {
  37840. delete indicesByUUID[ uuid ];
  37841. if ( index < nCachedObjects ) {
  37842. // object is cached, shrink the CACHED region
  37843. const firstActiveIndex = -- nCachedObjects,
  37844. lastCachedObject = objects[ firstActiveIndex ],
  37845. lastIndex = -- nObjects,
  37846. lastObject = objects[ lastIndex ];
  37847. // last cached object takes this object's place
  37848. indicesByUUID[ lastCachedObject.uuid ] = index;
  37849. objects[ index ] = lastCachedObject;
  37850. // last object goes to the activated slot and pop
  37851. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37852. objects[ firstActiveIndex ] = lastObject;
  37853. objects.pop();
  37854. // accounting is done, now do the same for all bindings
  37855. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37856. const bindingsForPath = bindings[ j ],
  37857. lastCached = bindingsForPath[ firstActiveIndex ],
  37858. last = bindingsForPath[ lastIndex ];
  37859. bindingsForPath[ index ] = lastCached;
  37860. bindingsForPath[ firstActiveIndex ] = last;
  37861. bindingsForPath.pop();
  37862. }
  37863. } else {
  37864. // object is active, just swap with the last and pop
  37865. const lastIndex = -- nObjects,
  37866. lastObject = objects[ lastIndex ];
  37867. if ( lastIndex > 0 ) {
  37868. indicesByUUID[ lastObject.uuid ] = index;
  37869. }
  37870. objects[ index ] = lastObject;
  37871. objects.pop();
  37872. // accounting is done, now do the same for all bindings
  37873. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37874. const bindingsForPath = bindings[ j ];
  37875. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  37876. bindingsForPath.pop();
  37877. }
  37878. } // cached or active
  37879. } // if object is known
  37880. } // for arguments
  37881. this.nCachedObjects_ = nCachedObjects;
  37882. }
  37883. // Internal interface used by befriended PropertyBinding.Composite:
  37884. subscribe_( path, parsedPath ) {
  37885. // returns an array of bindings for the given path that is changed
  37886. // according to the contained objects in the group
  37887. const indicesByPath = this._bindingsIndicesByPath;
  37888. let index = indicesByPath[ path ];
  37889. const bindings = this._bindings;
  37890. if ( index !== undefined ) return bindings[ index ];
  37891. const paths = this._paths,
  37892. parsedPaths = this._parsedPaths,
  37893. objects = this._objects,
  37894. nObjects = objects.length,
  37895. nCachedObjects = this.nCachedObjects_,
  37896. bindingsForPath = new Array( nObjects );
  37897. index = bindings.length;
  37898. indicesByPath[ path ] = index;
  37899. paths.push( path );
  37900. parsedPaths.push( parsedPath );
  37901. bindings.push( bindingsForPath );
  37902. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  37903. const object = objects[ i ];
  37904. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  37905. }
  37906. return bindingsForPath;
  37907. }
  37908. unsubscribe_( path ) {
  37909. // tells the group to forget about a property path and no longer
  37910. // update the array previously obtained with 'subscribe_'
  37911. const indicesByPath = this._bindingsIndicesByPath,
  37912. index = indicesByPath[ path ];
  37913. if ( index !== undefined ) {
  37914. const paths = this._paths,
  37915. parsedPaths = this._parsedPaths,
  37916. bindings = this._bindings,
  37917. lastBindingsIndex = bindings.length - 1,
  37918. lastBindings = bindings[ lastBindingsIndex ],
  37919. lastBindingsPath = path[ lastBindingsIndex ];
  37920. indicesByPath[ lastBindingsPath ] = index;
  37921. bindings[ index ] = lastBindings;
  37922. bindings.pop();
  37923. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  37924. parsedPaths.pop();
  37925. paths[ index ] = paths[ lastBindingsIndex ];
  37926. paths.pop();
  37927. }
  37928. }
  37929. }
  37930. /**
  37931. * An instance of `AnimationAction` schedules the playback of an animation which is
  37932. * stored in {@link AnimationClip}.
  37933. */
  37934. class AnimationAction {
  37935. /**
  37936. * Constructs a new animation action.
  37937. *
  37938. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  37939. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  37940. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  37941. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  37942. */
  37943. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  37944. this._mixer = mixer;
  37945. this._clip = clip;
  37946. this._localRoot = localRoot;
  37947. /**
  37948. * Defines how the animation is blended/combined when two or more animations
  37949. * are simultaneously played.
  37950. *
  37951. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  37952. */
  37953. this.blendMode = blendMode;
  37954. const tracks = clip.tracks,
  37955. nTracks = tracks.length,
  37956. interpolants = new Array( nTracks );
  37957. const interpolantSettings = {
  37958. endingStart: ZeroCurvatureEnding,
  37959. endingEnd: ZeroCurvatureEnding
  37960. };
  37961. for ( let i = 0; i !== nTracks; ++ i ) {
  37962. const interpolant = tracks[ i ].createInterpolant( null );
  37963. interpolants[ i ] = interpolant;
  37964. interpolant.settings = interpolantSettings;
  37965. }
  37966. this._interpolantSettings = interpolantSettings;
  37967. this._interpolants = interpolants; // bound by the mixer
  37968. // inside: PropertyMixer (managed by the mixer)
  37969. this._propertyBindings = new Array( nTracks );
  37970. this._cacheIndex = null; // for the memory manager
  37971. this._byClipCacheIndex = null; // for the memory manager
  37972. this._timeScaleInterpolant = null;
  37973. this._weightInterpolant = null;
  37974. /**
  37975. * The loop mode, set via {@link AnimationAction#setLoop}.
  37976. *
  37977. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  37978. * @default LoopRepeat
  37979. */
  37980. this.loop = LoopRepeat;
  37981. this._loopCount = -1;
  37982. // global mixer time when the action is to be started
  37983. // it's set back to 'null' upon start of the action
  37984. this._startTime = null;
  37985. /**
  37986. * The local time of this action (in seconds, starting with `0`).
  37987. *
  37988. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  37989. * loop state).
  37990. *
  37991. * @type {number}
  37992. * @default Infinity
  37993. */
  37994. this.time = 0;
  37995. /**
  37996. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  37997. * animation to pause. Negative values cause the animation to play backwards.
  37998. *
  37999. * @type {number}
  38000. * @default 1
  38001. */
  38002. this.timeScale = 1;
  38003. this._effectiveTimeScale = 1;
  38004. /**
  38005. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38006. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38007. * several actions.
  38008. *
  38009. * @type {number}
  38010. * @default 1
  38011. */
  38012. this.weight = 1;
  38013. this._effectiveWeight = 1;
  38014. /**
  38015. * The number of repetitions of the performed clip over the course of this action.
  38016. * Can be set via {@link AnimationAction#setLoop}.
  38017. *
  38018. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38019. * `THREE:LoopOnce`.
  38020. *
  38021. * @type {number}
  38022. * @default Infinity
  38023. */
  38024. this.repetitions = Infinity;
  38025. /**
  38026. * If set to `true`, the playback of the action is paused.
  38027. *
  38028. * @type {boolean}
  38029. * @default false
  38030. */
  38031. this.paused = false;
  38032. /**
  38033. * If set to `false`, the action is disabled so it has no impact.
  38034. *
  38035. * When the action is re-enabled, the animation continues from its current
  38036. * time (setting `enabled` to `false` doesn't reset the action).
  38037. *
  38038. * @type {boolean}
  38039. * @default true
  38040. */
  38041. this.enabled = true;
  38042. /**
  38043. * If set to true the animation will automatically be paused on its last frame.
  38044. *
  38045. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38046. * to `false` when the last loop of the action has finished, so that this action has
  38047. * no further impact.
  38048. *
  38049. * Note: This member has no impact if the action is interrupted (it
  38050. * has only an effect if its last loop has really finished).
  38051. *
  38052. * @type {boolean}
  38053. * @default false
  38054. */
  38055. this.clampWhenFinished = false;
  38056. /**
  38057. * Enables smooth interpolation without separate clips for start, loop and end.
  38058. *
  38059. * @type {boolean}
  38060. * @default true
  38061. */
  38062. this.zeroSlopeAtStart = true;
  38063. /**
  38064. * Enables smooth interpolation without separate clips for start, loop and end.
  38065. *
  38066. * @type {boolean}
  38067. * @default true
  38068. */
  38069. this.zeroSlopeAtEnd = true;
  38070. }
  38071. /**
  38072. * Starts the playback of the animation.
  38073. *
  38074. * @return {AnimationAction} A reference to this animation action.
  38075. */
  38076. play() {
  38077. this._mixer._activateAction( this );
  38078. return this;
  38079. }
  38080. /**
  38081. * Stops the playback of the animation.
  38082. *
  38083. * @return {AnimationAction} A reference to this animation action.
  38084. */
  38085. stop() {
  38086. this._mixer._deactivateAction( this );
  38087. return this.reset();
  38088. }
  38089. /**
  38090. * Resets the playback of the animation.
  38091. *
  38092. * @return {AnimationAction} A reference to this animation action.
  38093. */
  38094. reset() {
  38095. this.paused = false;
  38096. this.enabled = true;
  38097. this.time = 0; // restart clip
  38098. this._loopCount = -1;// forget previous loops
  38099. this._startTime = null;// forget scheduling
  38100. return this.stopFading().stopWarping();
  38101. }
  38102. /**
  38103. * Returns `true` if the animation is running.
  38104. *
  38105. * @return {boolean} Whether the animation is running or not.
  38106. */
  38107. isRunning() {
  38108. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38109. this._startTime === null && this._mixer._isActiveAction( this );
  38110. }
  38111. /**
  38112. * Returns `true` when {@link AnimationAction#play} has been called.
  38113. *
  38114. * @return {boolean} Whether the animation is scheduled or not.
  38115. */
  38116. isScheduled() {
  38117. return this._mixer._isActiveAction( this );
  38118. }
  38119. /**
  38120. * Defines the time when the animation should start.
  38121. *
  38122. * @param {number} time - The start time in seconds.
  38123. * @return {AnimationAction} A reference to this animation action.
  38124. */
  38125. startAt( time ) {
  38126. this._startTime = time;
  38127. return this;
  38128. }
  38129. /**
  38130. * Configures the loop settings for this action.
  38131. *
  38132. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38133. * @param {number} repetitions - The number of repetitions.
  38134. * @return {AnimationAction} A reference to this animation action.
  38135. */
  38136. setLoop( mode, repetitions ) {
  38137. this.loop = mode;
  38138. this.repetitions = repetitions;
  38139. return this;
  38140. }
  38141. /**
  38142. * Sets the effective weight of this action.
  38143. *
  38144. * An action has no effect and thus an effective weight of zero when the
  38145. * action is disabled.
  38146. *
  38147. * @param {number} weight - The weight to set.
  38148. * @return {AnimationAction} A reference to this animation action.
  38149. */
  38150. setEffectiveWeight( weight ) {
  38151. this.weight = weight;
  38152. // note: same logic as when updated at runtime
  38153. this._effectiveWeight = this.enabled ? weight : 0;
  38154. return this.stopFading();
  38155. }
  38156. /**
  38157. * Returns the effective weight of this action.
  38158. *
  38159. * @return {number} The effective weight.
  38160. */
  38161. getEffectiveWeight() {
  38162. return this._effectiveWeight;
  38163. }
  38164. /**
  38165. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38166. * within the passed time interval.
  38167. *
  38168. * @param {number} duration - The duration of the fade.
  38169. * @return {AnimationAction} A reference to this animation action.
  38170. */
  38171. fadeIn( duration ) {
  38172. return this._scheduleFading( duration, 0, 1 );
  38173. }
  38174. /**
  38175. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38176. * within the passed time interval.
  38177. *
  38178. * @param {number} duration - The duration of the fade.
  38179. * @return {AnimationAction} A reference to this animation action.
  38180. */
  38181. fadeOut( duration ) {
  38182. return this._scheduleFading( duration, 1, 0 );
  38183. }
  38184. /**
  38185. * Causes this action to fade in and the given action to fade out,
  38186. * within the passed time interval.
  38187. *
  38188. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38189. * @param {number} duration - The duration of the fade.
  38190. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38191. * @return {AnimationAction} A reference to this animation action.
  38192. */
  38193. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38194. fadeOutAction.fadeOut( duration );
  38195. this.fadeIn( duration );
  38196. if ( warp === true ) {
  38197. const fadeInDuration = this._clip.duration,
  38198. fadeOutDuration = fadeOutAction._clip.duration,
  38199. startEndRatio = fadeOutDuration / fadeInDuration,
  38200. endStartRatio = fadeInDuration / fadeOutDuration;
  38201. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38202. this.warp( endStartRatio, 1.0, duration );
  38203. }
  38204. return this;
  38205. }
  38206. /**
  38207. * Causes this action to fade out and the given action to fade in,
  38208. * within the passed time interval.
  38209. *
  38210. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38211. * @param {number} duration - The duration of the fade.
  38212. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38213. * @return {AnimationAction} A reference to this animation action.
  38214. */
  38215. crossFadeTo( fadeInAction, duration, warp = false ) {
  38216. return fadeInAction.crossFadeFrom( this, duration, warp );
  38217. }
  38218. /**
  38219. * Stops any fading which is applied to this action.
  38220. *
  38221. * @return {AnimationAction} A reference to this animation action.
  38222. */
  38223. stopFading() {
  38224. const weightInterpolant = this._weightInterpolant;
  38225. if ( weightInterpolant !== null ) {
  38226. this._weightInterpolant = null;
  38227. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38228. }
  38229. return this;
  38230. }
  38231. /**
  38232. * Sets the effective time scale of this action.
  38233. *
  38234. * An action has no effect and thus an effective time scale of zero when the
  38235. * action is paused.
  38236. *
  38237. * @param {number} timeScale - The time scale to set.
  38238. * @return {AnimationAction} A reference to this animation action.
  38239. */
  38240. setEffectiveTimeScale( timeScale ) {
  38241. this.timeScale = timeScale;
  38242. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38243. return this.stopWarping();
  38244. }
  38245. /**
  38246. * Returns the effective time scale of this action.
  38247. *
  38248. * @return {number} The effective time scale.
  38249. */
  38250. getEffectiveTimeScale() {
  38251. return this._effectiveTimeScale;
  38252. }
  38253. /**
  38254. * Sets the duration for a single loop of this action.
  38255. *
  38256. * @param {number} duration - The duration to set.
  38257. * @return {AnimationAction} A reference to this animation action.
  38258. */
  38259. setDuration( duration ) {
  38260. this.timeScale = this._clip.duration / duration;
  38261. return this.stopWarping();
  38262. }
  38263. /**
  38264. * Synchronizes this action with the passed other action.
  38265. *
  38266. * @param {AnimationAction} action - The action to sync with.
  38267. * @return {AnimationAction} A reference to this animation action.
  38268. */
  38269. syncWith( action ) {
  38270. this.time = action.time;
  38271. this.timeScale = action.timeScale;
  38272. return this.stopWarping();
  38273. }
  38274. /**
  38275. * Decelerates this animation's speed to `0` within the passed time interval.
  38276. *
  38277. * @param {number} duration - The duration.
  38278. * @return {AnimationAction} A reference to this animation action.
  38279. */
  38280. halt( duration ) {
  38281. return this.warp( this._effectiveTimeScale, 0, duration );
  38282. }
  38283. /**
  38284. * Changes the playback speed, within the passed time interval, by modifying
  38285. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38286. * `endTimeScale`.
  38287. *
  38288. * @param {number} startTimeScale - The start time scale.
  38289. * @param {number} endTimeScale - The end time scale.
  38290. * @param {number} duration - The duration.
  38291. * @return {AnimationAction} A reference to this animation action.
  38292. */
  38293. warp( startTimeScale, endTimeScale, duration ) {
  38294. const mixer = this._mixer,
  38295. now = mixer.time,
  38296. timeScale = this.timeScale;
  38297. let interpolant = this._timeScaleInterpolant;
  38298. if ( interpolant === null ) {
  38299. interpolant = mixer._lendControlInterpolant();
  38300. this._timeScaleInterpolant = interpolant;
  38301. }
  38302. const times = interpolant.parameterPositions,
  38303. values = interpolant.sampleValues;
  38304. times[ 0 ] = now;
  38305. times[ 1 ] = now + duration;
  38306. values[ 0 ] = startTimeScale / timeScale;
  38307. values[ 1 ] = endTimeScale / timeScale;
  38308. return this;
  38309. }
  38310. /**
  38311. * Stops any scheduled warping which is applied to this action.
  38312. *
  38313. * @return {AnimationAction} A reference to this animation action.
  38314. */
  38315. stopWarping() {
  38316. const timeScaleInterpolant = this._timeScaleInterpolant;
  38317. if ( timeScaleInterpolant !== null ) {
  38318. this._timeScaleInterpolant = null;
  38319. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38320. }
  38321. return this;
  38322. }
  38323. /**
  38324. * Returns the animation mixer of this animation action.
  38325. *
  38326. * @return {AnimationMixer} The animation mixer.
  38327. */
  38328. getMixer() {
  38329. return this._mixer;
  38330. }
  38331. /**
  38332. * Returns the animation clip of this animation action.
  38333. *
  38334. * @return {AnimationClip} The animation clip.
  38335. */
  38336. getClip() {
  38337. return this._clip;
  38338. }
  38339. /**
  38340. * Returns the root object of this animation action.
  38341. *
  38342. * @return {Object3D} The root object.
  38343. */
  38344. getRoot() {
  38345. return this._localRoot || this._mixer._root;
  38346. }
  38347. // Interna
  38348. _update( time, deltaTime, timeDirection, accuIndex ) {
  38349. // called by the mixer
  38350. if ( ! this.enabled ) {
  38351. // call ._updateWeight() to update ._effectiveWeight
  38352. this._updateWeight( time );
  38353. return;
  38354. }
  38355. const startTime = this._startTime;
  38356. if ( startTime !== null ) {
  38357. // check for scheduled start of action
  38358. const timeRunning = ( time - startTime ) * timeDirection;
  38359. if ( timeRunning < 0 || timeDirection === 0 ) {
  38360. deltaTime = 0;
  38361. } else {
  38362. this._startTime = null; // unschedule
  38363. deltaTime = timeDirection * timeRunning;
  38364. }
  38365. }
  38366. // apply time scale and advance time
  38367. deltaTime *= this._updateTimeScale( time );
  38368. const clipTime = this._updateTime( deltaTime );
  38369. // note: _updateTime may disable the action resulting in
  38370. // an effective weight of 0
  38371. const weight = this._updateWeight( time );
  38372. if ( weight > 0 ) {
  38373. const interpolants = this._interpolants;
  38374. const propertyMixers = this._propertyBindings;
  38375. switch ( this.blendMode ) {
  38376. case AdditiveAnimationBlendMode:
  38377. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38378. interpolants[ j ].evaluate( clipTime );
  38379. propertyMixers[ j ].accumulateAdditive( weight );
  38380. }
  38381. break;
  38382. case NormalAnimationBlendMode:
  38383. default:
  38384. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38385. interpolants[ j ].evaluate( clipTime );
  38386. propertyMixers[ j ].accumulate( accuIndex, weight );
  38387. }
  38388. }
  38389. }
  38390. }
  38391. _updateWeight( time ) {
  38392. let weight = 0;
  38393. if ( this.enabled ) {
  38394. weight = this.weight;
  38395. const interpolant = this._weightInterpolant;
  38396. if ( interpolant !== null ) {
  38397. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38398. weight *= interpolantValue;
  38399. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38400. this.stopFading();
  38401. if ( interpolantValue === 0 ) {
  38402. // faded out, disable
  38403. this.enabled = false;
  38404. }
  38405. }
  38406. }
  38407. }
  38408. this._effectiveWeight = weight;
  38409. return weight;
  38410. }
  38411. _updateTimeScale( time ) {
  38412. let timeScale = 0;
  38413. if ( ! this.paused ) {
  38414. timeScale = this.timeScale;
  38415. const interpolant = this._timeScaleInterpolant;
  38416. if ( interpolant !== null ) {
  38417. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38418. timeScale *= interpolantValue;
  38419. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38420. this.stopWarping();
  38421. if ( timeScale === 0 ) {
  38422. // motion has halted, pause
  38423. this.paused = true;
  38424. } else {
  38425. // warp done - apply final time scale
  38426. this.timeScale = timeScale;
  38427. }
  38428. }
  38429. }
  38430. }
  38431. this._effectiveTimeScale = timeScale;
  38432. return timeScale;
  38433. }
  38434. _updateTime( deltaTime ) {
  38435. const duration = this._clip.duration;
  38436. const loop = this.loop;
  38437. let time = this.time + deltaTime;
  38438. let loopCount = this._loopCount;
  38439. const pingPong = ( loop === LoopPingPong );
  38440. if ( deltaTime === 0 ) {
  38441. if ( loopCount === -1 ) return time;
  38442. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38443. }
  38444. if ( loop === LoopOnce ) {
  38445. if ( loopCount === -1 ) {
  38446. // just started
  38447. this._loopCount = 0;
  38448. this._setEndings( true, true, false );
  38449. }
  38450. handle_stop: {
  38451. if ( time >= duration ) {
  38452. time = duration;
  38453. } else if ( time < 0 ) {
  38454. time = 0;
  38455. } else {
  38456. this.time = time;
  38457. break handle_stop;
  38458. }
  38459. if ( this.clampWhenFinished ) this.paused = true;
  38460. else this.enabled = false;
  38461. this.time = time;
  38462. this._mixer.dispatchEvent( {
  38463. type: 'finished', action: this,
  38464. direction: deltaTime < 0 ? -1 : 1
  38465. } );
  38466. }
  38467. } else { // repetitive Repeat or PingPong
  38468. if ( loopCount === -1 ) {
  38469. // just started
  38470. if ( deltaTime >= 0 ) {
  38471. loopCount = 0;
  38472. this._setEndings( true, this.repetitions === 0, pingPong );
  38473. } else {
  38474. // when looping in reverse direction, the initial
  38475. // transition through zero counts as a repetition,
  38476. // so leave loopCount at -1
  38477. this._setEndings( this.repetitions === 0, true, pingPong );
  38478. }
  38479. }
  38480. if ( time >= duration || time < 0 ) {
  38481. // wrap around
  38482. const loopDelta = Math.floor( time / duration ); // signed
  38483. time -= duration * loopDelta;
  38484. loopCount += Math.abs( loopDelta );
  38485. const pending = this.repetitions - loopCount;
  38486. if ( pending <= 0 ) {
  38487. // have to stop (switch state, clamp time, fire event)
  38488. if ( this.clampWhenFinished ) this.paused = true;
  38489. else this.enabled = false;
  38490. time = deltaTime > 0 ? duration : 0;
  38491. this.time = time;
  38492. this._mixer.dispatchEvent( {
  38493. type: 'finished', action: this,
  38494. direction: deltaTime > 0 ? 1 : -1
  38495. } );
  38496. } else {
  38497. // keep running
  38498. if ( pending === 1 ) {
  38499. // entering the last round
  38500. const atStart = deltaTime < 0;
  38501. this._setEndings( atStart, ! atStart, pingPong );
  38502. } else {
  38503. this._setEndings( false, false, pingPong );
  38504. }
  38505. this._loopCount = loopCount;
  38506. this.time = time;
  38507. this._mixer.dispatchEvent( {
  38508. type: 'loop', action: this, loopDelta: loopDelta
  38509. } );
  38510. }
  38511. } else {
  38512. this.time = time;
  38513. }
  38514. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38515. // invert time for the "pong round"
  38516. return duration - time;
  38517. }
  38518. }
  38519. return time;
  38520. }
  38521. _setEndings( atStart, atEnd, pingPong ) {
  38522. const settings = this._interpolantSettings;
  38523. if ( pingPong ) {
  38524. settings.endingStart = ZeroSlopeEnding;
  38525. settings.endingEnd = ZeroSlopeEnding;
  38526. } else {
  38527. // assuming for LoopOnce atStart == atEnd == true
  38528. if ( atStart ) {
  38529. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38530. } else {
  38531. settings.endingStart = WrapAroundEnding;
  38532. }
  38533. if ( atEnd ) {
  38534. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38535. } else {
  38536. settings.endingEnd = WrapAroundEnding;
  38537. }
  38538. }
  38539. }
  38540. _scheduleFading( duration, weightNow, weightThen ) {
  38541. const mixer = this._mixer, now = mixer.time;
  38542. let interpolant = this._weightInterpolant;
  38543. if ( interpolant === null ) {
  38544. interpolant = mixer._lendControlInterpolant();
  38545. this._weightInterpolant = interpolant;
  38546. }
  38547. const times = interpolant.parameterPositions,
  38548. values = interpolant.sampleValues;
  38549. times[ 0 ] = now;
  38550. values[ 0 ] = weightNow;
  38551. times[ 1 ] = now + duration;
  38552. values[ 1 ] = weightThen;
  38553. return this;
  38554. }
  38555. }
  38556. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38557. /**
  38558. * `AnimationMixer` is a player for animations on a particular object in
  38559. * the scene. When multiple objects in the scene are animated independently,
  38560. * one `AnimationMixer` may be used for each object.
  38561. */
  38562. class AnimationMixer extends EventDispatcher {
  38563. /**
  38564. * Constructs a new animation mixer.
  38565. *
  38566. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38567. */
  38568. constructor( root ) {
  38569. super();
  38570. this._root = root;
  38571. this._initMemoryManager();
  38572. this._accuIndex = 0;
  38573. /**
  38574. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38575. *
  38576. * @type {number}
  38577. * @default 0
  38578. */
  38579. this.time = 0;
  38580. /**
  38581. * A scaling factor for the global time.
  38582. *
  38583. * Note: Setting this member to `0` and later back to `1` is a
  38584. * possibility to pause/unpause all actions that are controlled by this
  38585. * mixer.
  38586. *
  38587. * @type {number}
  38588. * @default 1
  38589. */
  38590. this.timeScale = 1.0;
  38591. }
  38592. _bindAction( action, prototypeAction ) {
  38593. const root = action._localRoot || this._root,
  38594. tracks = action._clip.tracks,
  38595. nTracks = tracks.length,
  38596. bindings = action._propertyBindings,
  38597. interpolants = action._interpolants,
  38598. rootUuid = root.uuid,
  38599. bindingsByRoot = this._bindingsByRootAndName;
  38600. let bindingsByName = bindingsByRoot[ rootUuid ];
  38601. if ( bindingsByName === undefined ) {
  38602. bindingsByName = {};
  38603. bindingsByRoot[ rootUuid ] = bindingsByName;
  38604. }
  38605. for ( let i = 0; i !== nTracks; ++ i ) {
  38606. const track = tracks[ i ],
  38607. trackName = track.name;
  38608. let binding = bindingsByName[ trackName ];
  38609. if ( binding !== undefined ) {
  38610. ++ binding.referenceCount;
  38611. bindings[ i ] = binding;
  38612. } else {
  38613. binding = bindings[ i ];
  38614. if ( binding !== undefined ) {
  38615. // existing binding, make sure the cache knows
  38616. if ( binding._cacheIndex === null ) {
  38617. ++ binding.referenceCount;
  38618. this._addInactiveBinding( binding, rootUuid, trackName );
  38619. }
  38620. continue;
  38621. }
  38622. const path = prototypeAction && prototypeAction.
  38623. _propertyBindings[ i ].binding.parsedPath;
  38624. binding = new PropertyMixer(
  38625. PropertyBinding.create( root, trackName, path ),
  38626. track.ValueTypeName, track.getValueSize() );
  38627. ++ binding.referenceCount;
  38628. this._addInactiveBinding( binding, rootUuid, trackName );
  38629. bindings[ i ] = binding;
  38630. }
  38631. interpolants[ i ].resultBuffer = binding.buffer;
  38632. }
  38633. }
  38634. _activateAction( action ) {
  38635. if ( ! this._isActiveAction( action ) ) {
  38636. if ( action._cacheIndex === null ) {
  38637. // this action has been forgotten by the cache, but the user
  38638. // appears to be still using it -> rebind
  38639. const rootUuid = ( action._localRoot || this._root ).uuid,
  38640. clipUuid = action._clip.uuid,
  38641. actionsForClip = this._actionsByClip[ clipUuid ];
  38642. this._bindAction( action,
  38643. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38644. this._addInactiveAction( action, clipUuid, rootUuid );
  38645. }
  38646. const bindings = action._propertyBindings;
  38647. // increment reference counts / sort out state
  38648. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38649. const binding = bindings[ i ];
  38650. if ( binding.useCount ++ === 0 ) {
  38651. this._lendBinding( binding );
  38652. binding.saveOriginalState();
  38653. }
  38654. }
  38655. this._lendAction( action );
  38656. }
  38657. }
  38658. _deactivateAction( action ) {
  38659. if ( this._isActiveAction( action ) ) {
  38660. const bindings = action._propertyBindings;
  38661. // decrement 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. binding.restoreOriginalState();
  38666. this._takeBackBinding( binding );
  38667. }
  38668. }
  38669. this._takeBackAction( action );
  38670. }
  38671. }
  38672. // Memory manager
  38673. _initMemoryManager() {
  38674. this._actions = []; // 'nActiveActions' followed by inactive ones
  38675. this._nActiveActions = 0;
  38676. this._actionsByClip = {};
  38677. // inside:
  38678. // {
  38679. // knownActions: Array< AnimationAction > - used as prototypes
  38680. // actionByRoot: AnimationAction - lookup
  38681. // }
  38682. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38683. this._nActiveBindings = 0;
  38684. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38685. this._controlInterpolants = []; // same game as above
  38686. this._nActiveControlInterpolants = 0;
  38687. const scope = this;
  38688. this.stats = {
  38689. actions: {
  38690. get total() {
  38691. return scope._actions.length;
  38692. },
  38693. get inUse() {
  38694. return scope._nActiveActions;
  38695. }
  38696. },
  38697. bindings: {
  38698. get total() {
  38699. return scope._bindings.length;
  38700. },
  38701. get inUse() {
  38702. return scope._nActiveBindings;
  38703. }
  38704. },
  38705. controlInterpolants: {
  38706. get total() {
  38707. return scope._controlInterpolants.length;
  38708. },
  38709. get inUse() {
  38710. return scope._nActiveControlInterpolants;
  38711. }
  38712. }
  38713. };
  38714. }
  38715. // Memory management for AnimationAction objects
  38716. _isActiveAction( action ) {
  38717. const index = action._cacheIndex;
  38718. return index !== null && index < this._nActiveActions;
  38719. }
  38720. _addInactiveAction( action, clipUuid, rootUuid ) {
  38721. const actions = this._actions,
  38722. actionsByClip = this._actionsByClip;
  38723. let actionsForClip = actionsByClip[ clipUuid ];
  38724. if ( actionsForClip === undefined ) {
  38725. actionsForClip = {
  38726. knownActions: [ action ],
  38727. actionByRoot: {}
  38728. };
  38729. action._byClipCacheIndex = 0;
  38730. actionsByClip[ clipUuid ] = actionsForClip;
  38731. } else {
  38732. const knownActions = actionsForClip.knownActions;
  38733. action._byClipCacheIndex = knownActions.length;
  38734. knownActions.push( action );
  38735. }
  38736. action._cacheIndex = actions.length;
  38737. actions.push( action );
  38738. actionsForClip.actionByRoot[ rootUuid ] = action;
  38739. }
  38740. _removeInactiveAction( action ) {
  38741. const actions = this._actions,
  38742. lastInactiveAction = actions[ actions.length - 1 ],
  38743. cacheIndex = action._cacheIndex;
  38744. lastInactiveAction._cacheIndex = cacheIndex;
  38745. actions[ cacheIndex ] = lastInactiveAction;
  38746. actions.pop();
  38747. action._cacheIndex = null;
  38748. const clipUuid = action._clip.uuid,
  38749. actionsByClip = this._actionsByClip,
  38750. actionsForClip = actionsByClip[ clipUuid ],
  38751. knownActionsForClip = actionsForClip.knownActions,
  38752. lastKnownAction =
  38753. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38754. byClipCacheIndex = action._byClipCacheIndex;
  38755. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38756. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38757. knownActionsForClip.pop();
  38758. action._byClipCacheIndex = null;
  38759. const actionByRoot = actionsForClip.actionByRoot,
  38760. rootUuid = ( action._localRoot || this._root ).uuid;
  38761. delete actionByRoot[ rootUuid ];
  38762. if ( knownActionsForClip.length === 0 ) {
  38763. delete actionsByClip[ clipUuid ];
  38764. }
  38765. this._removeInactiveBindingsForAction( action );
  38766. }
  38767. _removeInactiveBindingsForAction( action ) {
  38768. const bindings = action._propertyBindings;
  38769. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38770. const binding = bindings[ i ];
  38771. if ( -- binding.referenceCount === 0 ) {
  38772. this._removeInactiveBinding( binding );
  38773. }
  38774. }
  38775. }
  38776. _lendAction( action ) {
  38777. // [ active actions | inactive actions ]
  38778. // [ active actions >| inactive actions ]
  38779. // s a
  38780. // <-swap->
  38781. // a s
  38782. const actions = this._actions,
  38783. prevIndex = action._cacheIndex,
  38784. lastActiveIndex = this._nActiveActions ++,
  38785. firstInactiveAction = actions[ lastActiveIndex ];
  38786. action._cacheIndex = lastActiveIndex;
  38787. actions[ lastActiveIndex ] = action;
  38788. firstInactiveAction._cacheIndex = prevIndex;
  38789. actions[ prevIndex ] = firstInactiveAction;
  38790. }
  38791. _takeBackAction( action ) {
  38792. // [ active actions | inactive actions ]
  38793. // [ active actions |< inactive actions ]
  38794. // a s
  38795. // <-swap->
  38796. // s a
  38797. const actions = this._actions,
  38798. prevIndex = action._cacheIndex,
  38799. firstInactiveIndex = -- this._nActiveActions,
  38800. lastActiveAction = actions[ firstInactiveIndex ];
  38801. action._cacheIndex = firstInactiveIndex;
  38802. actions[ firstInactiveIndex ] = action;
  38803. lastActiveAction._cacheIndex = prevIndex;
  38804. actions[ prevIndex ] = lastActiveAction;
  38805. }
  38806. // Memory management for PropertyMixer objects
  38807. _addInactiveBinding( binding, rootUuid, trackName ) {
  38808. const bindingsByRoot = this._bindingsByRootAndName,
  38809. bindings = this._bindings;
  38810. let bindingByName = bindingsByRoot[ rootUuid ];
  38811. if ( bindingByName === undefined ) {
  38812. bindingByName = {};
  38813. bindingsByRoot[ rootUuid ] = bindingByName;
  38814. }
  38815. bindingByName[ trackName ] = binding;
  38816. binding._cacheIndex = bindings.length;
  38817. bindings.push( binding );
  38818. }
  38819. _removeInactiveBinding( binding ) {
  38820. const bindings = this._bindings,
  38821. propBinding = binding.binding,
  38822. rootUuid = propBinding.rootNode.uuid,
  38823. trackName = propBinding.path,
  38824. bindingsByRoot = this._bindingsByRootAndName,
  38825. bindingByName = bindingsByRoot[ rootUuid ],
  38826. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38827. cacheIndex = binding._cacheIndex;
  38828. lastInactiveBinding._cacheIndex = cacheIndex;
  38829. bindings[ cacheIndex ] = lastInactiveBinding;
  38830. bindings.pop();
  38831. delete bindingByName[ trackName ];
  38832. if ( Object.keys( bindingByName ).length === 0 ) {
  38833. delete bindingsByRoot[ rootUuid ];
  38834. }
  38835. }
  38836. _lendBinding( binding ) {
  38837. const bindings = this._bindings,
  38838. prevIndex = binding._cacheIndex,
  38839. lastActiveIndex = this._nActiveBindings ++,
  38840. firstInactiveBinding = bindings[ lastActiveIndex ];
  38841. binding._cacheIndex = lastActiveIndex;
  38842. bindings[ lastActiveIndex ] = binding;
  38843. firstInactiveBinding._cacheIndex = prevIndex;
  38844. bindings[ prevIndex ] = firstInactiveBinding;
  38845. }
  38846. _takeBackBinding( binding ) {
  38847. const bindings = this._bindings,
  38848. prevIndex = binding._cacheIndex,
  38849. firstInactiveIndex = -- this._nActiveBindings,
  38850. lastActiveBinding = bindings[ firstInactiveIndex ];
  38851. binding._cacheIndex = firstInactiveIndex;
  38852. bindings[ firstInactiveIndex ] = binding;
  38853. lastActiveBinding._cacheIndex = prevIndex;
  38854. bindings[ prevIndex ] = lastActiveBinding;
  38855. }
  38856. // Memory management of Interpolants for weight and time scale
  38857. _lendControlInterpolant() {
  38858. const interpolants = this._controlInterpolants,
  38859. lastActiveIndex = this._nActiveControlInterpolants ++;
  38860. let interpolant = interpolants[ lastActiveIndex ];
  38861. if ( interpolant === undefined ) {
  38862. interpolant = new LinearInterpolant(
  38863. new Float32Array( 2 ), new Float32Array( 2 ),
  38864. 1, _controlInterpolantsResultBuffer );
  38865. interpolant.__cacheIndex = lastActiveIndex;
  38866. interpolants[ lastActiveIndex ] = interpolant;
  38867. }
  38868. return interpolant;
  38869. }
  38870. _takeBackControlInterpolant( interpolant ) {
  38871. const interpolants = this._controlInterpolants,
  38872. prevIndex = interpolant.__cacheIndex,
  38873. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38874. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38875. interpolant.__cacheIndex = firstInactiveIndex;
  38876. interpolants[ firstInactiveIndex ] = interpolant;
  38877. lastActiveInterpolant.__cacheIndex = prevIndex;
  38878. interpolants[ prevIndex ] = lastActiveInterpolant;
  38879. }
  38880. /**
  38881. * Returns an instance of {@link AnimationAction} for the passed clip.
  38882. *
  38883. * If an action fitting the clip and root parameters doesn't yet exist, it
  38884. * will be created by this method. Calling this method several times with the
  38885. * same clip and root parameters always returns the same action.
  38886. *
  38887. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38888. * @param {Object3D} [optionalRoot] - An alternative root object.
  38889. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38890. * @return {?AnimationAction} The animation action.
  38891. */
  38892. clipAction( clip, optionalRoot, blendMode ) {
  38893. const root = optionalRoot || this._root,
  38894. rootUuid = root.uuid;
  38895. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  38896. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  38897. const actionsForClip = this._actionsByClip[ clipUuid ];
  38898. let prototypeAction = null;
  38899. if ( blendMode === undefined ) {
  38900. if ( clipObject !== null ) {
  38901. blendMode = clipObject.blendMode;
  38902. } else {
  38903. blendMode = NormalAnimationBlendMode;
  38904. }
  38905. }
  38906. if ( actionsForClip !== undefined ) {
  38907. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  38908. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  38909. return existingAction;
  38910. }
  38911. // we know the clip, so we don't have to parse all
  38912. // the bindings again but can just copy
  38913. prototypeAction = actionsForClip.knownActions[ 0 ];
  38914. // also, take the clip from the prototype action
  38915. if ( clipObject === null )
  38916. clipObject = prototypeAction._clip;
  38917. }
  38918. // clip must be known when specified via string
  38919. if ( clipObject === null ) return null;
  38920. // allocate all resources required to run it
  38921. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  38922. this._bindAction( newAction, prototypeAction );
  38923. // and make the action known to the memory manager
  38924. this._addInactiveAction( newAction, clipUuid, rootUuid );
  38925. return newAction;
  38926. }
  38927. /**
  38928. * Returns an existing animation action for the passed clip.
  38929. *
  38930. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  38931. * @param {Object3D} [optionalRoot] - An alternative root object.
  38932. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  38933. */
  38934. existingAction( clip, optionalRoot ) {
  38935. const root = optionalRoot || this._root,
  38936. rootUuid = root.uuid,
  38937. clipObject = typeof clip === 'string' ?
  38938. AnimationClip.findByName( root, clip ) : clip,
  38939. clipUuid = clipObject ? clipObject.uuid : clip,
  38940. actionsForClip = this._actionsByClip[ clipUuid ];
  38941. if ( actionsForClip !== undefined ) {
  38942. return actionsForClip.actionByRoot[ rootUuid ] || null;
  38943. }
  38944. return null;
  38945. }
  38946. /**
  38947. * Deactivates all previously scheduled actions on this mixer.
  38948. *
  38949. * @return {AnimationMixer} A reference to thi animation mixer.
  38950. */
  38951. stopAllAction() {
  38952. const actions = this._actions,
  38953. nActions = this._nActiveActions;
  38954. for ( let i = nActions - 1; i >= 0; -- i ) {
  38955. actions[ i ].stop();
  38956. }
  38957. return this;
  38958. }
  38959. /**
  38960. * Advances the global mixer time and updates the animation.
  38961. *
  38962. * This is usually done in the render loop by passing the delta
  38963. * time from {@link Clock} or {@link Timer}.
  38964. *
  38965. * @param {number} deltaTime - The delta time in seconds.
  38966. * @return {AnimationMixer} A reference to thi animation mixer.
  38967. */
  38968. update( deltaTime ) {
  38969. deltaTime *= this.timeScale;
  38970. const actions = this._actions,
  38971. nActions = this._nActiveActions,
  38972. time = this.time += deltaTime,
  38973. timeDirection = Math.sign( deltaTime ),
  38974. accuIndex = this._accuIndex ^= 1;
  38975. // run active actions
  38976. for ( let i = 0; i !== nActions; ++ i ) {
  38977. const action = actions[ i ];
  38978. action._update( time, deltaTime, timeDirection, accuIndex );
  38979. }
  38980. // update scene graph
  38981. const bindings = this._bindings,
  38982. nBindings = this._nActiveBindings;
  38983. for ( let i = 0; i !== nBindings; ++ i ) {
  38984. bindings[ i ].apply( accuIndex );
  38985. }
  38986. return this;
  38987. }
  38988. /**
  38989. * Sets the global mixer to a specific time and updates the animation accordingly.
  38990. *
  38991. * This is useful when you need to jump to an exact time in an animation. The
  38992. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  38993. *
  38994. * @param {number} time - The time to set in seconds.
  38995. * @return {AnimationMixer} A reference to thi animation mixer.
  38996. */
  38997. setTime( time ) {
  38998. this.time = 0; // Zero out time attribute for AnimationMixer object;
  38999. for ( let i = 0; i < this._actions.length; i ++ ) {
  39000. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39001. }
  39002. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39003. }
  39004. /**
  39005. * Returns this mixer's root object.
  39006. *
  39007. * @return {Object3D} The mixer's root object.
  39008. */
  39009. getRoot() {
  39010. return this._root;
  39011. }
  39012. /**
  39013. * Deallocates all memory resources for a clip. Before using this method make
  39014. * sure to call {@link AnimationAction#stop} for all related actions.
  39015. *
  39016. * @param {AnimationClip} clip - The clip to uncache.
  39017. */
  39018. uncacheClip( clip ) {
  39019. const actions = this._actions,
  39020. clipUuid = clip.uuid,
  39021. actionsByClip = this._actionsByClip,
  39022. actionsForClip = actionsByClip[ clipUuid ];
  39023. if ( actionsForClip !== undefined ) {
  39024. // note: just calling _removeInactiveAction would mess up the
  39025. // iteration state and also require updating the state we can
  39026. // just throw away
  39027. const actionsToRemove = actionsForClip.knownActions;
  39028. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39029. const action = actionsToRemove[ i ];
  39030. this._deactivateAction( action );
  39031. const cacheIndex = action._cacheIndex,
  39032. lastInactiveAction = actions[ actions.length - 1 ];
  39033. action._cacheIndex = null;
  39034. action._byClipCacheIndex = null;
  39035. lastInactiveAction._cacheIndex = cacheIndex;
  39036. actions[ cacheIndex ] = lastInactiveAction;
  39037. actions.pop();
  39038. this._removeInactiveBindingsForAction( action );
  39039. }
  39040. delete actionsByClip[ clipUuid ];
  39041. }
  39042. }
  39043. /**
  39044. * Deallocates all memory resources for a root object. Before using this
  39045. * method make sure to call {@link AnimationAction#stop} for all related
  39046. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39047. * mixer operates on a single root.
  39048. *
  39049. * @param {Object3D} root - The root object to uncache.
  39050. */
  39051. uncacheRoot( root ) {
  39052. const rootUuid = root.uuid,
  39053. actionsByClip = this._actionsByClip;
  39054. for ( const clipUuid in actionsByClip ) {
  39055. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39056. action = actionByRoot[ rootUuid ];
  39057. if ( action !== undefined ) {
  39058. this._deactivateAction( action );
  39059. this._removeInactiveAction( action );
  39060. }
  39061. }
  39062. const bindingsByRoot = this._bindingsByRootAndName,
  39063. bindingByName = bindingsByRoot[ rootUuid ];
  39064. if ( bindingByName !== undefined ) {
  39065. for ( const trackName in bindingByName ) {
  39066. const binding = bindingByName[ trackName ];
  39067. binding.restoreOriginalState();
  39068. this._removeInactiveBinding( binding );
  39069. }
  39070. }
  39071. }
  39072. /**
  39073. * Deallocates all memory resources for an action. The action is identified by the
  39074. * given clip and an optional root object. Before using this method make
  39075. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39076. *
  39077. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39078. * @param {Object3D} [optionalRoot] - An alternative root object.
  39079. */
  39080. uncacheAction( clip, optionalRoot ) {
  39081. const action = this.existingAction( clip, optionalRoot );
  39082. if ( action !== null ) {
  39083. this._deactivateAction( action );
  39084. this._removeInactiveAction( action );
  39085. }
  39086. }
  39087. }
  39088. /**
  39089. * Represents a 3D render target.
  39090. *
  39091. * @augments RenderTarget
  39092. */
  39093. class RenderTarget3D extends RenderTarget {
  39094. /**
  39095. * Constructs a new 3D render target.
  39096. *
  39097. * @param {number} [width=1] - The width of the render target.
  39098. * @param {number} [height=1] - The height of the render target.
  39099. * @param {number} [depth=1] - The height of the render target.
  39100. * @param {RenderTarget~Options} [options] - The configuration object.
  39101. */
  39102. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39103. super( width, height, options );
  39104. /**
  39105. * This flag can be used for type testing.
  39106. *
  39107. * @type {boolean}
  39108. * @readonly
  39109. * @default true
  39110. */
  39111. this.isRenderTarget3D = true;
  39112. this.depth = depth;
  39113. /**
  39114. * Overwritten with a different texture type.
  39115. *
  39116. * @type {Data3DTexture}
  39117. */
  39118. this.texture = new Data3DTexture( null, width, height, depth );
  39119. this._setTextureOptions( options );
  39120. this.texture.isRenderTargetTexture = true;
  39121. }
  39122. }
  39123. /**
  39124. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39125. *
  39126. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39127. * ```js
  39128. * uniforms: {
  39129. * time: { value: 1.0 },
  39130. * resolution: new Uniform( new Vector2() )
  39131. * };
  39132. * ```
  39133. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39134. * in {@link WebGLRenderer}.
  39135. */
  39136. class Uniform {
  39137. /**
  39138. * Constructs a new uniform.
  39139. *
  39140. * @param {any} value - The uniform value.
  39141. */
  39142. constructor( value ) {
  39143. /**
  39144. * The uniform value.
  39145. *
  39146. * @type {any}
  39147. */
  39148. this.value = value;
  39149. }
  39150. /**
  39151. * Returns a new uniform with copied values from this instance.
  39152. * If the value has a `clone()` method, the value is cloned as well.
  39153. *
  39154. * @return {Uniform} A clone of this instance.
  39155. */
  39156. clone() {
  39157. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39158. }
  39159. }
  39160. let _id = 0;
  39161. /**
  39162. * A class for managing multiple uniforms in a single group. The renderer will process
  39163. * such a definition as a single UBO.
  39164. *
  39165. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39166. * in {@link WebGLRenderer}.
  39167. *
  39168. * @augments EventDispatcher
  39169. */
  39170. class UniformsGroup extends EventDispatcher {
  39171. /**
  39172. * Constructs a new uniforms group.
  39173. */
  39174. constructor() {
  39175. super();
  39176. /**
  39177. * This flag can be used for type testing.
  39178. *
  39179. * @type {boolean}
  39180. * @readonly
  39181. * @default true
  39182. */
  39183. this.isUniformsGroup = true;
  39184. /**
  39185. * The ID of the 3D object.
  39186. *
  39187. * @name UniformsGroup#id
  39188. * @type {number}
  39189. * @readonly
  39190. */
  39191. Object.defineProperty( this, 'id', { value: _id ++ } );
  39192. /**
  39193. * The name of the uniforms group.
  39194. *
  39195. * @type {string}
  39196. */
  39197. this.name = '';
  39198. /**
  39199. * The buffer usage.
  39200. *
  39201. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39202. * @default StaticDrawUsage
  39203. */
  39204. this.usage = StaticDrawUsage;
  39205. /**
  39206. * An array holding the uniforms.
  39207. *
  39208. * @type {Array<Uniform>}
  39209. */
  39210. this.uniforms = [];
  39211. }
  39212. /**
  39213. * Adds the given uniform to this uniforms group.
  39214. *
  39215. * @param {Uniform} uniform - The uniform to add.
  39216. * @return {UniformsGroup} A reference to this uniforms group.
  39217. */
  39218. add( uniform ) {
  39219. this.uniforms.push( uniform );
  39220. return this;
  39221. }
  39222. /**
  39223. * Removes the given uniform from this uniforms group.
  39224. *
  39225. * @param {Uniform} uniform - The uniform to remove.
  39226. * @return {UniformsGroup} A reference to this uniforms group.
  39227. */
  39228. remove( uniform ) {
  39229. const index = this.uniforms.indexOf( uniform );
  39230. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39231. return this;
  39232. }
  39233. /**
  39234. * Sets the name of this uniforms group.
  39235. *
  39236. * @param {string} name - The name to set.
  39237. * @return {UniformsGroup} A reference to this uniforms group.
  39238. */
  39239. setName( name ) {
  39240. this.name = name;
  39241. return this;
  39242. }
  39243. /**
  39244. * Sets the usage of this uniforms group.
  39245. *
  39246. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39247. * @return {UniformsGroup} A reference to this uniforms group.
  39248. */
  39249. setUsage( value ) {
  39250. this.usage = value;
  39251. return this;
  39252. }
  39253. /**
  39254. * Frees the GPU-related resources allocated by this instance. Call this
  39255. * method whenever this instance is no longer used in your app.
  39256. *
  39257. * @fires Texture#dispose
  39258. */
  39259. dispose() {
  39260. this.dispatchEvent( { type: 'dispose' } );
  39261. }
  39262. /**
  39263. * Copies the values of the given uniforms group to this instance.
  39264. *
  39265. * @param {UniformsGroup} source - The uniforms group to copy.
  39266. * @return {UniformsGroup} A reference to this uniforms group.
  39267. */
  39268. copy( source ) {
  39269. this.name = source.name;
  39270. this.usage = source.usage;
  39271. const uniformsSource = source.uniforms;
  39272. this.uniforms.length = 0;
  39273. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39274. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39275. for ( let j = 0; j < uniforms.length; j ++ ) {
  39276. this.uniforms.push( uniforms[ j ].clone() );
  39277. }
  39278. }
  39279. return this;
  39280. }
  39281. /**
  39282. * Returns a new uniforms group with copied values from this instance.
  39283. *
  39284. * @return {UniformsGroup} A clone of this instance.
  39285. */
  39286. clone() {
  39287. return new this.constructor().copy( this );
  39288. }
  39289. }
  39290. /**
  39291. * An instanced version of an interleaved buffer.
  39292. *
  39293. * @augments InterleavedBuffer
  39294. */
  39295. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39296. /**
  39297. * Constructs a new instanced interleaved buffer.
  39298. *
  39299. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39300. * @param {number} stride - The number of typed-array elements per vertex.
  39301. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39302. */
  39303. constructor( array, stride, meshPerAttribute = 1 ) {
  39304. super( array, stride );
  39305. /**
  39306. * This flag can be used for type testing.
  39307. *
  39308. * @type {boolean}
  39309. * @readonly
  39310. * @default true
  39311. */
  39312. this.isInstancedInterleavedBuffer = true;
  39313. /**
  39314. * Defines how often a value of this buffer attribute should be repeated,
  39315. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39316. *
  39317. * @type {number}
  39318. * @default 1
  39319. */
  39320. this.meshPerAttribute = meshPerAttribute;
  39321. }
  39322. copy( source ) {
  39323. super.copy( source );
  39324. this.meshPerAttribute = source.meshPerAttribute;
  39325. return this;
  39326. }
  39327. clone( data ) {
  39328. const ib = super.clone( data );
  39329. ib.meshPerAttribute = this.meshPerAttribute;
  39330. return ib;
  39331. }
  39332. toJSON( data ) {
  39333. const json = super.toJSON( data );
  39334. json.isInstancedInterleavedBuffer = true;
  39335. json.meshPerAttribute = this.meshPerAttribute;
  39336. return json;
  39337. }
  39338. }
  39339. /**
  39340. * An alternative version of a buffer attribute with more control over the VBO.
  39341. *
  39342. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39343. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39344. *
  39345. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39346. * or even produces the VBOs in question.
  39347. *
  39348. * Notice that this class can only be used with {@link WebGLRenderer}.
  39349. */
  39350. class GLBufferAttribute {
  39351. /**
  39352. * Constructs a new GL buffer attribute.
  39353. *
  39354. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39355. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39356. * @param {number} itemSize - The item size.
  39357. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39358. * @param {number} count - The expected number of vertices in VBO.
  39359. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39360. */
  39361. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39362. /**
  39363. * This flag can be used for type testing.
  39364. *
  39365. * @type {boolean}
  39366. * @readonly
  39367. * @default true
  39368. */
  39369. this.isGLBufferAttribute = true;
  39370. /**
  39371. * The name of the buffer attribute.
  39372. *
  39373. * @type {string}
  39374. */
  39375. this.name = '';
  39376. /**
  39377. * The native WebGL buffer.
  39378. *
  39379. * @type {WebGLBuffer}
  39380. */
  39381. this.buffer = buffer;
  39382. /**
  39383. * The native data type.
  39384. *
  39385. * @type {number}
  39386. */
  39387. this.type = type;
  39388. /**
  39389. * The item size, see {@link BufferAttribute#itemSize}.
  39390. *
  39391. * @type {number}
  39392. */
  39393. this.itemSize = itemSize;
  39394. /**
  39395. * The corresponding size (in bytes) for the given `type` parameter.
  39396. *
  39397. * @type {number}
  39398. */
  39399. this.elementSize = elementSize;
  39400. /**
  39401. * The expected number of vertices in VBO.
  39402. *
  39403. * @type {number}
  39404. */
  39405. this.count = count;
  39406. /**
  39407. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39408. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39409. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39410. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39411. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39412. *
  39413. * @type {boolean}
  39414. */
  39415. this.normalized = normalized;
  39416. /**
  39417. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39418. *
  39419. * @type {number}
  39420. */
  39421. this.version = 0;
  39422. }
  39423. /**
  39424. * Flag to indicate that this attribute has changed and should be re-sent to
  39425. * the GPU. Set this to `true` when you modify the value of the array.
  39426. *
  39427. * @type {number}
  39428. * @default false
  39429. * @param {boolean} value
  39430. */
  39431. set needsUpdate( value ) {
  39432. if ( value === true ) this.version ++;
  39433. }
  39434. /**
  39435. * Sets the given native WebGL buffer.
  39436. *
  39437. * @param {WebGLBuffer} buffer - The buffer to set.
  39438. * @return {BufferAttribute} A reference to this instance.
  39439. */
  39440. setBuffer( buffer ) {
  39441. this.buffer = buffer;
  39442. return this;
  39443. }
  39444. /**
  39445. * Sets the given native data type and element size.
  39446. *
  39447. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39448. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39449. * @return {BufferAttribute} A reference to this instance.
  39450. */
  39451. setType( type, elementSize ) {
  39452. this.type = type;
  39453. this.elementSize = elementSize;
  39454. return this;
  39455. }
  39456. /**
  39457. * Sets the item size.
  39458. *
  39459. * @param {number} itemSize - The item size.
  39460. * @return {BufferAttribute} A reference to this instance.
  39461. */
  39462. setItemSize( itemSize ) {
  39463. this.itemSize = itemSize;
  39464. return this;
  39465. }
  39466. /**
  39467. * Sets the count (the expected number of vertices in VBO).
  39468. *
  39469. * @param {number} count - The count.
  39470. * @return {BufferAttribute} A reference to this instance.
  39471. */
  39472. setCount( count ) {
  39473. this.count = count;
  39474. return this;
  39475. }
  39476. }
  39477. const _matrix = /*@__PURE__*/ new Matrix4();
  39478. /**
  39479. * This class is designed to assist with raycasting. Raycasting is used for
  39480. * mouse picking (working out what objects in the 3d space the mouse is over)
  39481. * amongst other things.
  39482. */
  39483. class Raycaster {
  39484. /**
  39485. * Constructs a new raycaster.
  39486. *
  39487. * @param {Vector3} origin - The origin vector where the ray casts from.
  39488. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39489. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39490. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39491. */
  39492. constructor( origin, direction, near = 0, far = Infinity ) {
  39493. /**
  39494. * The ray used for raycasting.
  39495. *
  39496. * @type {Ray}
  39497. */
  39498. this.ray = new Ray( origin, direction );
  39499. /**
  39500. * All results returned are further away than near. Near can't be negative.
  39501. *
  39502. * @type {number}
  39503. * @default 0
  39504. */
  39505. this.near = near;
  39506. /**
  39507. * All results returned are further away than near. Near can't be negative.
  39508. *
  39509. * @type {number}
  39510. * @default Infinity
  39511. */
  39512. this.far = far;
  39513. /**
  39514. * The camera to use when raycasting against view-dependent objects such as
  39515. * billboarded objects like sprites. This field can be set manually or
  39516. * is set when calling `setFromCamera()`.
  39517. *
  39518. * @type {?Camera}
  39519. * @default null
  39520. */
  39521. this.camera = null;
  39522. /**
  39523. * Allows to selectively ignore 3D objects when performing intersection tests.
  39524. * The following code example ensures that only 3D objects on layer `1` will be
  39525. * honored by raycaster.
  39526. * ```js
  39527. * raycaster.layers.set( 1 );
  39528. * object.layers.enable( 1 );
  39529. * ```
  39530. *
  39531. * @type {Layers}
  39532. */
  39533. this.layers = new Layers();
  39534. /**
  39535. * A parameter object that configures the raycasting. It has the structure:
  39536. *
  39537. * ```
  39538. * {
  39539. * Mesh: {},
  39540. * Line: { threshold: 1 },
  39541. * LOD: {},
  39542. * Points: { threshold: 1 },
  39543. * Sprite: {}
  39544. * }
  39545. * ```
  39546. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39547. *
  39548. * @type {Object}
  39549. */
  39550. this.params = {
  39551. Mesh: {},
  39552. Line: { threshold: 1 },
  39553. LOD: {},
  39554. Points: { threshold: 1 },
  39555. Sprite: {}
  39556. };
  39557. }
  39558. /**
  39559. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39560. *
  39561. * @param {Vector3} origin - The origin vector where the ray casts from.
  39562. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39563. */
  39564. set( origin, direction ) {
  39565. // direction is assumed to be normalized (for accurate distance calculations)
  39566. this.ray.set( origin, direction );
  39567. }
  39568. /**
  39569. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39570. *
  39571. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39572. * X and Y components should be between `-1` and `1`.
  39573. * @param {Camera} camera - The camera from which the ray should originate.
  39574. */
  39575. setFromCamera( coords, camera ) {
  39576. if ( camera.isPerspectiveCamera ) {
  39577. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39578. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39579. this.camera = camera;
  39580. } else if ( camera.isOrthographicCamera ) {
  39581. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39582. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39583. this.camera = camera;
  39584. } else {
  39585. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  39586. }
  39587. }
  39588. /**
  39589. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39590. *
  39591. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39592. * @return {Raycaster} A reference to this raycaster.
  39593. */
  39594. setFromXRController( controller ) {
  39595. _matrix.identity().extractRotation( controller.matrixWorld );
  39596. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39597. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39598. return this;
  39599. }
  39600. /**
  39601. * The intersection point of a raycaster intersection test.
  39602. * @typedef {Object} Raycaster~Intersection
  39603. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39604. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39605. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39606. * @property {Vector3} point - The intersection point, in world coordinates.
  39607. * @property {Object} face - The face that has been intersected.
  39608. * @property {number} faceIndex - The face index.
  39609. * @property {Object3D} object - The 3D object that has been intersected.
  39610. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39611. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39612. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39613. * @property {number} instanceId - The index number of the instance where the ray
  39614. * intersects the {@link InstancedMesh}.
  39615. */
  39616. /**
  39617. * Checks all intersection between the ray and the object with or without the
  39618. * descendants. Intersections are returned sorted by distance, closest first.
  39619. *
  39620. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39621. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39622. * differently to ray casting than lines or points.
  39623. *
  39624. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39625. * to be detected; intersections of the ray passing through the back of a face will not
  39626. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39627. * to `THREE.DoubleSide`.
  39628. *
  39629. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39630. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39631. * Otherwise it only checks intersection with the object.
  39632. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39633. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39634. */
  39635. intersectObject( object, recursive = true, intersects = [] ) {
  39636. intersect( object, this, intersects, recursive );
  39637. intersects.sort( ascSort );
  39638. return intersects;
  39639. }
  39640. /**
  39641. * Checks all intersection between the ray and the objects with or without
  39642. * the descendants. Intersections are returned sorted by distance, closest first.
  39643. *
  39644. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39645. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39646. * Otherwise it only checks intersection with the object.
  39647. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39648. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39649. */
  39650. intersectObjects( objects, recursive = true, intersects = [] ) {
  39651. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39652. intersect( objects[ i ], this, intersects, recursive );
  39653. }
  39654. intersects.sort( ascSort );
  39655. return intersects;
  39656. }
  39657. }
  39658. function ascSort( a, b ) {
  39659. return a.distance - b.distance;
  39660. }
  39661. function intersect( object, raycaster, intersects, recursive ) {
  39662. let propagate = true;
  39663. if ( object.layers.test( raycaster.layers ) ) {
  39664. const result = object.raycast( raycaster, intersects );
  39665. if ( result === false ) propagate = false;
  39666. }
  39667. if ( propagate === true && recursive === true ) {
  39668. const children = object.children;
  39669. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39670. intersect( children[ i ], raycaster, intersects, true );
  39671. }
  39672. }
  39673. }
  39674. /**
  39675. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39676. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39677. *
  39678. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39679. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39680. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39681. * is inactive (e.g. tab switched or browser hidden).
  39682. *
  39683. * ```js
  39684. * const timer = new Timer();
  39685. * timer.connect( document ); // use Page Visibility API
  39686. * ```
  39687. */
  39688. class Timer {
  39689. /**
  39690. * Constructs a new timer.
  39691. */
  39692. constructor() {
  39693. this._previousTime = 0;
  39694. this._currentTime = 0;
  39695. this._startTime = performance.now();
  39696. this._delta = 0;
  39697. this._elapsed = 0;
  39698. this._timescale = 1;
  39699. this._document = null;
  39700. this._pageVisibilityHandler = null;
  39701. }
  39702. /**
  39703. * Connect the timer to the given document.Calling this method is not mandatory to
  39704. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39705. * delta values.
  39706. *
  39707. * @param {Document} document - The document.
  39708. */
  39709. connect( document ) {
  39710. this._document = document;
  39711. // use Page Visibility API to avoid large time delta values
  39712. if ( document.hidden !== undefined ) {
  39713. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39714. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39715. }
  39716. }
  39717. /**
  39718. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39719. */
  39720. disconnect() {
  39721. if ( this._pageVisibilityHandler !== null ) {
  39722. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39723. this._pageVisibilityHandler = null;
  39724. }
  39725. this._document = null;
  39726. }
  39727. /**
  39728. * Returns the time delta in seconds.
  39729. *
  39730. * @return {number} The time delta in second.
  39731. */
  39732. getDelta() {
  39733. return this._delta / 1000;
  39734. }
  39735. /**
  39736. * Returns the elapsed time in seconds.
  39737. *
  39738. * @return {number} The elapsed time in second.
  39739. */
  39740. getElapsed() {
  39741. return this._elapsed / 1000;
  39742. }
  39743. /**
  39744. * Returns the timescale.
  39745. *
  39746. * @return {number} The timescale.
  39747. */
  39748. getTimescale() {
  39749. return this._timescale;
  39750. }
  39751. /**
  39752. * Sets the given timescale which scale the time delta computation
  39753. * in `update()`.
  39754. *
  39755. * @param {number} timescale - The timescale to set.
  39756. * @return {Timer} A reference to this timer.
  39757. */
  39758. setTimescale( timescale ) {
  39759. this._timescale = timescale;
  39760. return this;
  39761. }
  39762. /**
  39763. * Resets the time computation for the current simulation step.
  39764. *
  39765. * @return {Timer} A reference to this timer.
  39766. */
  39767. reset() {
  39768. this._currentTime = performance.now() - this._startTime;
  39769. return this;
  39770. }
  39771. /**
  39772. * Can be used to free all internal resources. Usually called when
  39773. * the timer instance isn't required anymore.
  39774. */
  39775. dispose() {
  39776. this.disconnect();
  39777. }
  39778. /**
  39779. * Updates the internal state of the timer. This method should be called
  39780. * once per simulation step and before you perform queries against the timer
  39781. * (e.g. via `getDelta()`).
  39782. *
  39783. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39784. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39785. * time will be determined with `performance.now`.
  39786. * @return {Timer} A reference to this timer.
  39787. */
  39788. update( timestamp ) {
  39789. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39790. this._delta = 0;
  39791. } else {
  39792. this._previousTime = this._currentTime;
  39793. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39794. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39795. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39796. }
  39797. return this;
  39798. }
  39799. }
  39800. function handleVisibilityChange() {
  39801. if ( this._document.hidden === false ) this.reset();
  39802. }
  39803. /**
  39804. * This class can be used to represent points in 3D space as
  39805. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39806. */
  39807. class Spherical {
  39808. /**
  39809. * Constructs a new spherical.
  39810. *
  39811. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39812. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39813. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39814. */
  39815. constructor( radius = 1, phi = 0, theta = 0 ) {
  39816. /**
  39817. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39818. *
  39819. * @type {number}
  39820. * @default 1
  39821. */
  39822. this.radius = radius;
  39823. /**
  39824. * The polar angle in radians from the y (up) axis.
  39825. *
  39826. * @type {number}
  39827. * @default 0
  39828. */
  39829. this.phi = phi;
  39830. /**
  39831. * The equator/azimuthal angle in radians around the y (up) axis.
  39832. *
  39833. * @type {number}
  39834. * @default 0
  39835. */
  39836. this.theta = theta;
  39837. }
  39838. /**
  39839. * Sets the spherical components by copying the given values.
  39840. *
  39841. * @param {number} radius - The radius.
  39842. * @param {number} phi - The polar angle.
  39843. * @param {number} theta - The azimuthal angle.
  39844. * @return {Spherical} A reference to this spherical.
  39845. */
  39846. set( radius, phi, theta ) {
  39847. this.radius = radius;
  39848. this.phi = phi;
  39849. this.theta = theta;
  39850. return this;
  39851. }
  39852. /**
  39853. * Copies the values of the given spherical to this instance.
  39854. *
  39855. * @param {Spherical} other - The spherical to copy.
  39856. * @return {Spherical} A reference to this spherical.
  39857. */
  39858. copy( other ) {
  39859. this.radius = other.radius;
  39860. this.phi = other.phi;
  39861. this.theta = other.theta;
  39862. return this;
  39863. }
  39864. /**
  39865. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39866. * `0.000001`.
  39867. *
  39868. * @return {Spherical} A reference to this spherical.
  39869. */
  39870. makeSafe() {
  39871. const EPS = 0.000001;
  39872. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39873. return this;
  39874. }
  39875. /**
  39876. * Sets the spherical components from the given vector which is assumed to hold
  39877. * Cartesian coordinates.
  39878. *
  39879. * @param {Vector3} v - The vector to set.
  39880. * @return {Spherical} A reference to this spherical.
  39881. */
  39882. setFromVector3( v ) {
  39883. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39884. }
  39885. /**
  39886. * Sets the spherical components from the given Cartesian coordinates.
  39887. *
  39888. * @param {number} x - The x value.
  39889. * @param {number} y - The x value.
  39890. * @param {number} z - The x value.
  39891. * @return {Spherical} A reference to this spherical.
  39892. */
  39893. setFromCartesianCoords( x, y, z ) {
  39894. this.radius = Math.sqrt( x * x + y * y + z * z );
  39895. if ( this.radius === 0 ) {
  39896. this.theta = 0;
  39897. this.phi = 0;
  39898. } else {
  39899. this.theta = Math.atan2( x, z );
  39900. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  39901. }
  39902. return this;
  39903. }
  39904. /**
  39905. * Returns a new spherical with copied values from this instance.
  39906. *
  39907. * @return {Spherical} A clone of this instance.
  39908. */
  39909. clone() {
  39910. return new this.constructor().copy( this );
  39911. }
  39912. }
  39913. /**
  39914. * This class can be used to represent points in 3D space as
  39915. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  39916. */
  39917. class Cylindrical {
  39918. /**
  39919. * Constructs a new cylindrical.
  39920. *
  39921. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  39922. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39923. * @param {number} [y=0] - The height above the x-z plane.
  39924. */
  39925. constructor( radius = 1, theta = 0, y = 0 ) {
  39926. /**
  39927. * The distance from the origin to a point in the x-z plane.
  39928. *
  39929. * @type {number}
  39930. * @default 1
  39931. */
  39932. this.radius = radius;
  39933. /**
  39934. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  39935. *
  39936. * @type {number}
  39937. * @default 0
  39938. */
  39939. this.theta = theta;
  39940. /**
  39941. * The height above the x-z plane.
  39942. *
  39943. * @type {number}
  39944. * @default 0
  39945. */
  39946. this.y = y;
  39947. }
  39948. /**
  39949. * Sets the cylindrical components by copying the given values.
  39950. *
  39951. * @param {number} radius - The radius.
  39952. * @param {number} theta - The theta angle.
  39953. * @param {number} y - The height value.
  39954. * @return {Cylindrical} A reference to this cylindrical.
  39955. */
  39956. set( radius, theta, y ) {
  39957. this.radius = radius;
  39958. this.theta = theta;
  39959. this.y = y;
  39960. return this;
  39961. }
  39962. /**
  39963. * Copies the values of the given cylindrical to this instance.
  39964. *
  39965. * @param {Cylindrical} other - The cylindrical to copy.
  39966. * @return {Cylindrical} A reference to this cylindrical.
  39967. */
  39968. copy( other ) {
  39969. this.radius = other.radius;
  39970. this.theta = other.theta;
  39971. this.y = other.y;
  39972. return this;
  39973. }
  39974. /**
  39975. * Sets the cylindrical components from the given vector which is assumed to hold
  39976. * Cartesian coordinates.
  39977. *
  39978. * @param {Vector3} v - The vector to set.
  39979. * @return {Cylindrical} A reference to this cylindrical.
  39980. */
  39981. setFromVector3( v ) {
  39982. return this.setFromCartesianCoords( v.x, v.y, v.z );
  39983. }
  39984. /**
  39985. * Sets the cylindrical components from the given Cartesian coordinates.
  39986. *
  39987. * @param {number} x - The x value.
  39988. * @param {number} y - The x value.
  39989. * @param {number} z - The x value.
  39990. * @return {Cylindrical} A reference to this cylindrical.
  39991. */
  39992. setFromCartesianCoords( x, y, z ) {
  39993. this.radius = Math.sqrt( x * x + z * z );
  39994. this.theta = Math.atan2( x, z );
  39995. this.y = y;
  39996. return this;
  39997. }
  39998. /**
  39999. * Returns a new cylindrical with copied values from this instance.
  40000. *
  40001. * @return {Cylindrical} A clone of this instance.
  40002. */
  40003. clone() {
  40004. return new this.constructor().copy( this );
  40005. }
  40006. }
  40007. /**
  40008. * Represents a 2x2 matrix.
  40009. *
  40010. * A Note on Row-Major and Column-Major Ordering:
  40011. *
  40012. * The constructor and {@link Matrix2#set} method take arguments in
  40013. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40014. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40015. * This means that calling:
  40016. * ```js
  40017. * const m = new THREE.Matrix2();
  40018. * m.set( 11, 12,
  40019. * 21, 22 );
  40020. * ```
  40021. * will result in the elements array containing:
  40022. * ```js
  40023. * m.elements = [ 11, 21,
  40024. * 12, 22 ];
  40025. * ```
  40026. * and internally all calculations are performed using column-major ordering.
  40027. * However, as the actual ordering makes no difference mathematically and
  40028. * most people are used to thinking about matrices in row-major order, the
  40029. * three.js documentation shows matrices in row-major order. Just bear in
  40030. * mind that if you are reading the source code, you'll have to take the
  40031. * transpose of any matrices outlined here to make sense of the calculations.
  40032. */
  40033. class Matrix2 {
  40034. /**
  40035. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40036. * in row-major order. If no arguments are provided, the constructor
  40037. * initializes the matrix as an identity matrix.
  40038. *
  40039. * @param {number} [n11] - 1-1 matrix element.
  40040. * @param {number} [n12] - 1-2 matrix element.
  40041. * @param {number} [n21] - 2-1 matrix element.
  40042. * @param {number} [n22] - 2-2 matrix element.
  40043. */
  40044. constructor( n11, n12, n21, n22 ) {
  40045. /**
  40046. * This flag can be used for type testing.
  40047. *
  40048. * @type {boolean}
  40049. * @readonly
  40050. * @default true
  40051. */
  40052. Matrix2.prototype.isMatrix2 = true;
  40053. /**
  40054. * A column-major list of matrix values.
  40055. *
  40056. * @type {Array<number>}
  40057. */
  40058. this.elements = [
  40059. 1, 0,
  40060. 0, 1,
  40061. ];
  40062. if ( n11 !== undefined ) {
  40063. this.set( n11, n12, n21, n22 );
  40064. }
  40065. }
  40066. /**
  40067. * Sets this matrix to the 2x2 identity matrix.
  40068. *
  40069. * @return {Matrix2} A reference to this matrix.
  40070. */
  40071. identity() {
  40072. this.set(
  40073. 1, 0,
  40074. 0, 1,
  40075. );
  40076. return this;
  40077. }
  40078. /**
  40079. * Sets the elements of the matrix from the given array.
  40080. *
  40081. * @param {Array<number>} array - The matrix elements in column-major order.
  40082. * @param {number} [offset=0] - Index of the first element in the array.
  40083. * @return {Matrix2} A reference to this matrix.
  40084. */
  40085. fromArray( array, offset = 0 ) {
  40086. for ( let i = 0; i < 4; i ++ ) {
  40087. this.elements[ i ] = array[ i + offset ];
  40088. }
  40089. return this;
  40090. }
  40091. /**
  40092. * Sets the elements of the matrix.The arguments are supposed to be
  40093. * in row-major order.
  40094. *
  40095. * @param {number} n11 - 1-1 matrix element.
  40096. * @param {number} n12 - 1-2 matrix element.
  40097. * @param {number} n21 - 2-1 matrix element.
  40098. * @param {number} n22 - 2-2 matrix element.
  40099. * @return {Matrix2} A reference to this matrix.
  40100. */
  40101. set( n11, n12, n21, n22 ) {
  40102. const te = this.elements;
  40103. te[ 0 ] = n11; te[ 2 ] = n12;
  40104. te[ 1 ] = n21; te[ 3 ] = n22;
  40105. return this;
  40106. }
  40107. }
  40108. const _vector$4 = /*@__PURE__*/ new Vector2();
  40109. /**
  40110. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40111. */
  40112. class Box2 {
  40113. /**
  40114. * Constructs a new bounding box.
  40115. *
  40116. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40117. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40118. */
  40119. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40120. /**
  40121. * This flag can be used for type testing.
  40122. *
  40123. * @type {boolean}
  40124. * @readonly
  40125. * @default true
  40126. */
  40127. this.isBox2 = true;
  40128. /**
  40129. * The lower boundary of the box.
  40130. *
  40131. * @type {Vector2}
  40132. */
  40133. this.min = min;
  40134. /**
  40135. * The upper boundary of the box.
  40136. *
  40137. * @type {Vector2}
  40138. */
  40139. this.max = max;
  40140. }
  40141. /**
  40142. * Sets the lower and upper boundaries of this box.
  40143. * Please note that this method only copies the values from the given objects.
  40144. *
  40145. * @param {Vector2} min - The lower boundary of the box.
  40146. * @param {Vector2} max - The upper boundary of the box.
  40147. * @return {Box2} A reference to this bounding box.
  40148. */
  40149. set( min, max ) {
  40150. this.min.copy( min );
  40151. this.max.copy( max );
  40152. return this;
  40153. }
  40154. /**
  40155. * Sets the upper and lower bounds of this box so it encloses the position data
  40156. * in the given array.
  40157. *
  40158. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40159. * @return {Box2} A reference to this bounding box.
  40160. */
  40161. setFromPoints( points ) {
  40162. this.makeEmpty();
  40163. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40164. this.expandByPoint( points[ i ] );
  40165. }
  40166. return this;
  40167. }
  40168. /**
  40169. * Centers this box on the given center vector and sets this box's width, height and
  40170. * depth to the given size values.
  40171. *
  40172. * @param {Vector2} center - The center of the box.
  40173. * @param {Vector2} size - The x and y dimensions of the box.
  40174. * @return {Box2} A reference to this bounding box.
  40175. */
  40176. setFromCenterAndSize( center, size ) {
  40177. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40178. this.min.copy( center ).sub( halfSize );
  40179. this.max.copy( center ).add( halfSize );
  40180. return this;
  40181. }
  40182. /**
  40183. * Returns a new box with copied values from this instance.
  40184. *
  40185. * @return {Box2} A clone of this instance.
  40186. */
  40187. clone() {
  40188. return new this.constructor().copy( this );
  40189. }
  40190. /**
  40191. * Copies the values of the given box to this instance.
  40192. *
  40193. * @param {Box2} box - The box to copy.
  40194. * @return {Box2} A reference to this bounding box.
  40195. */
  40196. copy( box ) {
  40197. this.min.copy( box.min );
  40198. this.max.copy( box.max );
  40199. return this;
  40200. }
  40201. /**
  40202. * Makes this box empty which means in encloses a zero space in 2D.
  40203. *
  40204. * @return {Box2} A reference to this bounding box.
  40205. */
  40206. makeEmpty() {
  40207. this.min.x = this.min.y = + Infinity;
  40208. this.max.x = this.max.y = - Infinity;
  40209. return this;
  40210. }
  40211. /**
  40212. * Returns true if this box includes zero points within its bounds.
  40213. * Note that a box with equal lower and upper bounds still includes one
  40214. * point, the one both bounds share.
  40215. *
  40216. * @return {boolean} Whether this box is empty or not.
  40217. */
  40218. isEmpty() {
  40219. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40220. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40221. }
  40222. /**
  40223. * Returns the center point of this box.
  40224. *
  40225. * @param {Vector2} target - The target vector that is used to store the method's result.
  40226. * @return {Vector2} The center point.
  40227. */
  40228. getCenter( target ) {
  40229. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40230. }
  40231. /**
  40232. * Returns the dimensions of this box.
  40233. *
  40234. * @param {Vector2} target - The target vector that is used to store the method's result.
  40235. * @return {Vector2} The size.
  40236. */
  40237. getSize( target ) {
  40238. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40239. }
  40240. /**
  40241. * Expands the boundaries of this box to include the given point.
  40242. *
  40243. * @param {Vector2} point - The point that should be included by the bounding box.
  40244. * @return {Box2} A reference to this bounding box.
  40245. */
  40246. expandByPoint( point ) {
  40247. this.min.min( point );
  40248. this.max.max( point );
  40249. return this;
  40250. }
  40251. /**
  40252. * Expands this box equilaterally by the given vector. The width of this
  40253. * box will be expanded by the x component of the vector in both
  40254. * directions. The height of this box will be expanded by the y component of
  40255. * the vector in both directions.
  40256. *
  40257. * @param {Vector2} vector - The vector that should expand the bounding box.
  40258. * @return {Box2} A reference to this bounding box.
  40259. */
  40260. expandByVector( vector ) {
  40261. this.min.sub( vector );
  40262. this.max.add( vector );
  40263. return this;
  40264. }
  40265. /**
  40266. * Expands each dimension of the box by the given scalar. If negative, the
  40267. * dimensions of the box will be contracted.
  40268. *
  40269. * @param {number} scalar - The scalar value that should expand the bounding box.
  40270. * @return {Box2} A reference to this bounding box.
  40271. */
  40272. expandByScalar( scalar ) {
  40273. this.min.addScalar( - scalar );
  40274. this.max.addScalar( scalar );
  40275. return this;
  40276. }
  40277. /**
  40278. * Returns `true` if the given point lies within or on the boundaries of this box.
  40279. *
  40280. * @param {Vector2} point - The point to test.
  40281. * @return {boolean} Whether the bounding box contains the given point or not.
  40282. */
  40283. containsPoint( point ) {
  40284. return point.x >= this.min.x && point.x <= this.max.x &&
  40285. point.y >= this.min.y && point.y <= this.max.y;
  40286. }
  40287. /**
  40288. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40289. * If this box and the given one are identical, this function also returns `true`.
  40290. *
  40291. * @param {Box2} box - The bounding box to test.
  40292. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40293. */
  40294. containsBox( box ) {
  40295. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40296. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40297. }
  40298. /**
  40299. * Returns a point as a proportion of this box's width and height.
  40300. *
  40301. * @param {Vector2} point - A point in 2D space.
  40302. * @param {Vector2} target - The target vector that is used to store the method's result.
  40303. * @return {Vector2} A point as a proportion of this box's width and height.
  40304. */
  40305. getParameter( point, target ) {
  40306. // This can potentially have a divide by zero if the box
  40307. // has a size dimension of 0.
  40308. return target.set(
  40309. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40310. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40311. );
  40312. }
  40313. /**
  40314. * Returns `true` if the given bounding box intersects with this bounding box.
  40315. *
  40316. * @param {Box2} box - The bounding box to test.
  40317. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40318. */
  40319. intersectsBox( box ) {
  40320. // using 4 splitting planes to rule out intersections
  40321. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40322. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40323. }
  40324. /**
  40325. * Clamps the given point within the bounds of this box.
  40326. *
  40327. * @param {Vector2} point - The point to clamp.
  40328. * @param {Vector2} target - The target vector that is used to store the method's result.
  40329. * @return {Vector2} The clamped point.
  40330. */
  40331. clampPoint( point, target ) {
  40332. return target.copy( point ).clamp( this.min, this.max );
  40333. }
  40334. /**
  40335. * Returns the euclidean distance from any edge of this box to the specified point. If
  40336. * the given point lies inside of this box, the distance will be `0`.
  40337. *
  40338. * @param {Vector2} point - The point to compute the distance to.
  40339. * @return {number} The euclidean distance.
  40340. */
  40341. distanceToPoint( point ) {
  40342. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40343. }
  40344. /**
  40345. * Computes the intersection of this bounding box and the given one, setting the upper
  40346. * bound of this box to the lesser of the two boxes' upper bounds and the
  40347. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40348. * there's no overlap, makes this box empty.
  40349. *
  40350. * @param {Box2} box - The bounding box to intersect with.
  40351. * @return {Box2} A reference to this bounding box.
  40352. */
  40353. intersect( box ) {
  40354. this.min.max( box.min );
  40355. this.max.min( box.max );
  40356. if ( this.isEmpty() ) this.makeEmpty();
  40357. return this;
  40358. }
  40359. /**
  40360. * Computes the union of this box and another and the given one, setting the upper
  40361. * bound of this box to the greater of the two boxes' upper bounds and the
  40362. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40363. *
  40364. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40365. * @return {Box2} A reference to this bounding box.
  40366. */
  40367. union( box ) {
  40368. this.min.min( box.min );
  40369. this.max.max( box.max );
  40370. return this;
  40371. }
  40372. /**
  40373. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40374. * effectively moving it in 2D space.
  40375. *
  40376. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40377. * @return {Box2} A reference to this bounding box.
  40378. */
  40379. translate( offset ) {
  40380. this.min.add( offset );
  40381. this.max.add( offset );
  40382. return this;
  40383. }
  40384. /**
  40385. * Returns `true` if this bounding box is equal with the given one.
  40386. *
  40387. * @param {Box2} box - The box to test for equality.
  40388. * @return {boolean} Whether this bounding box is equal with the given one.
  40389. */
  40390. equals( box ) {
  40391. return box.min.equals( this.min ) && box.max.equals( this.max );
  40392. }
  40393. }
  40394. const _startP = /*@__PURE__*/ new Vector3();
  40395. const _startEnd = /*@__PURE__*/ new Vector3();
  40396. const _d1 = /*@__PURE__*/ new Vector3();
  40397. const _d2 = /*@__PURE__*/ new Vector3();
  40398. const _r = /*@__PURE__*/ new Vector3();
  40399. const _c1 = /*@__PURE__*/ new Vector3();
  40400. const _c2 = /*@__PURE__*/ new Vector3();
  40401. /**
  40402. * An analytical line segment in 3D space represented by a start and end point.
  40403. */
  40404. class Line3 {
  40405. /**
  40406. * Constructs a new line segment.
  40407. *
  40408. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40409. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40410. */
  40411. constructor( start = new Vector3(), end = new Vector3() ) {
  40412. /**
  40413. * Start of the line segment.
  40414. *
  40415. * @type {Vector3}
  40416. */
  40417. this.start = start;
  40418. /**
  40419. * End of the line segment.
  40420. *
  40421. * @type {Vector3}
  40422. */
  40423. this.end = end;
  40424. }
  40425. /**
  40426. * Sets the start and end values by copying the given vectors.
  40427. *
  40428. * @param {Vector3} start - The start point.
  40429. * @param {Vector3} end - The end point.
  40430. * @return {Line3} A reference to this line segment.
  40431. */
  40432. set( start, end ) {
  40433. this.start.copy( start );
  40434. this.end.copy( end );
  40435. return this;
  40436. }
  40437. /**
  40438. * Copies the values of the given line segment to this instance.
  40439. *
  40440. * @param {Line3} line - The line segment to copy.
  40441. * @return {Line3} A reference to this line segment.
  40442. */
  40443. copy( line ) {
  40444. this.start.copy( line.start );
  40445. this.end.copy( line.end );
  40446. return this;
  40447. }
  40448. /**
  40449. * Returns the center of the line segment.
  40450. *
  40451. * @param {Vector3} target - The target vector that is used to store the method's result.
  40452. * @return {Vector3} The center point.
  40453. */
  40454. getCenter( target ) {
  40455. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40456. }
  40457. /**
  40458. * Returns the delta vector of the line segment's start and end point.
  40459. *
  40460. * @param {Vector3} target - The target vector that is used to store the method's result.
  40461. * @return {Vector3} The delta vector.
  40462. */
  40463. delta( target ) {
  40464. return target.subVectors( this.end, this.start );
  40465. }
  40466. /**
  40467. * Returns the squared Euclidean distance between the line' start and end point.
  40468. *
  40469. * @return {number} The squared Euclidean distance.
  40470. */
  40471. distanceSq() {
  40472. return this.start.distanceToSquared( this.end );
  40473. }
  40474. /**
  40475. * Returns the Euclidean distance between the line' start and end point.
  40476. *
  40477. * @return {number} The Euclidean distance.
  40478. */
  40479. distance() {
  40480. return this.start.distanceTo( this.end );
  40481. }
  40482. /**
  40483. * Returns a vector at a certain position along the line segment.
  40484. *
  40485. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40486. * @param {Vector3} target - The target vector that is used to store the method's result.
  40487. * @return {Vector3} The delta vector.
  40488. */
  40489. at( t, target ) {
  40490. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40491. }
  40492. /**
  40493. * Returns a point parameter based on the closest point as projected on the line segment.
  40494. *
  40495. * @param {Vector3} point - The point for which to return a point parameter.
  40496. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40497. * @return {number} The point parameter.
  40498. */
  40499. closestPointToPointParameter( point, clampToLine ) {
  40500. _startP.subVectors( point, this.start );
  40501. _startEnd.subVectors( this.end, this.start );
  40502. const startEnd2 = _startEnd.dot( _startEnd );
  40503. const startEnd_startP = _startEnd.dot( _startP );
  40504. let t = startEnd_startP / startEnd2;
  40505. if ( clampToLine ) {
  40506. t = clamp( t, 0, 1 );
  40507. }
  40508. return t;
  40509. }
  40510. /**
  40511. * Returns the closest point on the line for a given point.
  40512. *
  40513. * @param {Vector3} point - The point to compute the closest point on the line for.
  40514. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40515. * @param {Vector3} target - The target vector that is used to store the method's result.
  40516. * @return {Vector3} The closest point on the line.
  40517. */
  40518. closestPointToPoint( point, clampToLine, target ) {
  40519. const t = this.closestPointToPointParameter( point, clampToLine );
  40520. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40521. }
  40522. /**
  40523. * Returns the closest squared distance between this line segment and the given one.
  40524. *
  40525. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40526. * @param {Vector3} [c1] - The closest point on this line segment.
  40527. * @param {Vector3} [c2] - The closest point on the given line segment.
  40528. * @return {number} The squared distance between this line segment and the given one.
  40529. */
  40530. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40531. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40532. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40533. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40534. // distance between between S1(s) and S2(t)
  40535. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40536. let s, t;
  40537. const p1 = this.start;
  40538. const p2 = line.start;
  40539. const q1 = this.end;
  40540. const q2 = line.end;
  40541. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40542. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40543. _r.subVectors( p1, p2 );
  40544. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40545. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40546. const f = _d2.dot( _r );
  40547. // Check if either or both segments degenerate into points
  40548. if ( a <= EPSILON && e <= EPSILON ) {
  40549. // Both segments degenerate into points
  40550. c1.copy( p1 );
  40551. c2.copy( p2 );
  40552. c1.sub( c2 );
  40553. return c1.dot( c1 );
  40554. }
  40555. if ( a <= EPSILON ) {
  40556. // First segment degenerates into a point
  40557. s = 0;
  40558. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40559. t = clamp( t, 0, 1 );
  40560. } else {
  40561. const c = _d1.dot( _r );
  40562. if ( e <= EPSILON ) {
  40563. // Second segment degenerates into a point
  40564. t = 0;
  40565. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40566. } else {
  40567. // The general nondegenerate case starts here
  40568. const b = _d1.dot( _d2 );
  40569. const denom = a * e - b * b; // Always nonnegative
  40570. // If segments not parallel, compute closest point on L1 to L2 and
  40571. // clamp to segment S1. Else pick arbitrary s (here 0)
  40572. if ( denom !== 0 ) {
  40573. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40574. } else {
  40575. s = 0;
  40576. }
  40577. // Compute point on L2 closest to S1(s) using
  40578. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40579. t = ( b * s + f ) / e;
  40580. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40581. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40582. // and clamp s to [0, 1]
  40583. if ( t < 0 ) {
  40584. t = 0.;
  40585. s = clamp( - c / a, 0, 1 );
  40586. } else if ( t > 1 ) {
  40587. t = 1;
  40588. s = clamp( ( b - c ) / a, 0, 1 );
  40589. }
  40590. }
  40591. }
  40592. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40593. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40594. c1.sub( c2 );
  40595. return c1.dot( c1 );
  40596. }
  40597. /**
  40598. * Applies a 4x4 transformation matrix to this line segment.
  40599. *
  40600. * @param {Matrix4} matrix - The transformation matrix.
  40601. * @return {Line3} A reference to this line segment.
  40602. */
  40603. applyMatrix4( matrix ) {
  40604. this.start.applyMatrix4( matrix );
  40605. this.end.applyMatrix4( matrix );
  40606. return this;
  40607. }
  40608. /**
  40609. * Returns `true` if this line segment is equal with the given one.
  40610. *
  40611. * @param {Line3} line - The line segment to test for equality.
  40612. * @return {boolean} Whether this line segment is equal with the given one.
  40613. */
  40614. equals( line ) {
  40615. return line.start.equals( this.start ) && line.end.equals( this.end );
  40616. }
  40617. /**
  40618. * Returns a new line segment with copied values from this instance.
  40619. *
  40620. * @return {Line3} A clone of this instance.
  40621. */
  40622. clone() {
  40623. return new this.constructor().copy( this );
  40624. }
  40625. }
  40626. const _vector$3 = /*@__PURE__*/ new Vector3();
  40627. /**
  40628. * This displays a cone shaped helper object for a {@link SpotLight}.
  40629. *
  40630. * ```js
  40631. * const spotLight = new THREE.SpotLight( 0xffffff );
  40632. * spotLight.position.set( 10, 10, 10 );
  40633. * scene.add( spotLight );
  40634. *
  40635. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40636. * scene.add( spotLightHelper );
  40637. * ```
  40638. *
  40639. * @augments Object3D
  40640. */
  40641. class SpotLightHelper extends Object3D {
  40642. /**
  40643. * Constructs a new spot light helper.
  40644. *
  40645. * @param {HemisphereLight} light - The light to be visualized.
  40646. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40647. * the color of the light.
  40648. */
  40649. constructor( light, color ) {
  40650. super();
  40651. /**
  40652. * The light being visualized.
  40653. *
  40654. * @type {SpotLight}
  40655. */
  40656. this.light = light;
  40657. this.matrixAutoUpdate = false;
  40658. /**
  40659. * The color parameter passed in the constructor.
  40660. * If not set, the helper will take the color of the light.
  40661. *
  40662. * @type {number|Color|string}
  40663. */
  40664. this.color = color;
  40665. this.type = 'SpotLightHelper';
  40666. const geometry = new BufferGeometry();
  40667. const positions = [
  40668. 0, 0, 0, 0, 0, 1,
  40669. 0, 0, 0, 1, 0, 1,
  40670. 0, 0, 0, -1, 0, 1,
  40671. 0, 0, 0, 0, 1, 1,
  40672. 0, 0, 0, 0, -1, 1
  40673. ];
  40674. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40675. const p1 = ( i / l ) * Math.PI * 2;
  40676. const p2 = ( j / l ) * Math.PI * 2;
  40677. positions.push(
  40678. Math.cos( p1 ), Math.sin( p1 ), 1,
  40679. Math.cos( p2 ), Math.sin( p2 ), 1
  40680. );
  40681. }
  40682. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40683. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40684. this.cone = new LineSegments( geometry, material );
  40685. this.add( this.cone );
  40686. this.update();
  40687. }
  40688. /**
  40689. * Frees the GPU-related resources allocated by this instance. Call this
  40690. * method whenever this instance is no longer used in your app.
  40691. */
  40692. dispose() {
  40693. this.cone.geometry.dispose();
  40694. this.cone.material.dispose();
  40695. }
  40696. /**
  40697. * Updates the helper to match the position and direction of the
  40698. * light being visualized.
  40699. */
  40700. update() {
  40701. this.light.updateWorldMatrix( true, false );
  40702. this.light.target.updateWorldMatrix( true, false );
  40703. // update the local matrix based on the parent and light target transforms
  40704. if ( this.parent ) {
  40705. this.parent.updateWorldMatrix( true );
  40706. this.matrix
  40707. .copy( this.parent.matrixWorld )
  40708. .invert()
  40709. .multiply( this.light.matrixWorld );
  40710. } else {
  40711. this.matrix.copy( this.light.matrixWorld );
  40712. }
  40713. this.matrixWorld.copy( this.light.matrixWorld );
  40714. const coneLength = this.light.distance ? this.light.distance : 1000;
  40715. const coneWidth = coneLength * Math.tan( this.light.angle );
  40716. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40717. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40718. this.cone.lookAt( _vector$3 );
  40719. if ( this.color !== undefined ) {
  40720. this.cone.material.color.set( this.color );
  40721. } else {
  40722. this.cone.material.color.copy( this.light.color );
  40723. }
  40724. }
  40725. }
  40726. const _vector$2 = /*@__PURE__*/ new Vector3();
  40727. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40728. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40729. /**
  40730. * A helper object to assist with visualizing a {@link Skeleton}.
  40731. *
  40732. * ```js
  40733. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40734. * scene.add( helper );
  40735. * ```
  40736. *
  40737. * @augments LineSegments
  40738. */
  40739. class SkeletonHelper extends LineSegments {
  40740. /**
  40741. * Constructs a new hemisphere light helper.
  40742. *
  40743. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40744. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40745. */
  40746. constructor( object ) {
  40747. const bones = getBoneList( object );
  40748. const geometry = new BufferGeometry();
  40749. const vertices = [];
  40750. const colors = [];
  40751. const color1 = new Color( 0, 0, 1 );
  40752. const color2 = new Color( 0, 1, 0 );
  40753. for ( let i = 0; i < bones.length; i ++ ) {
  40754. const bone = bones[ i ];
  40755. if ( bone.parent && bone.parent.isBone ) {
  40756. vertices.push( 0, 0, 0 );
  40757. vertices.push( 0, 0, 0 );
  40758. colors.push( color1.r, color1.g, color1.b );
  40759. colors.push( color2.r, color2.g, color2.b );
  40760. }
  40761. }
  40762. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40763. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40764. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40765. super( geometry, material );
  40766. /**
  40767. * This flag can be used for type testing.
  40768. *
  40769. * @type {boolean}
  40770. * @readonly
  40771. * @default true
  40772. */
  40773. this.isSkeletonHelper = true;
  40774. this.type = 'SkeletonHelper';
  40775. /**
  40776. * The object being visualized.
  40777. *
  40778. * @type {Object3D}
  40779. */
  40780. this.root = object;
  40781. /**
  40782. * The list of bones that the helper visualizes.
  40783. *
  40784. * @type {Array<Bone>}
  40785. */
  40786. this.bones = bones;
  40787. this.matrix = object.matrixWorld;
  40788. this.matrixAutoUpdate = false;
  40789. }
  40790. updateMatrixWorld( force ) {
  40791. const bones = this.bones;
  40792. const geometry = this.geometry;
  40793. const position = geometry.getAttribute( 'position' );
  40794. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40795. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40796. const bone = bones[ i ];
  40797. if ( bone.parent && bone.parent.isBone ) {
  40798. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40799. _vector$2.setFromMatrixPosition( _boneMatrix );
  40800. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40801. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40802. _vector$2.setFromMatrixPosition( _boneMatrix );
  40803. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40804. j += 2;
  40805. }
  40806. }
  40807. geometry.getAttribute( 'position' ).needsUpdate = true;
  40808. super.updateMatrixWorld( force );
  40809. }
  40810. /**
  40811. * Frees the GPU-related resources allocated by this instance. Call this
  40812. * method whenever this instance is no longer used in your app.
  40813. */
  40814. dispose() {
  40815. this.geometry.dispose();
  40816. this.material.dispose();
  40817. }
  40818. }
  40819. function getBoneList( object ) {
  40820. const boneList = [];
  40821. if ( object.isBone === true ) {
  40822. boneList.push( object );
  40823. }
  40824. for ( let i = 0; i < object.children.length; i ++ ) {
  40825. boneList.push( ...getBoneList( object.children[ i ] ) );
  40826. }
  40827. return boneList;
  40828. }
  40829. /**
  40830. * This displays a helper object consisting of a spherical mesh for
  40831. * visualizing an instance of {@link PointLight}.
  40832. *
  40833. * ```js
  40834. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40835. * pointLight.position.set( 10, 10, 10 );
  40836. * scene.add( pointLight );
  40837. *
  40838. * const sphereSize = 1;
  40839. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40840. * scene.add( pointLightHelper );
  40841. * ```
  40842. *
  40843. * @augments Mesh
  40844. */
  40845. class PointLightHelper extends Mesh {
  40846. /**
  40847. * Constructs a new point light helper.
  40848. *
  40849. * @param {PointLight} light - The light to be visualized.
  40850. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40851. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40852. * the color of the light.
  40853. */
  40854. constructor( light, sphereSize, color ) {
  40855. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40856. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40857. super( geometry, material );
  40858. /**
  40859. * The light being visualized.
  40860. *
  40861. * @type {HemisphereLight}
  40862. */
  40863. this.light = light;
  40864. /**
  40865. * The color parameter passed in the constructor.
  40866. * If not set, the helper will take the color of the light.
  40867. *
  40868. * @type {number|Color|string}
  40869. */
  40870. this.color = color;
  40871. this.type = 'PointLightHelper';
  40872. this.matrix = this.light.matrixWorld;
  40873. this.matrixAutoUpdate = false;
  40874. this.update();
  40875. /*
  40876. // TODO: delete this comment?
  40877. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  40878. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  40879. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  40880. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  40881. const d = light.distance;
  40882. if ( d === 0.0 ) {
  40883. this.lightDistance.visible = false;
  40884. } else {
  40885. this.lightDistance.scale.set( d, d, d );
  40886. }
  40887. this.add( this.lightDistance );
  40888. */
  40889. }
  40890. /**
  40891. * Frees the GPU-related resources allocated by this instance. Call this
  40892. * method whenever this instance is no longer used in your app.
  40893. */
  40894. dispose() {
  40895. this.geometry.dispose();
  40896. this.material.dispose();
  40897. }
  40898. /**
  40899. * Updates the helper to match the position of the
  40900. * light being visualized.
  40901. */
  40902. update() {
  40903. this.light.updateWorldMatrix( true, false );
  40904. if ( this.color !== undefined ) {
  40905. this.material.color.set( this.color );
  40906. } else {
  40907. this.material.color.copy( this.light.color );
  40908. }
  40909. /*
  40910. const d = this.light.distance;
  40911. if ( d === 0.0 ) {
  40912. this.lightDistance.visible = false;
  40913. } else {
  40914. this.lightDistance.visible = true;
  40915. this.lightDistance.scale.set( d, d, d );
  40916. }
  40917. */
  40918. }
  40919. }
  40920. const _vector$1 = /*@__PURE__*/ new Vector3();
  40921. const _color1 = /*@__PURE__*/ new Color();
  40922. const _color2 = /*@__PURE__*/ new Color();
  40923. /**
  40924. * Creates a visual aid consisting of a spherical mesh for a
  40925. * given {@link HemisphereLight}.
  40926. *
  40927. * ```js
  40928. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  40929. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  40930. * scene.add( helper );
  40931. * ```
  40932. *
  40933. * @augments Object3D
  40934. */
  40935. class HemisphereLightHelper extends Object3D {
  40936. /**
  40937. * Constructs a new hemisphere light helper.
  40938. *
  40939. * @param {HemisphereLight} light - The light to be visualized.
  40940. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  40941. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40942. * the color of the light.
  40943. */
  40944. constructor( light, size, color ) {
  40945. super();
  40946. /**
  40947. * The light being visualized.
  40948. *
  40949. * @type {HemisphereLight}
  40950. */
  40951. this.light = light;
  40952. this.matrix = light.matrixWorld;
  40953. this.matrixAutoUpdate = false;
  40954. /**
  40955. * The color parameter passed in the constructor.
  40956. * If not set, the helper will take the color of the light.
  40957. *
  40958. * @type {number|Color|string}
  40959. */
  40960. this.color = color;
  40961. this.type = 'HemisphereLightHelper';
  40962. const geometry = new OctahedronGeometry( size );
  40963. geometry.rotateY( Math.PI * 0.5 );
  40964. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  40965. if ( this.color === undefined ) this.material.vertexColors = true;
  40966. const position = geometry.getAttribute( 'position' );
  40967. const colors = new Float32Array( position.count * 3 );
  40968. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  40969. this.add( new Mesh( geometry, this.material ) );
  40970. this.update();
  40971. }
  40972. /**
  40973. * Frees the GPU-related resources allocated by this instance. Call this
  40974. * method whenever this instance is no longer used in your app.
  40975. */
  40976. dispose() {
  40977. this.children[ 0 ].geometry.dispose();
  40978. this.children[ 0 ].material.dispose();
  40979. }
  40980. /**
  40981. * Updates the helper to match the position and direction of the
  40982. * light being visualized.
  40983. */
  40984. update() {
  40985. const mesh = this.children[ 0 ];
  40986. if ( this.color !== undefined ) {
  40987. this.material.color.set( this.color );
  40988. } else {
  40989. const colors = mesh.geometry.getAttribute( 'color' );
  40990. _color1.copy( this.light.color );
  40991. _color2.copy( this.light.groundColor );
  40992. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  40993. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  40994. colors.setXYZ( i, color.r, color.g, color.b );
  40995. }
  40996. colors.needsUpdate = true;
  40997. }
  40998. this.light.updateWorldMatrix( true, false );
  40999. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41000. }
  41001. }
  41002. /**
  41003. * The helper is an object to define grids. Grids are two-dimensional
  41004. * arrays of lines.
  41005. *
  41006. * ```js
  41007. * const size = 10;
  41008. * const divisions = 10;
  41009. *
  41010. * const gridHelper = new THREE.GridHelper( size, divisions );
  41011. * scene.add( gridHelper );
  41012. * ```
  41013. *
  41014. * @augments LineSegments
  41015. */
  41016. class GridHelper extends LineSegments {
  41017. /**
  41018. * Constructs a new grid helper.
  41019. *
  41020. * @param {number} [size=10] - The size of the grid.
  41021. * @param {number} [divisions=10] - The number of divisions across the grid.
  41022. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41023. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41024. */
  41025. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41026. color1 = new Color( color1 );
  41027. color2 = new Color( color2 );
  41028. const center = divisions / 2;
  41029. const step = size / divisions;
  41030. const halfSize = size / 2;
  41031. const vertices = [], colors = [];
  41032. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41033. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41034. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41035. const color = i === center ? color1 : color2;
  41036. color.toArray( colors, j ); j += 3;
  41037. color.toArray( colors, j ); j += 3;
  41038. color.toArray( colors, j ); j += 3;
  41039. color.toArray( colors, j ); j += 3;
  41040. }
  41041. const geometry = new BufferGeometry();
  41042. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41043. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41044. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41045. super( geometry, material );
  41046. this.type = 'GridHelper';
  41047. }
  41048. /**
  41049. * Frees the GPU-related resources allocated by this instance. Call this
  41050. * method whenever this instance is no longer used in your app.
  41051. */
  41052. dispose() {
  41053. this.geometry.dispose();
  41054. this.material.dispose();
  41055. }
  41056. }
  41057. /**
  41058. * This helper is an object to define polar grids. Grids are
  41059. * two-dimensional arrays of lines.
  41060. *
  41061. * ```js
  41062. * const radius = 10;
  41063. * const sectors = 16;
  41064. * const rings = 8;
  41065. * const divisions = 64;
  41066. *
  41067. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41068. * scene.add( helper );
  41069. * ```
  41070. *
  41071. * @augments LineSegments
  41072. */
  41073. class PolarGridHelper extends LineSegments {
  41074. /**
  41075. * Constructs a new polar grid helper.
  41076. *
  41077. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41078. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41079. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41080. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41081. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41082. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41083. */
  41084. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41085. color1 = new Color( color1 );
  41086. color2 = new Color( color2 );
  41087. const vertices = [];
  41088. const colors = [];
  41089. // create the sectors
  41090. if ( sectors > 1 ) {
  41091. for ( let i = 0; i < sectors; i ++ ) {
  41092. const v = ( i / sectors ) * ( Math.PI * 2 );
  41093. const x = Math.sin( v ) * radius;
  41094. const z = Math.cos( v ) * radius;
  41095. vertices.push( 0, 0, 0 );
  41096. vertices.push( x, 0, z );
  41097. const color = ( i & 1 ) ? color1 : color2;
  41098. colors.push( color.r, color.g, color.b );
  41099. colors.push( color.r, color.g, color.b );
  41100. }
  41101. }
  41102. // create the rings
  41103. for ( let i = 0; i < rings; i ++ ) {
  41104. const color = ( i & 1 ) ? color1 : color2;
  41105. const r = radius - ( radius / rings * i );
  41106. for ( let j = 0; j < divisions; j ++ ) {
  41107. // first vertex
  41108. let v = ( j / divisions ) * ( Math.PI * 2 );
  41109. let x = Math.sin( v ) * r;
  41110. let z = Math.cos( v ) * r;
  41111. vertices.push( x, 0, z );
  41112. colors.push( color.r, color.g, color.b );
  41113. // second vertex
  41114. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41115. x = Math.sin( v ) * r;
  41116. z = Math.cos( v ) * r;
  41117. vertices.push( x, 0, z );
  41118. colors.push( color.r, color.g, color.b );
  41119. }
  41120. }
  41121. const geometry = new BufferGeometry();
  41122. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41123. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41124. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41125. super( geometry, material );
  41126. this.type = 'PolarGridHelper';
  41127. }
  41128. /**
  41129. * Frees the GPU-related resources allocated by this instance. Call this
  41130. * method whenever this instance is no longer used in your app.
  41131. */
  41132. dispose() {
  41133. this.geometry.dispose();
  41134. this.material.dispose();
  41135. }
  41136. }
  41137. const _v1 = /*@__PURE__*/ new Vector3();
  41138. const _v2 = /*@__PURE__*/ new Vector3();
  41139. const _v3 = /*@__PURE__*/ new Vector3();
  41140. /**
  41141. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41142. * effect on the scene. This consists of plane and a line representing the
  41143. * light's position and direction.
  41144. *
  41145. * ```js
  41146. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41147. * scene.add( light );
  41148. *
  41149. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41150. * scene.add( helper );
  41151. * ```
  41152. *
  41153. * @augments Object3D
  41154. */
  41155. class DirectionalLightHelper extends Object3D {
  41156. /**
  41157. * Constructs a new directional light helper.
  41158. *
  41159. * @param {DirectionalLight} light - The light to be visualized.
  41160. * @param {number} [size=1] - The dimensions of the plane.
  41161. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41162. * the color of the light.
  41163. */
  41164. constructor( light, size, color ) {
  41165. super();
  41166. /**
  41167. * The light being visualized.
  41168. *
  41169. * @type {DirectionalLight}
  41170. */
  41171. this.light = light;
  41172. this.matrix = light.matrixWorld;
  41173. this.matrixAutoUpdate = false;
  41174. /**
  41175. * The color parameter passed in the constructor.
  41176. * If not set, the helper will take the color of the light.
  41177. *
  41178. * @type {number|Color|string}
  41179. */
  41180. this.color = color;
  41181. this.type = 'DirectionalLightHelper';
  41182. if ( size === undefined ) size = 1;
  41183. let geometry = new BufferGeometry();
  41184. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41185. - size, size, 0,
  41186. size, size, 0,
  41187. size, - size, 0,
  41188. - size, - size, 0,
  41189. - size, size, 0
  41190. ], 3 ) );
  41191. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41192. /**
  41193. * Contains the line showing the location of the directional light.
  41194. *
  41195. * @type {Line}
  41196. */
  41197. this.lightPlane = new Line( geometry, material );
  41198. this.add( this.lightPlane );
  41199. geometry = new BufferGeometry();
  41200. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41201. /**
  41202. * Represents the target line of the directional light.
  41203. *
  41204. * @type {Line}
  41205. */
  41206. this.targetLine = new Line( geometry, material );
  41207. this.add( this.targetLine );
  41208. this.update();
  41209. }
  41210. /**
  41211. * Frees the GPU-related resources allocated by this instance. Call this
  41212. * method whenever this instance is no longer used in your app.
  41213. */
  41214. dispose() {
  41215. this.lightPlane.geometry.dispose();
  41216. this.lightPlane.material.dispose();
  41217. this.targetLine.geometry.dispose();
  41218. this.targetLine.material.dispose();
  41219. }
  41220. /**
  41221. * Updates the helper to match the position and direction of the
  41222. * light being visualized.
  41223. */
  41224. update() {
  41225. this.light.updateWorldMatrix( true, false );
  41226. this.light.target.updateWorldMatrix( true, false );
  41227. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41228. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41229. _v3.subVectors( _v2, _v1 );
  41230. this.lightPlane.lookAt( _v2 );
  41231. if ( this.color !== undefined ) {
  41232. this.lightPlane.material.color.set( this.color );
  41233. this.targetLine.material.color.set( this.color );
  41234. } else {
  41235. this.lightPlane.material.color.copy( this.light.color );
  41236. this.targetLine.material.color.copy( this.light.color );
  41237. }
  41238. this.targetLine.lookAt( _v2 );
  41239. this.targetLine.scale.z = _v3.length();
  41240. }
  41241. }
  41242. const _vector = /*@__PURE__*/ new Vector3();
  41243. const _camera = /*@__PURE__*/ new Camera();
  41244. /**
  41245. * This helps with visualizing what a camera contains in its frustum. It
  41246. * visualizes the frustum of a camera using a line segments.
  41247. *
  41248. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41249. *
  41250. * `CameraHelper` must be a child of the scene.
  41251. *
  41252. * ```js
  41253. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41254. * const helper = new THREE.CameraHelper( camera );
  41255. * scene.add( helper );
  41256. * ```
  41257. *
  41258. * @augments LineSegments
  41259. */
  41260. class CameraHelper extends LineSegments {
  41261. /**
  41262. * Constructs a new arrow helper.
  41263. *
  41264. * @param {Camera} camera - The camera to visualize.
  41265. */
  41266. constructor( camera ) {
  41267. const geometry = new BufferGeometry();
  41268. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41269. const vertices = [];
  41270. const colors = [];
  41271. const pointMap = {};
  41272. // near
  41273. addLine( 'n1', 'n2' );
  41274. addLine( 'n2', 'n4' );
  41275. addLine( 'n4', 'n3' );
  41276. addLine( 'n3', 'n1' );
  41277. // far
  41278. addLine( 'f1', 'f2' );
  41279. addLine( 'f2', 'f4' );
  41280. addLine( 'f4', 'f3' );
  41281. addLine( 'f3', 'f1' );
  41282. // sides
  41283. addLine( 'n1', 'f1' );
  41284. addLine( 'n2', 'f2' );
  41285. addLine( 'n3', 'f3' );
  41286. addLine( 'n4', 'f4' );
  41287. // cone
  41288. addLine( 'p', 'n1' );
  41289. addLine( 'p', 'n2' );
  41290. addLine( 'p', 'n3' );
  41291. addLine( 'p', 'n4' );
  41292. // up
  41293. addLine( 'u1', 'u2' );
  41294. addLine( 'u2', 'u3' );
  41295. addLine( 'u3', 'u1' );
  41296. // target
  41297. addLine( 'c', 't' );
  41298. addLine( 'p', 'c' );
  41299. // cross
  41300. addLine( 'cn1', 'cn2' );
  41301. addLine( 'cn3', 'cn4' );
  41302. addLine( 'cf1', 'cf2' );
  41303. addLine( 'cf3', 'cf4' );
  41304. function addLine( a, b ) {
  41305. addPoint( a );
  41306. addPoint( b );
  41307. }
  41308. function addPoint( id ) {
  41309. vertices.push( 0, 0, 0 );
  41310. colors.push( 0, 0, 0 );
  41311. if ( pointMap[ id ] === undefined ) {
  41312. pointMap[ id ] = [];
  41313. }
  41314. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41315. }
  41316. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41317. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41318. super( geometry, material );
  41319. this.type = 'CameraHelper';
  41320. /**
  41321. * The camera being visualized.
  41322. *
  41323. * @type {Camera}
  41324. */
  41325. this.camera = camera;
  41326. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41327. this.matrix = camera.matrixWorld;
  41328. this.matrixAutoUpdate = false;
  41329. /**
  41330. * This contains the points used to visualize the camera.
  41331. *
  41332. * @type {Object<string,Array<number>>}
  41333. */
  41334. this.pointMap = pointMap;
  41335. this.update();
  41336. // colors
  41337. const colorFrustum = new Color( 0xffaa00 );
  41338. const colorCone = new Color( 0xff0000 );
  41339. const colorUp = new Color( 0x00aaff );
  41340. const colorTarget = new Color( 0xffffff );
  41341. const colorCross = new Color( 0x333333 );
  41342. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41343. }
  41344. /**
  41345. * Defines the colors of the helper.
  41346. *
  41347. * @param {Color} frustum - The frustum line color.
  41348. * @param {Color} cone - The cone line color.
  41349. * @param {Color} up - The up line color.
  41350. * @param {Color} target - The target line color.
  41351. * @param {Color} cross - The cross line color.
  41352. */
  41353. setColors( frustum, cone, up, target, cross ) {
  41354. const geometry = this.geometry;
  41355. const colorAttribute = geometry.getAttribute( 'color' );
  41356. // near
  41357. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41358. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41359. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41360. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41361. // far
  41362. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41363. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41364. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41365. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41366. // sides
  41367. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41368. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41369. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41370. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41371. // cone
  41372. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41373. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41374. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41375. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41376. // up
  41377. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41378. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41379. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41380. // target
  41381. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41382. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41383. // cross
  41384. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41385. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41386. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41387. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41388. colorAttribute.needsUpdate = true;
  41389. }
  41390. /**
  41391. * Updates the helper based on the projection matrix of the camera.
  41392. */
  41393. update() {
  41394. const geometry = this.geometry;
  41395. const pointMap = this.pointMap;
  41396. const w = 1, h = 1;
  41397. let nearZ, farZ;
  41398. // we need just camera projection matrix inverse
  41399. // world matrix must be identity
  41400. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41401. // Adjust z values based on coordinate system
  41402. if ( this.camera.reversedDepth === true ) {
  41403. nearZ = 1;
  41404. farZ = 0;
  41405. } else {
  41406. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41407. nearZ = -1;
  41408. farZ = 1;
  41409. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41410. nearZ = 0;
  41411. farZ = 1;
  41412. } else {
  41413. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41414. }
  41415. }
  41416. // center / target
  41417. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41418. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41419. // near
  41420. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41421. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41422. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41423. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41424. // far
  41425. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41426. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41427. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41428. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41429. // up
  41430. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41431. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41432. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41433. // cross
  41434. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41435. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41436. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41437. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41438. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41439. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41440. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41441. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41442. geometry.getAttribute( 'position' ).needsUpdate = true;
  41443. }
  41444. /**
  41445. * Frees the GPU-related resources allocated by this instance. Call this
  41446. * method whenever this instance is no longer used in your app.
  41447. */
  41448. dispose() {
  41449. this.geometry.dispose();
  41450. this.material.dispose();
  41451. }
  41452. }
  41453. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41454. _vector.set( x, y, z ).unproject( camera );
  41455. const points = pointMap[ point ];
  41456. if ( points !== undefined ) {
  41457. const position = geometry.getAttribute( 'position' );
  41458. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41459. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41460. }
  41461. }
  41462. }
  41463. const _box = /*@__PURE__*/ new Box3();
  41464. /**
  41465. * Helper object to graphically show the world-axis-aligned bounding box
  41466. * around an object. The actual bounding box is handled with {@link Box3},
  41467. * this is just a visual helper for debugging. It can be automatically
  41468. * resized with {@link BoxHelper#update} when the object it's created from
  41469. * is transformed. Note that the object must have a geometry for this to work,
  41470. * so it won't work with sprites.
  41471. *
  41472. * ```js
  41473. * const sphere = new THREE.SphereGeometry();
  41474. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41475. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41476. * scene.add( box );
  41477. * ```
  41478. *
  41479. * @augments LineSegments
  41480. */
  41481. class BoxHelper extends LineSegments {
  41482. /**
  41483. * Constructs a new box helper.
  41484. *
  41485. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41486. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41487. */
  41488. constructor( object, color = 0xffff00 ) {
  41489. 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 ] );
  41490. const positions = new Float32Array( 8 * 3 );
  41491. const geometry = new BufferGeometry();
  41492. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41493. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41494. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41495. /**
  41496. * The 3D object being visualized.
  41497. *
  41498. * @type {Object3D}
  41499. */
  41500. this.object = object;
  41501. this.type = 'BoxHelper';
  41502. this.matrixAutoUpdate = false;
  41503. this.update();
  41504. }
  41505. /**
  41506. * Updates the helper's geometry to match the dimensions of the object,
  41507. * including any children.
  41508. */
  41509. update() {
  41510. if ( this.object !== undefined ) {
  41511. _box.setFromObject( this.object );
  41512. }
  41513. if ( _box.isEmpty() ) return;
  41514. const min = _box.min;
  41515. const max = _box.max;
  41516. /*
  41517. 5____4
  41518. 1/___0/|
  41519. | 6__|_7
  41520. 2/___3/
  41521. 0: max.x, max.y, max.z
  41522. 1: min.x, max.y, max.z
  41523. 2: min.x, min.y, max.z
  41524. 3: max.x, min.y, max.z
  41525. 4: max.x, max.y, min.z
  41526. 5: min.x, max.y, min.z
  41527. 6: min.x, min.y, min.z
  41528. 7: max.x, min.y, min.z
  41529. */
  41530. const position = this.geometry.attributes.position;
  41531. const array = position.array;
  41532. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41533. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41534. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41535. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41536. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41537. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41538. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41539. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41540. position.needsUpdate = true;
  41541. this.geometry.computeBoundingSphere();
  41542. }
  41543. /**
  41544. * Updates the wireframe box for the passed object.
  41545. *
  41546. * @param {Object3D} object - The 3D object to create the helper for.
  41547. * @return {BoxHelper} A reference to this instance.
  41548. */
  41549. setFromObject( object ) {
  41550. this.object = object;
  41551. this.update();
  41552. return this;
  41553. }
  41554. copy( source, recursive ) {
  41555. super.copy( source, recursive );
  41556. this.object = source.object;
  41557. return this;
  41558. }
  41559. /**
  41560. * Frees the GPU-related resources allocated by this instance. Call this
  41561. * method whenever this instance is no longer used in your app.
  41562. */
  41563. dispose() {
  41564. this.geometry.dispose();
  41565. this.material.dispose();
  41566. }
  41567. }
  41568. /**
  41569. * A helper object to visualize an instance of {@link Box3}.
  41570. *
  41571. * ```js
  41572. * const box = new THREE.Box3();
  41573. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41574. *
  41575. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41576. * scene.add( helper )
  41577. * ```
  41578. *
  41579. * @augments LineSegments
  41580. */
  41581. class Box3Helper extends LineSegments {
  41582. /**
  41583. * Constructs a new box3 helper.
  41584. *
  41585. * @param {Box3} box - The box to visualize.
  41586. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41587. */
  41588. constructor( box, color = 0xffff00 ) {
  41589. 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 ] );
  41590. 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 ];
  41591. const geometry = new BufferGeometry();
  41592. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41593. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41594. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41595. /**
  41596. * The box being visualized.
  41597. *
  41598. * @type {Box3}
  41599. */
  41600. this.box = box;
  41601. this.type = 'Box3Helper';
  41602. this.geometry.computeBoundingSphere();
  41603. }
  41604. updateMatrixWorld( force ) {
  41605. const box = this.box;
  41606. if ( box.isEmpty() ) return;
  41607. box.getCenter( this.position );
  41608. box.getSize( this.scale );
  41609. this.scale.multiplyScalar( 0.5 );
  41610. super.updateMatrixWorld( force );
  41611. }
  41612. /**
  41613. * Frees the GPU-related resources allocated by this instance. Call this
  41614. * method whenever this instance is no longer used in your app.
  41615. */
  41616. dispose() {
  41617. this.geometry.dispose();
  41618. this.material.dispose();
  41619. }
  41620. }
  41621. /**
  41622. * A helper object to visualize an instance of {@link Plane}.
  41623. *
  41624. * ```js
  41625. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41626. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41627. * scene.add( helper );
  41628. * ```
  41629. *
  41630. * @augments Line
  41631. */
  41632. class PlaneHelper extends Line {
  41633. /**
  41634. * Constructs a new plane helper.
  41635. *
  41636. * @param {Plane} plane - The plane to be visualized.
  41637. * @param {number} [size=1] - The side length of plane helper.
  41638. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41639. */
  41640. constructor( plane, size = 1, hex = 0xffff00 ) {
  41641. const color = hex;
  41642. 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 ];
  41643. const geometry = new BufferGeometry();
  41644. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41645. geometry.computeBoundingSphere();
  41646. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41647. this.type = 'PlaneHelper';
  41648. /**
  41649. * The plane being visualized.
  41650. *
  41651. * @type {Plane}
  41652. */
  41653. this.plane = plane;
  41654. /**
  41655. * The side length of plane helper.
  41656. *
  41657. * @type {number}
  41658. * @default 1
  41659. */
  41660. this.size = size;
  41661. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41662. const geometry2 = new BufferGeometry();
  41663. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41664. geometry2.computeBoundingSphere();
  41665. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41666. }
  41667. updateMatrixWorld( force ) {
  41668. this.position.set( 0, 0, 0 );
  41669. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41670. this.lookAt( this.plane.normal );
  41671. this.translateZ( - this.plane.constant );
  41672. super.updateMatrixWorld( force );
  41673. }
  41674. /**
  41675. * Updates the helper to match the position and direction of the
  41676. * light being visualized.
  41677. */
  41678. dispose() {
  41679. this.geometry.dispose();
  41680. this.material.dispose();
  41681. this.children[ 0 ].geometry.dispose();
  41682. this.children[ 0 ].material.dispose();
  41683. }
  41684. }
  41685. const _axis = /*@__PURE__*/ new Vector3();
  41686. let _lineGeometry, _coneGeometry;
  41687. /**
  41688. * An 3D arrow object for visualizing directions.
  41689. *
  41690. * ```js
  41691. * const dir = new THREE.Vector3( 1, 2, 0 );
  41692. *
  41693. * //normalize the direction vector (convert to vector of length 1)
  41694. * dir.normalize();
  41695. *
  41696. * const origin = new THREE.Vector3( 0, 0, 0 );
  41697. * const length = 1;
  41698. * const hex = 0xffff00;
  41699. *
  41700. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41701. * scene.add( arrowHelper );
  41702. * ```
  41703. *
  41704. * @augments Object3D
  41705. */
  41706. class ArrowHelper extends Object3D {
  41707. /**
  41708. * Constructs a new arrow helper.
  41709. *
  41710. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41711. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41712. * @param {number} [length=1] - Length of the arrow in world units.
  41713. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41714. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41715. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41716. */
  41717. 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 ) {
  41718. super();
  41719. this.type = 'ArrowHelper';
  41720. if ( _lineGeometry === undefined ) {
  41721. _lineGeometry = new BufferGeometry();
  41722. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41723. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41724. _coneGeometry.translate( 0, -0.5, 0 );
  41725. }
  41726. this.position.copy( origin );
  41727. /**
  41728. * The line part of the arrow helper.
  41729. *
  41730. * @type {Line}
  41731. */
  41732. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41733. this.line.matrixAutoUpdate = false;
  41734. this.add( this.line );
  41735. /**
  41736. * The cone part of the arrow helper.
  41737. *
  41738. * @type {Mesh}
  41739. */
  41740. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41741. this.cone.matrixAutoUpdate = false;
  41742. this.add( this.cone );
  41743. this.setDirection( dir );
  41744. this.setLength( length, headLength, headWidth );
  41745. }
  41746. /**
  41747. * Sets the direction of the helper.
  41748. *
  41749. * @param {Vector3} dir - The normalized direction vector.
  41750. */
  41751. setDirection( dir ) {
  41752. // dir is assumed to be normalized
  41753. if ( dir.y > 0.99999 ) {
  41754. this.quaternion.set( 0, 0, 0, 1 );
  41755. } else if ( dir.y < -0.99999 ) {
  41756. this.quaternion.set( 1, 0, 0, 0 );
  41757. } else {
  41758. _axis.set( dir.z, 0, - dir.x ).normalize();
  41759. const radians = Math.acos( dir.y );
  41760. this.quaternion.setFromAxisAngle( _axis, radians );
  41761. }
  41762. }
  41763. /**
  41764. * Sets the length of the helper.
  41765. *
  41766. * @param {number} length - Length of the arrow in world units.
  41767. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41768. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41769. */
  41770. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41771. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41772. this.line.updateMatrix();
  41773. this.cone.scale.set( headWidth, headLength, headWidth );
  41774. this.cone.position.y = length;
  41775. this.cone.updateMatrix();
  41776. }
  41777. /**
  41778. * Sets the color of the helper.
  41779. *
  41780. * @param {number|Color|string} color - The color to set.
  41781. */
  41782. setColor( color ) {
  41783. this.line.material.color.set( color );
  41784. this.cone.material.color.set( color );
  41785. }
  41786. copy( source ) {
  41787. super.copy( source, false );
  41788. this.line.copy( source.line );
  41789. this.cone.copy( source.cone );
  41790. return this;
  41791. }
  41792. /**
  41793. * Frees the GPU-related resources allocated by this instance. Call this
  41794. * method whenever this instance is no longer used in your app.
  41795. */
  41796. dispose() {
  41797. this.line.geometry.dispose();
  41798. this.line.material.dispose();
  41799. this.cone.geometry.dispose();
  41800. this.cone.material.dispose();
  41801. }
  41802. }
  41803. /**
  41804. * An axis object to visualize the 3 axes in a simple way.
  41805. * The X axis is red. The Y axis is green. The Z axis is blue.
  41806. *
  41807. * ```js
  41808. * const axesHelper = new THREE.AxesHelper( 5 );
  41809. * scene.add( axesHelper );
  41810. * ```
  41811. *
  41812. * @augments LineSegments
  41813. */
  41814. class AxesHelper extends LineSegments {
  41815. /**
  41816. * Constructs a new axes helper.
  41817. *
  41818. * @param {number} [size=1] - Size of the lines representing the axes.
  41819. */
  41820. constructor( size = 1 ) {
  41821. const vertices = [
  41822. 0, 0, 0, size, 0, 0,
  41823. 0, 0, 0, 0, size, 0,
  41824. 0, 0, 0, 0, 0, size
  41825. ];
  41826. const colors = [
  41827. 1, 0, 0, 1, 0.6, 0,
  41828. 0, 1, 0, 0.6, 1, 0,
  41829. 0, 0, 1, 0, 0.6, 1
  41830. ];
  41831. const geometry = new BufferGeometry();
  41832. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41833. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41834. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41835. super( geometry, material );
  41836. this.type = 'AxesHelper';
  41837. }
  41838. /**
  41839. * Defines the colors of the axes helper.
  41840. *
  41841. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41842. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41843. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41844. * @return {AxesHelper} A reference to this axes helper.
  41845. */
  41846. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41847. const color = new Color();
  41848. const array = this.geometry.attributes.color.array;
  41849. color.set( xAxisColor );
  41850. color.toArray( array, 0 );
  41851. color.toArray( array, 3 );
  41852. color.set( yAxisColor );
  41853. color.toArray( array, 6 );
  41854. color.toArray( array, 9 );
  41855. color.set( zAxisColor );
  41856. color.toArray( array, 12 );
  41857. color.toArray( array, 15 );
  41858. this.geometry.attributes.color.needsUpdate = true;
  41859. return this;
  41860. }
  41861. /**
  41862. * Frees the GPU-related resources allocated by this instance. Call this
  41863. * method whenever this instance is no longer used in your app.
  41864. */
  41865. dispose() {
  41866. this.geometry.dispose();
  41867. this.material.dispose();
  41868. }
  41869. }
  41870. /**
  41871. * This class is used to convert a series of paths to an array of
  41872. * shapes. It is specifically used in context of fonts and SVG.
  41873. */
  41874. class ShapePath {
  41875. /**
  41876. * Constructs a new shape path.
  41877. */
  41878. constructor() {
  41879. this.type = 'ShapePath';
  41880. /**
  41881. * The color of the shape.
  41882. *
  41883. * @type {Color}
  41884. */
  41885. this.color = new Color();
  41886. /**
  41887. * The paths that have been generated for this shape.
  41888. *
  41889. * @type {Array<Path>}
  41890. * @default null
  41891. */
  41892. this.subPaths = [];
  41893. /**
  41894. * The current path that is being generated.
  41895. *
  41896. * @type {?Path}
  41897. * @default null
  41898. */
  41899. this.currentPath = null;
  41900. }
  41901. /**
  41902. * Creates a new path and moves it current point to the given one.
  41903. *
  41904. * @param {number} x - The x coordinate.
  41905. * @param {number} y - The y coordinate.
  41906. * @return {ShapePath} A reference to this shape path.
  41907. */
  41908. moveTo( x, y ) {
  41909. this.currentPath = new Path();
  41910. this.subPaths.push( this.currentPath );
  41911. this.currentPath.moveTo( x, y );
  41912. return this;
  41913. }
  41914. /**
  41915. * Adds an instance of {@link LineCurve} to the path by connecting
  41916. * the current point with the given one.
  41917. *
  41918. * @param {number} x - The x coordinate of the end point.
  41919. * @param {number} y - The y coordinate of the end point.
  41920. * @return {ShapePath} A reference to this shape path.
  41921. */
  41922. lineTo( x, y ) {
  41923. this.currentPath.lineTo( x, y );
  41924. return this;
  41925. }
  41926. /**
  41927. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  41928. * the current point with the given one.
  41929. *
  41930. * @param {number} aCPx - The x coordinate of the control point.
  41931. * @param {number} aCPy - The y coordinate of the control point.
  41932. * @param {number} aX - The x coordinate of the end point.
  41933. * @param {number} aY - The y coordinate of the end point.
  41934. * @return {ShapePath} A reference to this shape path.
  41935. */
  41936. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  41937. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  41938. return this;
  41939. }
  41940. /**
  41941. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  41942. * the current point with the given one.
  41943. *
  41944. * @param {number} aCP1x - The x coordinate of the first control point.
  41945. * @param {number} aCP1y - The y coordinate of the first control point.
  41946. * @param {number} aCP2x - The x coordinate of the second control point.
  41947. * @param {number} aCP2y - The y coordinate of the second control point.
  41948. * @param {number} aX - The x coordinate of the end point.
  41949. * @param {number} aY - The y coordinate of the end point.
  41950. * @return {ShapePath} A reference to this shape path.
  41951. */
  41952. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  41953. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  41954. return this;
  41955. }
  41956. /**
  41957. * Adds an instance of {@link SplineCurve} to the path by connecting
  41958. * the current point with the given list of points.
  41959. *
  41960. * @param {Array<Vector2>} pts - An array of points in 2D space.
  41961. * @return {ShapePath} A reference to this shape path.
  41962. */
  41963. splineThru( pts ) {
  41964. this.currentPath.splineThru( pts );
  41965. return this;
  41966. }
  41967. /**
  41968. * Converts the paths into an array of shapes.
  41969. *
  41970. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  41971. * If this flag is set to `true`, then those are flipped.
  41972. * @return {Array<Shape>} An array of shapes.
  41973. */
  41974. toShapes( isCCW ) {
  41975. function toShapesNoHoles( inSubpaths ) {
  41976. const shapes = [];
  41977. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  41978. const tmpPath = inSubpaths[ i ];
  41979. const tmpShape = new Shape();
  41980. tmpShape.curves = tmpPath.curves;
  41981. shapes.push( tmpShape );
  41982. }
  41983. return shapes;
  41984. }
  41985. function isPointInsidePolygon( inPt, inPolygon ) {
  41986. const polyLen = inPolygon.length;
  41987. // inPt on polygon contour => immediate success or
  41988. // toggling of inside/outside at every single! intersection point of an edge
  41989. // with the horizontal line through inPt, left of inPt
  41990. // not counting lowerY endpoints of edges and whole edges on that line
  41991. let inside = false;
  41992. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  41993. let edgeLowPt = inPolygon[ p ];
  41994. let edgeHighPt = inPolygon[ q ];
  41995. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  41996. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  41997. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  41998. // not parallel
  41999. if ( edgeDy < 0 ) {
  42000. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42001. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42002. }
  42003. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42004. if ( inPt.y === edgeLowPt.y ) {
  42005. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42006. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42007. } else {
  42008. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42009. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42010. if ( perpEdge < 0 ) continue;
  42011. inside = ! inside; // true intersection left of inPt
  42012. }
  42013. } else {
  42014. // parallel or collinear
  42015. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42016. // edge lies on the same horizontal line as inPt
  42017. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42018. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42019. // continue;
  42020. }
  42021. }
  42022. return inside;
  42023. }
  42024. const isClockWise = ShapeUtils.isClockWise;
  42025. const subPaths = this.subPaths;
  42026. if ( subPaths.length === 0 ) return [];
  42027. let solid, tmpPath, tmpShape;
  42028. const shapes = [];
  42029. if ( subPaths.length === 1 ) {
  42030. tmpPath = subPaths[ 0 ];
  42031. tmpShape = new Shape();
  42032. tmpShape.curves = tmpPath.curves;
  42033. shapes.push( tmpShape );
  42034. return shapes;
  42035. }
  42036. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42037. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42038. // console.log("Holes first", holesFirst);
  42039. const betterShapeHoles = [];
  42040. const newShapes = [];
  42041. let newShapeHoles = [];
  42042. let mainIdx = 0;
  42043. let tmpPoints;
  42044. newShapes[ mainIdx ] = undefined;
  42045. newShapeHoles[ mainIdx ] = [];
  42046. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42047. tmpPath = subPaths[ i ];
  42048. tmpPoints = tmpPath.getPoints();
  42049. solid = isClockWise( tmpPoints );
  42050. solid = isCCW ? ! solid : solid;
  42051. if ( solid ) {
  42052. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42053. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42054. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42055. if ( holesFirst ) mainIdx ++;
  42056. newShapeHoles[ mainIdx ] = [];
  42057. //console.log('cw', i);
  42058. } else {
  42059. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42060. //console.log('ccw', i);
  42061. }
  42062. }
  42063. // only Holes? -> probably all Shapes with wrong orientation
  42064. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42065. if ( newShapes.length > 1 ) {
  42066. let ambiguous = false;
  42067. let toChange = 0;
  42068. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42069. betterShapeHoles[ sIdx ] = [];
  42070. }
  42071. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42072. const sho = newShapeHoles[ sIdx ];
  42073. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42074. const ho = sho[ hIdx ];
  42075. let hole_unassigned = true;
  42076. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42077. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42078. if ( sIdx !== s2Idx ) toChange ++;
  42079. if ( hole_unassigned ) {
  42080. hole_unassigned = false;
  42081. betterShapeHoles[ s2Idx ].push( ho );
  42082. } else {
  42083. ambiguous = true;
  42084. }
  42085. }
  42086. }
  42087. if ( hole_unassigned ) {
  42088. betterShapeHoles[ sIdx ].push( ho );
  42089. }
  42090. }
  42091. }
  42092. if ( toChange > 0 && ambiguous === false ) {
  42093. newShapeHoles = betterShapeHoles;
  42094. }
  42095. }
  42096. let tmpHoles;
  42097. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42098. tmpShape = newShapes[ i ].s;
  42099. shapes.push( tmpShape );
  42100. tmpHoles = newShapeHoles[ i ];
  42101. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42102. tmpShape.holes.push( tmpHoles[ j ].h );
  42103. }
  42104. }
  42105. //console.log("shape", shapes);
  42106. return shapes;
  42107. }
  42108. }
  42109. /**
  42110. * Abstract base class for controls.
  42111. *
  42112. * @abstract
  42113. * @augments EventDispatcher
  42114. */
  42115. class Controls extends EventDispatcher {
  42116. /**
  42117. * Constructs a new controls instance.
  42118. *
  42119. * @param {Object3D} object - The object that is managed by the controls.
  42120. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  42121. */
  42122. constructor( object, domElement = null ) {
  42123. super();
  42124. /**
  42125. * The object that is managed by the controls.
  42126. *
  42127. * @type {Object3D}
  42128. */
  42129. this.object = object;
  42130. /**
  42131. * The HTML element used for event listeners.
  42132. *
  42133. * @type {?HTMLDOMElement}
  42134. * @default null
  42135. */
  42136. this.domElement = domElement;
  42137. /**
  42138. * Whether the controls responds to user input or not.
  42139. *
  42140. * @type {boolean}
  42141. * @default true
  42142. */
  42143. this.enabled = true;
  42144. /**
  42145. * The internal state of the controls.
  42146. *
  42147. * @type {number}
  42148. * @default -1
  42149. */
  42150. this.state = -1;
  42151. /**
  42152. * This object defines the keyboard input of the controls.
  42153. *
  42154. * @type {Object}
  42155. */
  42156. this.keys = {};
  42157. /**
  42158. * This object defines what type of actions are assigned to the available mouse buttons.
  42159. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42160. *
  42161. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42162. */
  42163. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42164. /**
  42165. * This object defines what type of actions are assigned to what kind of touch interaction.
  42166. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42167. *
  42168. * @type {{ONE: ?number, TWO: ?number}}
  42169. */
  42170. this.touches = { ONE: null, TWO: null };
  42171. }
  42172. /**
  42173. * Connects the controls to the DOM. This method has so called "side effects" since
  42174. * it adds the module's event listeners to the DOM.
  42175. *
  42176. * @param {HTMLDOMElement} element - The DOM element to connect to.
  42177. */
  42178. connect( element ) {
  42179. if ( element === undefined ) {
  42180. console.warn( 'THREE.Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42181. return;
  42182. }
  42183. if ( this.domElement !== null ) this.disconnect();
  42184. this.domElement = element;
  42185. }
  42186. /**
  42187. * Disconnects the controls from the DOM.
  42188. */
  42189. disconnect() {}
  42190. /**
  42191. * Call this method if you no longer want use to the controls. It frees all internal
  42192. * resources and removes all event listeners.
  42193. */
  42194. dispose() {}
  42195. /**
  42196. * Controls should implement this method if they have to update their internal state
  42197. * per simulation step.
  42198. *
  42199. * @param {number} [delta] - The time delta in seconds.
  42200. */
  42201. update( /* delta */ ) {}
  42202. }
  42203. /**
  42204. * Scales the texture as large as possible within its surface without cropping
  42205. * or stretching the texture. The method preserves the original aspect ratio of
  42206. * the texture. Akin to CSS `object-fit: contain`
  42207. *
  42208. * @param {Texture} texture - The texture.
  42209. * @param {number} aspect - The texture's aspect ratio.
  42210. * @return {Texture} The updated texture.
  42211. */
  42212. function contain( texture, aspect ) {
  42213. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42214. if ( imageAspect > aspect ) {
  42215. texture.repeat.x = 1;
  42216. texture.repeat.y = imageAspect / aspect;
  42217. texture.offset.x = 0;
  42218. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42219. } else {
  42220. texture.repeat.x = aspect / imageAspect;
  42221. texture.repeat.y = 1;
  42222. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42223. texture.offset.y = 0;
  42224. }
  42225. return texture;
  42226. }
  42227. /**
  42228. * Scales the texture to the smallest possible size to fill the surface, leaving
  42229. * no empty space. The method preserves the original aspect ratio of the texture.
  42230. * Akin to CSS `object-fit: cover`.
  42231. *
  42232. * @param {Texture} texture - The texture.
  42233. * @param {number} aspect - The texture's aspect ratio.
  42234. * @return {Texture} The updated texture.
  42235. */
  42236. function cover( texture, aspect ) {
  42237. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42238. if ( imageAspect > aspect ) {
  42239. texture.repeat.x = aspect / imageAspect;
  42240. texture.repeat.y = 1;
  42241. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42242. texture.offset.y = 0;
  42243. } else {
  42244. texture.repeat.x = 1;
  42245. texture.repeat.y = imageAspect / aspect;
  42246. texture.offset.x = 0;
  42247. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42248. }
  42249. return texture;
  42250. }
  42251. /**
  42252. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42253. *
  42254. * @param {Texture} texture - The texture.
  42255. * @return {Texture} The updated texture.
  42256. */
  42257. function fill( texture ) {
  42258. texture.repeat.x = 1;
  42259. texture.repeat.y = 1;
  42260. texture.offset.x = 0;
  42261. texture.offset.y = 0;
  42262. return texture;
  42263. }
  42264. /**
  42265. * Determines how many bytes must be used to represent the texture.
  42266. *
  42267. * @param {number} width - The width of the texture.
  42268. * @param {number} height - The height of the texture.
  42269. * @param {number} format - The texture's format.
  42270. * @param {number} type - The texture's type.
  42271. * @return {number} The byte length.
  42272. */
  42273. function getByteLength( width, height, format, type ) {
  42274. const typeByteLength = getTextureTypeByteLength( type );
  42275. switch ( format ) {
  42276. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42277. case AlphaFormat:
  42278. return width * height;
  42279. case RedFormat:
  42280. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42281. case RedIntegerFormat:
  42282. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42283. case RGFormat:
  42284. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42285. case RGIntegerFormat:
  42286. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42287. case RGBFormat:
  42288. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42289. case RGBAFormat:
  42290. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42291. case RGBAIntegerFormat:
  42292. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42293. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42294. case RGB_S3TC_DXT1_Format:
  42295. case RGBA_S3TC_DXT1_Format:
  42296. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42297. case RGBA_S3TC_DXT3_Format:
  42298. case RGBA_S3TC_DXT5_Format:
  42299. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42300. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42301. case RGB_PVRTC_2BPPV1_Format:
  42302. case RGBA_PVRTC_2BPPV1_Format:
  42303. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42304. case RGB_PVRTC_4BPPV1_Format:
  42305. case RGBA_PVRTC_4BPPV1_Format:
  42306. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42307. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42308. case RGB_ETC1_Format:
  42309. case RGB_ETC2_Format:
  42310. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42311. case RGBA_ETC2_EAC_Format:
  42312. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42313. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42314. case RGBA_ASTC_4x4_Format:
  42315. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42316. case RGBA_ASTC_5x4_Format:
  42317. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42318. case RGBA_ASTC_5x5_Format:
  42319. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42320. case RGBA_ASTC_6x5_Format:
  42321. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42322. case RGBA_ASTC_6x6_Format:
  42323. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42324. case RGBA_ASTC_8x5_Format:
  42325. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42326. case RGBA_ASTC_8x6_Format:
  42327. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42328. case RGBA_ASTC_8x8_Format:
  42329. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42330. case RGBA_ASTC_10x5_Format:
  42331. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42332. case RGBA_ASTC_10x6_Format:
  42333. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42334. case RGBA_ASTC_10x8_Format:
  42335. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42336. case RGBA_ASTC_10x10_Format:
  42337. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42338. case RGBA_ASTC_12x10_Format:
  42339. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42340. case RGBA_ASTC_12x12_Format:
  42341. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42342. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42343. case RGBA_BPTC_Format:
  42344. case RGB_BPTC_SIGNED_Format:
  42345. case RGB_BPTC_UNSIGNED_Format:
  42346. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42347. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42348. case RED_RGTC1_Format:
  42349. case SIGNED_RED_RGTC1_Format:
  42350. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42351. case RED_GREEN_RGTC2_Format:
  42352. case SIGNED_RED_GREEN_RGTC2_Format:
  42353. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42354. }
  42355. throw new Error(
  42356. `Unable to determine texture byte length for ${format} format.`,
  42357. );
  42358. }
  42359. function getTextureTypeByteLength( type ) {
  42360. switch ( type ) {
  42361. case UnsignedByteType:
  42362. case ByteType:
  42363. return { byteLength: 1, components: 1 };
  42364. case UnsignedShortType:
  42365. case ShortType:
  42366. case HalfFloatType:
  42367. return { byteLength: 2, components: 1 };
  42368. case UnsignedShort4444Type:
  42369. case UnsignedShort5551Type:
  42370. return { byteLength: 2, components: 4 };
  42371. case UnsignedIntType:
  42372. case IntType:
  42373. case FloatType:
  42374. return { byteLength: 4, components: 1 };
  42375. case UnsignedInt5999Type:
  42376. return { byteLength: 4, components: 3 };
  42377. }
  42378. throw new Error( `Unknown texture type ${type}.` );
  42379. }
  42380. /**
  42381. * A class containing utility functions for textures.
  42382. *
  42383. * @hideconstructor
  42384. */
  42385. class TextureUtils {
  42386. /**
  42387. * Scales the texture as large as possible within its surface without cropping
  42388. * or stretching the texture. The method preserves the original aspect ratio of
  42389. * the texture. Akin to CSS `object-fit: contain`
  42390. *
  42391. * @param {Texture} texture - The texture.
  42392. * @param {number} aspect - The texture's aspect ratio.
  42393. * @return {Texture} The updated texture.
  42394. */
  42395. static contain( texture, aspect ) {
  42396. return contain( texture, aspect );
  42397. }
  42398. /**
  42399. * Scales the texture to the smallest possible size to fill the surface, leaving
  42400. * no empty space. The method preserves the original aspect ratio of the texture.
  42401. * Akin to CSS `object-fit: cover`.
  42402. *
  42403. * @param {Texture} texture - The texture.
  42404. * @param {number} aspect - The texture's aspect ratio.
  42405. * @return {Texture} The updated texture.
  42406. */
  42407. static cover( texture, aspect ) {
  42408. return cover( texture, aspect );
  42409. }
  42410. /**
  42411. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42412. *
  42413. * @param {Texture} texture - The texture.
  42414. * @return {Texture} The updated texture.
  42415. */
  42416. static fill( texture ) {
  42417. return fill( texture );
  42418. }
  42419. /**
  42420. * Determines how many bytes must be used to represent the texture.
  42421. *
  42422. * @param {number} width - The width of the texture.
  42423. * @param {number} height - The height of the texture.
  42424. * @param {number} format - The texture's format.
  42425. * @param {number} type - The texture's type.
  42426. * @return {number} The byte length.
  42427. */
  42428. static getByteLength( width, height, format, type ) {
  42429. return getByteLength( width, height, format, type );
  42430. }
  42431. }
  42432. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42433. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42434. revision: REVISION,
  42435. } } ) );
  42436. }
  42437. if ( typeof window !== 'undefined' ) {
  42438. if ( window.__THREE__ ) {
  42439. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42440. } else {
  42441. window.__THREE__ = REVISION;
  42442. }
  42443. }
  42444. 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号