three.core.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '174';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const ZeroStencilOp = 0;
  170. const KeepStencilOp = 7680;
  171. const ReplaceStencilOp = 7681;
  172. const IncrementStencilOp = 7682;
  173. const DecrementStencilOp = 7683;
  174. const IncrementWrapStencilOp = 34055;
  175. const DecrementWrapStencilOp = 34056;
  176. const InvertStencilOp = 5386;
  177. const NeverStencilFunc = 512;
  178. const LessStencilFunc = 513;
  179. const EqualStencilFunc = 514;
  180. const LessEqualStencilFunc = 515;
  181. const GreaterStencilFunc = 516;
  182. const NotEqualStencilFunc = 517;
  183. const GreaterEqualStencilFunc = 518;
  184. const AlwaysStencilFunc = 519;
  185. const NeverCompare = 512;
  186. const LessCompare = 513;
  187. const EqualCompare = 514;
  188. const LessEqualCompare = 515;
  189. const GreaterCompare = 516;
  190. const NotEqualCompare = 517;
  191. const GreaterEqualCompare = 518;
  192. const AlwaysCompare = 519;
  193. const StaticDrawUsage = 35044;
  194. const DynamicDrawUsage = 35048;
  195. const StreamDrawUsage = 35040;
  196. const StaticReadUsage = 35045;
  197. const DynamicReadUsage = 35049;
  198. const StreamReadUsage = 35041;
  199. const StaticCopyUsage = 35046;
  200. const DynamicCopyUsage = 35050;
  201. const StreamCopyUsage = 35042;
  202. const GLSL1 = '100';
  203. const GLSL3 = '300 es';
  204. const WebGLCoordinateSystem = 2000;
  205. const WebGPUCoordinateSystem = 2001;
  206. const TimestampQuery = {
  207. COMPUTE: 'compute',
  208. RENDER: 'render'
  209. };
  210. /**
  211. * This modules allows to dispatch event objects on custom JavaScript objects.
  212. *
  213. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  214. *
  215. * Code Example:
  216. * ```js
  217. * class Car extends EventDispatcher {
  218. * start() {
  219. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  220. * }
  221. *};
  222. *
  223. * // Using events with the custom object
  224. * const car = new Car();
  225. * car.addEventListener( 'start', function ( event ) {
  226. * alert( event.message );
  227. * } );
  228. *
  229. * car.start();
  230. * ```
  231. */
  232. class EventDispatcher {
  233. /**
  234. * Adds the given event listener to the given event type.
  235. *
  236. * @param {string} type - The type of event to listen to.
  237. * @param {Function} listener - The function that gets called when the event is fired.
  238. */
  239. addEventListener( type, listener ) {
  240. if ( this._listeners === undefined ) this._listeners = {};
  241. const listeners = this._listeners;
  242. if ( listeners[ type ] === undefined ) {
  243. listeners[ type ] = [];
  244. }
  245. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  246. listeners[ type ].push( listener );
  247. }
  248. }
  249. /**
  250. * Returns `true` if the given event listener has been added to the given event type.
  251. *
  252. * @param {string} type - The type of event.
  253. * @param {Function} listener - The listener to check.
  254. * @return {boolean} Whether the given event listener has been added to the given event type.
  255. */
  256. hasEventListener( type, listener ) {
  257. const listeners = this._listeners;
  258. if ( listeners === undefined ) return false;
  259. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  260. }
  261. /**
  262. * Removes the given event listener from the given event type.
  263. *
  264. * @param {string} type - The type of event.
  265. * @param {Function} listener - The listener to remove.
  266. */
  267. removeEventListener( type, listener ) {
  268. const listeners = this._listeners;
  269. if ( listeners === undefined ) return;
  270. const listenerArray = listeners[ type ];
  271. if ( listenerArray !== undefined ) {
  272. const index = listenerArray.indexOf( listener );
  273. if ( index !== -1 ) {
  274. listenerArray.splice( index, 1 );
  275. }
  276. }
  277. }
  278. /**
  279. * Dispatches an event object.
  280. *
  281. * @param {Object} event - The event that gets fired.
  282. */
  283. dispatchEvent( event ) {
  284. const listeners = this._listeners;
  285. if ( listeners === undefined ) return;
  286. const listenerArray = listeners[ event.type ];
  287. if ( listenerArray !== undefined ) {
  288. event.target = this;
  289. // Make a copy, in case listeners are removed while iterating.
  290. const array = listenerArray.slice( 0 );
  291. for ( let i = 0, l = array.length; i < l; i ++ ) {
  292. array[ i ].call( this, event );
  293. }
  294. event.target = null;
  295. }
  296. }
  297. }
  298. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  299. let _seed = 1234567;
  300. const DEG2RAD = Math.PI / 180;
  301. const RAD2DEG = 180 / Math.PI;
  302. /**
  303. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  304. * (universally unique identifier).
  305. *
  306. * @return {string} The UUID.
  307. */
  308. function generateUUID() {
  309. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  310. const d0 = Math.random() * 0xffffffff | 0;
  311. const d1 = Math.random() * 0xffffffff | 0;
  312. const d2 = Math.random() * 0xffffffff | 0;
  313. const d3 = Math.random() * 0xffffffff | 0;
  314. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  315. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  316. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  317. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  318. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  319. return uuid.toLowerCase();
  320. }
  321. /**
  322. * Clamps the given value between min and max.
  323. *
  324. * @param {number} value - The value to clamp.
  325. * @param {number} min - The min value.
  326. * @param {number} max - The max value.
  327. * @return {number} The clamped value.
  328. */
  329. function clamp( value, min, max ) {
  330. return Math.max( min, Math.min( max, value ) );
  331. }
  332. /**
  333. * Computes the Euclidean modulo of the given parameters that
  334. * is `( ( n % m ) + m ) % m`.
  335. *
  336. * @param {number} n - The first parameter.
  337. * @param {number} m - The second parameter.
  338. * @return {number} The Euclidean modulo.
  339. */
  340. function euclideanModulo( n, m ) {
  341. // https://en.wikipedia.org/wiki/Modulo_operation
  342. return ( ( n % m ) + m ) % m;
  343. }
  344. /**
  345. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  346. * for the given value.
  347. *
  348. * @param {number} x - The value to be mapped.
  349. * @param {number} a1 - Minimum value for range A.
  350. * @param {number} a2 - Maximum value for range A.
  351. * @param {number} b1 - Minimum value for range B.
  352. * @param {number} b2 - Maximum value for range B.
  353. * @return {number} The mapped value.
  354. */
  355. function mapLinear( x, a1, a2, b1, b2 ) {
  356. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  357. }
  358. /**
  359. * Returns the percentage in the closed interval `[0, 1]` of the given value
  360. * between the start and end point.
  361. *
  362. * @param {number} x - The start point
  363. * @param {number} y - The end point.
  364. * @param {number} value - A value between start and end.
  365. * @return {number} The interpolation factor.
  366. */
  367. function inverseLerp( x, y, value ) {
  368. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  369. if ( x !== y ) {
  370. return ( value - x ) / ( y - x );
  371. } else {
  372. return 0;
  373. }
  374. }
  375. /**
  376. * Returns a value linearly interpolated from two known points based on the given interval -
  377. * `t = 0` will return `x` and `t = 1` will return `y`.
  378. *
  379. * @param {number} x - The start point
  380. * @param {number} y - The end point.
  381. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  382. * @return {number} The interpolated value.
  383. */
  384. function lerp( x, y, t ) {
  385. return ( 1 - t ) * x + t * y;
  386. }
  387. /**
  388. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  389. * time to maintain frame rate independent movement. For details, see
  390. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  391. *
  392. * @param {number} x - The current point.
  393. * @param {number} y - The target point.
  394. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  395. * and a lower value will make the movement more gradual.
  396. * @param {number} dt - Delta time in seconds.
  397. * @return {number} The interpolated value.
  398. */
  399. function damp( x, y, lambda, dt ) {
  400. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  401. }
  402. /**
  403. * Returns a value that alternates between `0` and the given `length` parameter.
  404. *
  405. * @param {number} x - The value to pingpong.
  406. * @param {number} [length=1] - The positive value the function will pingpong to.
  407. * @return {number} The alternated value.
  408. */
  409. function pingpong( x, length = 1 ) {
  410. // https://www.desmos.com/calculator/vcsjnyz7x4
  411. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  412. }
  413. /**
  414. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  415. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  416. * the `min` and `max`.
  417. *
  418. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  419. *
  420. * @param {number} x - The value to evaluate based on its position between min and max.
  421. * @param {number} min - The min value. Any x value below min will be `0`.
  422. * @param {number} max - The max value. Any x value above max will be `1`.
  423. * @return {number} The alternated value.
  424. */
  425. function smoothstep( x, min, max ) {
  426. if ( x <= min ) return 0;
  427. if ( x >= max ) return 1;
  428. x = ( x - min ) / ( max - min );
  429. return x * x * ( 3 - 2 * x );
  430. }
  431. /**
  432. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  433. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  434. *
  435. * @param {number} x - The value to evaluate based on its position between min and max.
  436. * @param {number} min - The min value. Any x value below min will be `0`.
  437. * @param {number} max - The max value. Any x value above max will be `1`.
  438. * @return {number} The alternated value.
  439. */
  440. function smootherstep( x, min, max ) {
  441. if ( x <= min ) return 0;
  442. if ( x >= max ) return 1;
  443. x = ( x - min ) / ( max - min );
  444. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  445. }
  446. /**
  447. * Returns a random integer from `<low, high>` interval.
  448. *
  449. * @param {number} low - The lower value boundary.
  450. * @param {number} high - The upper value boundary
  451. * @return {number} A random integer.
  452. */
  453. function randInt( low, high ) {
  454. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  455. }
  456. /**
  457. * Returns a random float from `<low, high>` interval.
  458. *
  459. * @param {number} low - The lower value boundary.
  460. * @param {number} high - The upper value boundary
  461. * @return {number} A random float.
  462. */
  463. function randFloat( low, high ) {
  464. return low + Math.random() * ( high - low );
  465. }
  466. /**
  467. * Returns a random integer from `<-range/2, range/2>` interval.
  468. *
  469. * @param {number} range - Defines the value range.
  470. * @return {number} A random float.
  471. */
  472. function randFloatSpread( range ) {
  473. return range * ( 0.5 - Math.random() );
  474. }
  475. /**
  476. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  477. *
  478. * @param {number} [s] - The integer seed.
  479. * @return {number} A random float.
  480. */
  481. function seededRandom( s ) {
  482. if ( s !== undefined ) _seed = s;
  483. // Mulberry32 generator
  484. let t = _seed += 0x6D2B79F5;
  485. t = Math.imul( t ^ t >>> 15, t | 1 );
  486. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  487. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  488. }
  489. /**
  490. * Converts degrees to radians.
  491. *
  492. * @param {number} degrees - A value in degrees.
  493. * @return {number} The converted value in radians.
  494. */
  495. function degToRad( degrees ) {
  496. return degrees * DEG2RAD;
  497. }
  498. /**
  499. * Converts radians to degrees.
  500. *
  501. * @param {number} radians - A value in radians.
  502. * @return {number} The converted value in degrees.
  503. */
  504. function radToDeg( radians ) {
  505. return radians * RAD2DEG;
  506. }
  507. /**
  508. * Returns `true` if the given number is a power of two.
  509. *
  510. * @param {number} value - The value to check.
  511. * @return {boolean} Whether the given number is a power of two or not.
  512. */
  513. function isPowerOfTwo( value ) {
  514. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  515. }
  516. /**
  517. * Returns the smallest power of two that is greater than or equal to the given number.
  518. *
  519. * @param {number} value - The value to find a POT for.
  520. * @return {number} The smallest power of two that is greater than or equal to the given number.
  521. */
  522. function ceilPowerOfTwo( value ) {
  523. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  524. }
  525. /**
  526. * Returns the largest power of two that is less than or equal to the given number.
  527. *
  528. * @param {number} value - The value to find a POT for.
  529. * @return {number} The largest power of two that is less than or equal to the given number.
  530. */
  531. function floorPowerOfTwo( value ) {
  532. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  533. }
  534. /**
  535. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  536. * defined by the given angles and order.
  537. *
  538. * Rotations are applied to the axes in the order specified by order:
  539. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  540. *
  541. * @param {Quaternion} q - The quaternion to set.
  542. * @param {number} a - The rotation applied to the first axis, in radians.
  543. * @param {number} b - The rotation applied to the second axis, in radians.
  544. * @param {number} c - The rotation applied to the third axis, in radians.
  545. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  546. */
  547. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  548. const cos = Math.cos;
  549. const sin = Math.sin;
  550. const c2 = cos( b / 2 );
  551. const s2 = sin( b / 2 );
  552. const c13 = cos( ( a + c ) / 2 );
  553. const s13 = sin( ( a + c ) / 2 );
  554. const c1_3 = cos( ( a - c ) / 2 );
  555. const s1_3 = sin( ( a - c ) / 2 );
  556. const c3_1 = cos( ( c - a ) / 2 );
  557. const s3_1 = sin( ( c - a ) / 2 );
  558. switch ( order ) {
  559. case 'XYX':
  560. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  561. break;
  562. case 'YZY':
  563. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  564. break;
  565. case 'ZXZ':
  566. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  567. break;
  568. case 'XZX':
  569. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  570. break;
  571. case 'YXY':
  572. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  573. break;
  574. case 'ZYZ':
  575. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  576. break;
  577. default:
  578. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  579. }
  580. }
  581. /**
  582. * Denormalizes the given value according to the given typed array.
  583. *
  584. * @param {number} value - The value to denormalize.
  585. * @param {TypedArray} array - The typed array that defines the data type of the value.
  586. * @return {number} The denormalize (float) value in the range `[0,1]`.
  587. */
  588. function denormalize( value, array ) {
  589. switch ( array.constructor ) {
  590. case Float32Array:
  591. return value;
  592. case Uint32Array:
  593. return value / 4294967295.0;
  594. case Uint16Array:
  595. return value / 65535.0;
  596. case Uint8Array:
  597. return value / 255.0;
  598. case Int32Array:
  599. return Math.max( value / 2147483647.0, -1 );
  600. case Int16Array:
  601. return Math.max( value / 32767.0, -1 );
  602. case Int8Array:
  603. return Math.max( value / 127.0, -1 );
  604. default:
  605. throw new Error( 'Invalid component type.' );
  606. }
  607. }
  608. /**
  609. * Normalizes the given value according to the given typed array.
  610. *
  611. * @param {number} value - The float value in the range `[0,1]` to normalize.
  612. * @param {TypedArray} array - The typed array that defines the data type of the value.
  613. * @return {number} The normalize value.
  614. */
  615. function normalize( value, array ) {
  616. switch ( array.constructor ) {
  617. case Float32Array:
  618. return value;
  619. case Uint32Array:
  620. return Math.round( value * 4294967295.0 );
  621. case Uint16Array:
  622. return Math.round( value * 65535.0 );
  623. case Uint8Array:
  624. return Math.round( value * 255.0 );
  625. case Int32Array:
  626. return Math.round( value * 2147483647.0 );
  627. case Int16Array:
  628. return Math.round( value * 32767.0 );
  629. case Int8Array:
  630. return Math.round( value * 127.0 );
  631. default:
  632. throw new Error( 'Invalid component type.' );
  633. }
  634. }
  635. const MathUtils = {
  636. DEG2RAD: DEG2RAD,
  637. RAD2DEG: RAD2DEG,
  638. generateUUID: generateUUID,
  639. clamp: clamp,
  640. euclideanModulo: euclideanModulo,
  641. mapLinear: mapLinear,
  642. inverseLerp: inverseLerp,
  643. lerp: lerp,
  644. damp: damp,
  645. pingpong: pingpong,
  646. smoothstep: smoothstep,
  647. smootherstep: smootherstep,
  648. randInt: randInt,
  649. randFloat: randFloat,
  650. randFloatSpread: randFloatSpread,
  651. seededRandom: seededRandom,
  652. degToRad: degToRad,
  653. radToDeg: radToDeg,
  654. isPowerOfTwo: isPowerOfTwo,
  655. ceilPowerOfTwo: ceilPowerOfTwo,
  656. floorPowerOfTwo: floorPowerOfTwo,
  657. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  658. normalize: normalize,
  659. denormalize: denormalize
  660. };
  661. /**
  662. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  663. * (labeled x and y), which can be used to represent a number of things, such as:
  664. *
  665. * - A point in 2D space (i.e. a position on a plane).
  666. * - A direction and length across a plane. In three.js the length will
  667. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  668. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  669. * - Any arbitrary ordered pair of numbers.
  670. *
  671. * There are other things a 2D vector can be used to represent, such as
  672. * momentum vectors, complex numbers and so on, however these are the most
  673. * common uses in three.js.
  674. *
  675. * Iterating through a vector instance will yield its components `(x, y)` in
  676. * the corresponding order.
  677. * ```js
  678. * const a = new THREE.Vector2( 0, 1 );
  679. *
  680. * //no arguments; will be initialised to (0, 0)
  681. * const b = new THREE.Vector2( );
  682. *
  683. * const d = a.distanceTo( b );
  684. * ```
  685. */
  686. class Vector2 {
  687. /**
  688. * Constructs a new 2D vector.
  689. *
  690. * @param {number} [x=0] - The x value of this vector.
  691. * @param {number} [y=0] - The y value of this vector.
  692. */
  693. constructor( x = 0, y = 0 ) {
  694. /**
  695. * This flag can be used for type testing.
  696. *
  697. * @type {boolean}
  698. * @readonly
  699. * @default true
  700. */
  701. Vector2.prototype.isVector2 = true;
  702. /**
  703. * The x value of this vector.
  704. *
  705. * @type {number}
  706. */
  707. this.x = x;
  708. /**
  709. * The y value of this vector.
  710. *
  711. * @type {number}
  712. */
  713. this.y = y;
  714. }
  715. /**
  716. * Alias for {@link Vector2#x}.
  717. *
  718. * @type {number}
  719. */
  720. get width() {
  721. return this.x;
  722. }
  723. set width( value ) {
  724. this.x = value;
  725. }
  726. /**
  727. * Alias for {@link Vector2#y}.
  728. *
  729. * @type {number}
  730. */
  731. get height() {
  732. return this.y;
  733. }
  734. set height( value ) {
  735. this.y = value;
  736. }
  737. /**
  738. * Sets the vector components.
  739. *
  740. * @param {number} x - The value of the x component.
  741. * @param {number} y - The value of the y component.
  742. * @return {Vector2} A reference to this vector.
  743. */
  744. set( x, y ) {
  745. this.x = x;
  746. this.y = y;
  747. return this;
  748. }
  749. /**
  750. * Sets the vector components to the same value.
  751. *
  752. * @param {number} scalar - The value to set for all vector components.
  753. * @return {Vector2} A reference to this vector.
  754. */
  755. setScalar( scalar ) {
  756. this.x = scalar;
  757. this.y = scalar;
  758. return this;
  759. }
  760. /**
  761. * Sets the vector's x component to the given value
  762. *
  763. * @param {number} x - The value to set.
  764. * @return {Vector2} A reference to this vector.
  765. */
  766. setX( x ) {
  767. this.x = x;
  768. return this;
  769. }
  770. /**
  771. * Sets the vector's y component to the given value
  772. *
  773. * @param {number} y - The value to set.
  774. * @return {Vector2} A reference to this vector.
  775. */
  776. setY( y ) {
  777. this.y = y;
  778. return this;
  779. }
  780. /**
  781. * Allows to set a vector component with an index.
  782. *
  783. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  784. * @param {number} value - The value to set.
  785. * @return {Vector2} A reference to this vector.
  786. */
  787. setComponent( index, value ) {
  788. switch ( index ) {
  789. case 0: this.x = value; break;
  790. case 1: this.y = value; break;
  791. default: throw new Error( 'index is out of range: ' + index );
  792. }
  793. return this;
  794. }
  795. /**
  796. * Returns the value of the vector component which matches the given index.
  797. *
  798. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  799. * @return {number} A vector component value.
  800. */
  801. getComponent( index ) {
  802. switch ( index ) {
  803. case 0: return this.x;
  804. case 1: return this.y;
  805. default: throw new Error( 'index is out of range: ' + index );
  806. }
  807. }
  808. /**
  809. * Returns a new vector with copied values from this instance.
  810. *
  811. * @return {Vector2} A clone of this instance.
  812. */
  813. clone() {
  814. return new this.constructor( this.x, this.y );
  815. }
  816. /**
  817. * Copies the values of the given vector to this instance.
  818. *
  819. * @param {Vector2} v - The vector to copy.
  820. * @return {Vector2} A reference to this vector.
  821. */
  822. copy( v ) {
  823. this.x = v.x;
  824. this.y = v.y;
  825. return this;
  826. }
  827. /**
  828. * Adds the given vector to this instance.
  829. *
  830. * @param {Vector2} v - The vector to add.
  831. * @return {Vector2} A reference to this vector.
  832. */
  833. add( v ) {
  834. this.x += v.x;
  835. this.y += v.y;
  836. return this;
  837. }
  838. /**
  839. * Adds the given scalar value to all components of this instance.
  840. *
  841. * @param {number} s - The scalar to add.
  842. * @return {Vector2} A reference to this vector.
  843. */
  844. addScalar( s ) {
  845. this.x += s;
  846. this.y += s;
  847. return this;
  848. }
  849. /**
  850. * Adds the given vectors and stores the result in this instance.
  851. *
  852. * @param {Vector2} a - The first vector.
  853. * @param {Vector2} b - The second vector.
  854. * @return {Vector2} A reference to this vector.
  855. */
  856. addVectors( a, b ) {
  857. this.x = a.x + b.x;
  858. this.y = a.y + b.y;
  859. return this;
  860. }
  861. /**
  862. * Adds the given vector scaled by the given factor to this instance.
  863. *
  864. * @param {Vector2} v - The vector.
  865. * @param {number} s - The factor that scales `v`.
  866. * @return {Vector2} A reference to this vector.
  867. */
  868. addScaledVector( v, s ) {
  869. this.x += v.x * s;
  870. this.y += v.y * s;
  871. return this;
  872. }
  873. /**
  874. * Subtracts the given vector from this instance.
  875. *
  876. * @param {Vector2} v - The vector to subtract.
  877. * @return {Vector2} A reference to this vector.
  878. */
  879. sub( v ) {
  880. this.x -= v.x;
  881. this.y -= v.y;
  882. return this;
  883. }
  884. /**
  885. * Subtracts the given scalar value from all components of this instance.
  886. *
  887. * @param {number} s - The scalar to subtract.
  888. * @return {Vector2} A reference to this vector.
  889. */
  890. subScalar( s ) {
  891. this.x -= s;
  892. this.y -= s;
  893. return this;
  894. }
  895. /**
  896. * Subtracts the given vectors and stores the result in this instance.
  897. *
  898. * @param {Vector2} a - The first vector.
  899. * @param {Vector2} b - The second vector.
  900. * @return {Vector2} A reference to this vector.
  901. */
  902. subVectors( a, b ) {
  903. this.x = a.x - b.x;
  904. this.y = a.y - b.y;
  905. return this;
  906. }
  907. /**
  908. * Multiplies the given vector with this instance.
  909. *
  910. * @param {Vector2} v - The vector to multiply.
  911. * @return {Vector2} A reference to this vector.
  912. */
  913. multiply( v ) {
  914. this.x *= v.x;
  915. this.y *= v.y;
  916. return this;
  917. }
  918. /**
  919. * Multiplies the given scalar value with all components of this instance.
  920. *
  921. * @param {number} scalar - The scalar to multiply.
  922. * @return {Vector2} A reference to this vector.
  923. */
  924. multiplyScalar( scalar ) {
  925. this.x *= scalar;
  926. this.y *= scalar;
  927. return this;
  928. }
  929. /**
  930. * Divides this instance by the given vector.
  931. *
  932. * @param {Vector2} v - The vector to divide.
  933. * @return {Vector2} A reference to this vector.
  934. */
  935. divide( v ) {
  936. this.x /= v.x;
  937. this.y /= v.y;
  938. return this;
  939. }
  940. /**
  941. * Divides this vector by the given scalar.
  942. *
  943. * @param {number} scalar - The scalar to divide.
  944. * @return {Vector2} A reference to this vector.
  945. */
  946. divideScalar( scalar ) {
  947. return this.multiplyScalar( 1 / scalar );
  948. }
  949. /**
  950. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  951. * the given 3x3 matrix.
  952. *
  953. * @param {Matrix3} m - The matrix to apply.
  954. * @return {Vector2} A reference to this vector.
  955. */
  956. applyMatrix3( m ) {
  957. const x = this.x, y = this.y;
  958. const e = m.elements;
  959. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  960. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  961. return this;
  962. }
  963. /**
  964. * If this vector's x or y value is greater than the given vector's x or y
  965. * value, replace that value with the corresponding min value.
  966. *
  967. * @param {Vector2} v - The vector.
  968. * @return {Vector2} A reference to this vector.
  969. */
  970. min( v ) {
  971. this.x = Math.min( this.x, v.x );
  972. this.y = Math.min( this.y, v.y );
  973. return this;
  974. }
  975. /**
  976. * If this vector's x or y value is less than the given vector's x or y
  977. * value, replace that value with the corresponding max value.
  978. *
  979. * @param {Vector2} v - The vector.
  980. * @return {Vector2} A reference to this vector.
  981. */
  982. max( v ) {
  983. this.x = Math.max( this.x, v.x );
  984. this.y = Math.max( this.y, v.y );
  985. return this;
  986. }
  987. /**
  988. * If this vector's x or y value is greater than the max vector's x or y
  989. * value, it is replaced by the corresponding value.
  990. * If this vector's x or y value is less than the min vector's x or y value,
  991. * it is replaced by the corresponding value.
  992. *
  993. * @param {Vector2} min - The minimum x and y values.
  994. * @param {Vector2} max - The maximum x and y values in the desired range.
  995. * @return {Vector2} A reference to this vector.
  996. */
  997. clamp( min, max ) {
  998. // assumes min < max, componentwise
  999. this.x = clamp( this.x, min.x, max.x );
  1000. this.y = clamp( this.y, min.y, max.y );
  1001. return this;
  1002. }
  1003. /**
  1004. * If this vector's x or y values are greater than the max value, they are
  1005. * replaced by the max value.
  1006. * If this vector's x or y values are less than the min value, they are
  1007. * replaced by the min value.
  1008. *
  1009. * @param {number} minVal - The minimum value the components will be clamped to.
  1010. * @param {number} maxVal - The maximum value the components will be clamped to.
  1011. * @return {Vector2} A reference to this vector.
  1012. */
  1013. clampScalar( minVal, maxVal ) {
  1014. this.x = clamp( this.x, minVal, maxVal );
  1015. this.y = clamp( this.y, minVal, maxVal );
  1016. return this;
  1017. }
  1018. /**
  1019. * If this vector's length is greater than the max value, it is replaced by
  1020. * the max value.
  1021. * If this vector's length is less than the min value, it is replaced by the
  1022. * min value.
  1023. *
  1024. * @param {number} min - The minimum value the vector length will be clamped to.
  1025. * @param {number} max - The maximum value the vector length will be clamped to.
  1026. * @return {Vector2} A reference to this vector.
  1027. */
  1028. clampLength( min, max ) {
  1029. const length = this.length();
  1030. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  1031. }
  1032. /**
  1033. * The components of this vector are rounded down to the nearest integer value.
  1034. *
  1035. * @return {Vector2} A reference to this vector.
  1036. */
  1037. floor() {
  1038. this.x = Math.floor( this.x );
  1039. this.y = Math.floor( this.y );
  1040. return this;
  1041. }
  1042. /**
  1043. * The components of this vector are rounded up to the nearest integer value.
  1044. *
  1045. * @return {Vector2} A reference to this vector.
  1046. */
  1047. ceil() {
  1048. this.x = Math.ceil( this.x );
  1049. this.y = Math.ceil( this.y );
  1050. return this;
  1051. }
  1052. /**
  1053. * The components of this vector are rounded to the nearest integer value
  1054. *
  1055. * @return {Vector2} A reference to this vector.
  1056. */
  1057. round() {
  1058. this.x = Math.round( this.x );
  1059. this.y = Math.round( this.y );
  1060. return this;
  1061. }
  1062. /**
  1063. * The components of this vector are rounded towards zero (up if negative,
  1064. * down if positive) to an integer value.
  1065. *
  1066. * @return {Vector2} A reference to this vector.
  1067. */
  1068. roundToZero() {
  1069. this.x = Math.trunc( this.x );
  1070. this.y = Math.trunc( this.y );
  1071. return this;
  1072. }
  1073. /**
  1074. * Inverts this vector - i.e. sets x = -x and y = -y.
  1075. *
  1076. * @return {Vector2} A reference to this vector.
  1077. */
  1078. negate() {
  1079. this.x = - this.x;
  1080. this.y = - this.y;
  1081. return this;
  1082. }
  1083. /**
  1084. * Calculates the dot product of the given vector with this instance.
  1085. *
  1086. * @param {Vector2} v - The vector to compute the dot product with.
  1087. * @return {number} The result of the dot product.
  1088. */
  1089. dot( v ) {
  1090. return this.x * v.x + this.y * v.y;
  1091. }
  1092. /**
  1093. * Calculates the cross product of the given vector with this instance.
  1094. *
  1095. * @param {Vector2} v - The vector to compute the cross product with.
  1096. * @return {number} The result of the cross product.
  1097. */
  1098. cross( v ) {
  1099. return this.x * v.y - this.y * v.x;
  1100. }
  1101. /**
  1102. * Computes the square of the Euclidean length (straight-line length) from
  1103. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  1104. * compare the length squared instead as it is slightly more efficient to calculate.
  1105. *
  1106. * @return {number} The square length of this vector.
  1107. */
  1108. lengthSq() {
  1109. return this.x * this.x + this.y * this.y;
  1110. }
  1111. /**
  1112. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  1113. *
  1114. * @return {number} The length of this vector.
  1115. */
  1116. length() {
  1117. return Math.sqrt( this.x * this.x + this.y * this.y );
  1118. }
  1119. /**
  1120. * Computes the Manhattan length of this vector.
  1121. *
  1122. * @return {number} The length of this vector.
  1123. */
  1124. manhattanLength() {
  1125. return Math.abs( this.x ) + Math.abs( this.y );
  1126. }
  1127. /**
  1128. * Converts this vector to a unit vector - that is, sets it equal to a vector
  1129. * with the same direction as this one, but with a vector length of `1`.
  1130. *
  1131. * @return {Vector2} A reference to this vector.
  1132. */
  1133. normalize() {
  1134. return this.divideScalar( this.length() || 1 );
  1135. }
  1136. /**
  1137. * Computes the angle in radians of this vector with respect to the positive x-axis.
  1138. *
  1139. * @return {number} The angle in radians.
  1140. */
  1141. angle() {
  1142. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1143. return angle;
  1144. }
  1145. /**
  1146. * Returns the angle between the given vector and this instance in radians.
  1147. *
  1148. * @param {Vector2} v - The vector to compute the angle with.
  1149. * @return {number} The angle in radians.
  1150. */
  1151. angleTo( v ) {
  1152. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1153. if ( denominator === 0 ) return Math.PI / 2;
  1154. const theta = this.dot( v ) / denominator;
  1155. // clamp, to handle numerical problems
  1156. return Math.acos( clamp( theta, -1, 1 ) );
  1157. }
  1158. /**
  1159. * Computes the distance from the given vector to this instance.
  1160. *
  1161. * @param {Vector2} v - The vector to compute the distance to.
  1162. * @return {number} The distance.
  1163. */
  1164. distanceTo( v ) {
  1165. return Math.sqrt( this.distanceToSquared( v ) );
  1166. }
  1167. /**
  1168. * Computes the squared distance from the given vector to this instance.
  1169. * If you are just comparing the distance with another distance, you should compare
  1170. * the distance squared instead as it is slightly more efficient to calculate.
  1171. *
  1172. * @param {Vector2} v - The vector to compute the squared distance to.
  1173. * @return {number} The squared distance.
  1174. */
  1175. distanceToSquared( v ) {
  1176. const dx = this.x - v.x, dy = this.y - v.y;
  1177. return dx * dx + dy * dy;
  1178. }
  1179. /**
  1180. * Computes the Manhattan distance from the given vector to this instance.
  1181. *
  1182. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  1183. * @return {number} The Manhattan distance.
  1184. */
  1185. manhattanDistanceTo( v ) {
  1186. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1187. }
  1188. /**
  1189. * Sets this vector to a vector with the same direction as this one, but
  1190. * with the specified length.
  1191. *
  1192. * @param {number} length - The new length of this vector.
  1193. * @return {Vector2} A reference to this vector.
  1194. */
  1195. setLength( length ) {
  1196. return this.normalize().multiplyScalar( length );
  1197. }
  1198. /**
  1199. * Linearly interpolates between the given vector and this instance, where
  1200. * alpha is the percent distance along the line - alpha = 0 will be this
  1201. * vector, and alpha = 1 will be the given one.
  1202. *
  1203. * @param {Vector2} v - The vector to interpolate towards.
  1204. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1205. * @return {Vector2} A reference to this vector.
  1206. */
  1207. lerp( v, alpha ) {
  1208. this.x += ( v.x - this.x ) * alpha;
  1209. this.y += ( v.y - this.y ) * alpha;
  1210. return this;
  1211. }
  1212. /**
  1213. * Linearly interpolates between the given vectors, where alpha is the percent
  1214. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  1215. * be the second one. The result is stored in this instance.
  1216. *
  1217. * @param {Vector2} v1 - The first vector.
  1218. * @param {Vector2} v2 - The second vector.
  1219. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  1220. * @return {Vector2} A reference to this vector.
  1221. */
  1222. lerpVectors( v1, v2, alpha ) {
  1223. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1224. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1225. return this;
  1226. }
  1227. /**
  1228. * Returns `true` if this vector is equal with the given one.
  1229. *
  1230. * @param {Vector2} v - The vector to test for equality.
  1231. * @return {boolean} Whether this vector is equal with the given one.
  1232. */
  1233. equals( v ) {
  1234. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1235. }
  1236. /**
  1237. * Sets this vector's x value to be `array[ offset ]` and y
  1238. * value to be `array[ offset + 1 ]`.
  1239. *
  1240. * @param {Array<number>} array - An array holding the vector component values.
  1241. * @param {number} [offset=0] - The offset into the array.
  1242. * @return {Vector2} A reference to this vector.
  1243. */
  1244. fromArray( array, offset = 0 ) {
  1245. this.x = array[ offset ];
  1246. this.y = array[ offset + 1 ];
  1247. return this;
  1248. }
  1249. /**
  1250. * Writes the components of this vector to the given array. If no array is provided,
  1251. * the method returns a new instance.
  1252. *
  1253. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  1254. * @param {number} [offset=0] - Index of the first element in the array.
  1255. * @return {Array<number>} The vector components.
  1256. */
  1257. toArray( array = [], offset = 0 ) {
  1258. array[ offset ] = this.x;
  1259. array[ offset + 1 ] = this.y;
  1260. return array;
  1261. }
  1262. /**
  1263. * Sets the components of this vector from the given buffer attribute.
  1264. *
  1265. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  1266. * @param {number} index - The index into the attribute.
  1267. * @return {Vector2} A reference to this vector.
  1268. */
  1269. fromBufferAttribute( attribute, index ) {
  1270. this.x = attribute.getX( index );
  1271. this.y = attribute.getY( index );
  1272. return this;
  1273. }
  1274. /**
  1275. * Rotates this vector around the given center by the given angle.
  1276. *
  1277. * @param {Vector2} center - The point around which to rotate.
  1278. * @param {number} angle - The angle to rotate, in radians.
  1279. * @return {Vector2} A reference to this vector.
  1280. */
  1281. rotateAround( center, angle ) {
  1282. const c = Math.cos( angle ), s = Math.sin( angle );
  1283. const x = this.x - center.x;
  1284. const y = this.y - center.y;
  1285. this.x = x * c - y * s + center.x;
  1286. this.y = x * s + y * c + center.y;
  1287. return this;
  1288. }
  1289. /**
  1290. * Sets each component of this vector to a pseudo-random value between `0` and
  1291. * `1`, excluding `1`.
  1292. *
  1293. * @return {Vector2} A reference to this vector.
  1294. */
  1295. random() {
  1296. this.x = Math.random();
  1297. this.y = Math.random();
  1298. return this;
  1299. }
  1300. *[ Symbol.iterator ]() {
  1301. yield this.x;
  1302. yield this.y;
  1303. }
  1304. }
  1305. /**
  1306. * Represents a 3x3 matrix.
  1307. *
  1308. * A Note on Row-Major and Column-Major Ordering:
  1309. *
  1310. * The constructor and {@link Matrix3#set} method take arguments in
  1311. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  1312. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  1313. * This means that calling:
  1314. * ```js
  1315. * const m = new THREE.Matrix();
  1316. * m.set( 11, 12, 13,
  1317. * 21, 22, 23,
  1318. * 31, 32, 33 );
  1319. * ```
  1320. * will result in the elements array containing:
  1321. * ```js
  1322. * m.elements = [ 11, 21, 31,
  1323. * 12, 22, 32,
  1324. * 13, 23, 33 ];
  1325. * ```
  1326. * and internally all calculations are performed using column-major ordering.
  1327. * However, as the actual ordering makes no difference mathematically and
  1328. * most people are used to thinking about matrices in row-major order, the
  1329. * three.js documentation shows matrices in row-major order. Just bear in
  1330. * mind that if you are reading the source code, you'll have to take the
  1331. * transpose of any matrices outlined here to make sense of the calculations.
  1332. */
  1333. class Matrix3 {
  1334. /**
  1335. * Constructs a new 3x3 matrix. The arguments are supposed to be
  1336. * in row-major order. If no arguments are provided, the constructor
  1337. * initializes the matrix as an identity matrix.
  1338. *
  1339. * @param {number} [n11] - 1-1 matrix element.
  1340. * @param {number} [n12] - 1-2 matrix element.
  1341. * @param {number} [n13] - 1-3 matrix element.
  1342. * @param {number} [n21] - 2-1 matrix element.
  1343. * @param {number} [n22] - 2-2 matrix element.
  1344. * @param {number} [n23] - 2-3 matrix element.
  1345. * @param {number} [n31] - 3-1 matrix element.
  1346. * @param {number} [n32] - 3-2 matrix element.
  1347. * @param {number} [n33] - 3-3 matrix element.
  1348. */
  1349. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1350. /**
  1351. * This flag can be used for type testing.
  1352. *
  1353. * @type {boolean}
  1354. * @readonly
  1355. * @default true
  1356. */
  1357. Matrix3.prototype.isMatrix3 = true;
  1358. /**
  1359. * A column-major list of matrix values.
  1360. *
  1361. * @type {Array<number>}
  1362. */
  1363. this.elements = [
  1364. 1, 0, 0,
  1365. 0, 1, 0,
  1366. 0, 0, 1
  1367. ];
  1368. if ( n11 !== undefined ) {
  1369. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  1370. }
  1371. }
  1372. /**
  1373. * Sets the elements of the matrix.The arguments are supposed to be
  1374. * in row-major order.
  1375. *
  1376. * @param {number} [n11] - 1-1 matrix element.
  1377. * @param {number} [n12] - 1-2 matrix element.
  1378. * @param {number} [n13] - 1-3 matrix element.
  1379. * @param {number} [n21] - 2-1 matrix element.
  1380. * @param {number} [n22] - 2-2 matrix element.
  1381. * @param {number} [n23] - 2-3 matrix element.
  1382. * @param {number} [n31] - 3-1 matrix element.
  1383. * @param {number} [n32] - 3-2 matrix element.
  1384. * @param {number} [n33] - 3-3 matrix element.
  1385. * @return {Matrix3} A reference to this matrix.
  1386. */
  1387. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1388. const te = this.elements;
  1389. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1390. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1391. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1392. return this;
  1393. }
  1394. /**
  1395. * Sets this matrix to the 3x3 identity matrix.
  1396. *
  1397. * @return {Matrix3} A reference to this matrix.
  1398. */
  1399. identity() {
  1400. this.set(
  1401. 1, 0, 0,
  1402. 0, 1, 0,
  1403. 0, 0, 1
  1404. );
  1405. return this;
  1406. }
  1407. /**
  1408. * Copies the values of the given matrix to this instance.
  1409. *
  1410. * @param {Matrix3} m - The matrix to copy.
  1411. * @return {Matrix3} A reference to this matrix.
  1412. */
  1413. copy( m ) {
  1414. const te = this.elements;
  1415. const me = m.elements;
  1416. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1417. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1418. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1419. return this;
  1420. }
  1421. /**
  1422. * Extracts the basis of this matrix into the three axis vectors provided.
  1423. *
  1424. * @param {Vector3} xAxis - The basis's x axis.
  1425. * @param {Vector3} yAxis - The basis's y axis.
  1426. * @param {Vector3} zAxis - The basis's z axis.
  1427. * @return {Matrix3} A reference to this matrix.
  1428. */
  1429. extractBasis( xAxis, yAxis, zAxis ) {
  1430. xAxis.setFromMatrix3Column( this, 0 );
  1431. yAxis.setFromMatrix3Column( this, 1 );
  1432. zAxis.setFromMatrix3Column( this, 2 );
  1433. return this;
  1434. }
  1435. /**
  1436. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  1437. *
  1438. * @param {Matrix4} m - The 4x4 matrix.
  1439. * @return {Matrix3} A reference to this matrix.
  1440. */
  1441. setFromMatrix4( m ) {
  1442. const me = m.elements;
  1443. this.set(
  1444. me[ 0 ], me[ 4 ], me[ 8 ],
  1445. me[ 1 ], me[ 5 ], me[ 9 ],
  1446. me[ 2 ], me[ 6 ], me[ 10 ]
  1447. );
  1448. return this;
  1449. }
  1450. /**
  1451. * Post-multiplies this matrix by the given 3x3 matrix.
  1452. *
  1453. * @param {Matrix3} m - The matrix to multiply with.
  1454. * @return {Matrix3} A reference to this matrix.
  1455. */
  1456. multiply( m ) {
  1457. return this.multiplyMatrices( this, m );
  1458. }
  1459. /**
  1460. * Pre-multiplies this matrix by the given 3x3 matrix.
  1461. *
  1462. * @param {Matrix3} m - The matrix to multiply with.
  1463. * @return {Matrix3} A reference to this matrix.
  1464. */
  1465. premultiply( m ) {
  1466. return this.multiplyMatrices( m, this );
  1467. }
  1468. /**
  1469. * Multiples the given 3x3 matrices and stores the result
  1470. * in this matrix.
  1471. *
  1472. * @param {Matrix3} a - The first matrix.
  1473. * @param {Matrix3} b - The second matrix.
  1474. * @return {Matrix3} A reference to this matrix.
  1475. */
  1476. multiplyMatrices( a, b ) {
  1477. const ae = a.elements;
  1478. const be = b.elements;
  1479. const te = this.elements;
  1480. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1481. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1482. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1483. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1484. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1485. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1486. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1487. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1488. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1489. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1490. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1491. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1492. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1493. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1494. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1495. return this;
  1496. }
  1497. /**
  1498. * Multiplies every component of the matrix by the given scalar.
  1499. *
  1500. * @param {number} s - The scalar.
  1501. * @return {Matrix3} A reference to this matrix.
  1502. */
  1503. multiplyScalar( s ) {
  1504. const te = this.elements;
  1505. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1506. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1507. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1508. return this;
  1509. }
  1510. /**
  1511. * Computes and returns the determinant of this matrix.
  1512. *
  1513. * @return {number} The determinant.
  1514. */
  1515. determinant() {
  1516. const te = this.elements;
  1517. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1518. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1519. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1520. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1521. }
  1522. /**
  1523. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  1524. * You can not invert with a determinant of zero. If you attempt this, the method produces
  1525. * a zero matrix instead.
  1526. *
  1527. * @return {Matrix3} A reference to this matrix.
  1528. */
  1529. invert() {
  1530. const te = this.elements,
  1531. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1532. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1533. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1534. t11 = n33 * n22 - n32 * n23,
  1535. t12 = n32 * n13 - n33 * n12,
  1536. t13 = n23 * n12 - n22 * n13,
  1537. det = n11 * t11 + n21 * t12 + n31 * t13;
  1538. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1539. const detInv = 1 / det;
  1540. te[ 0 ] = t11 * detInv;
  1541. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1542. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1543. te[ 3 ] = t12 * detInv;
  1544. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1545. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1546. te[ 6 ] = t13 * detInv;
  1547. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1548. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1549. return this;
  1550. }
  1551. /**
  1552. * Transposes this matrix in place.
  1553. *
  1554. * @return {Matrix3} A reference to this matrix.
  1555. */
  1556. transpose() {
  1557. let tmp;
  1558. const m = this.elements;
  1559. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1560. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1561. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1562. return this;
  1563. }
  1564. /**
  1565. * Computes the normal matrix which is the inverse transpose of the upper
  1566. * left 3x3 portion of the given 4x4 matrix.
  1567. *
  1568. * @param {Matrix4} matrix4 - The 4x4 matrix.
  1569. * @return {Matrix3} A reference to this matrix.
  1570. */
  1571. getNormalMatrix( matrix4 ) {
  1572. return this.setFromMatrix4( matrix4 ).invert().transpose();
  1573. }
  1574. /**
  1575. * Transposes this matrix into the supplied array, and returns itself unchanged.
  1576. *
  1577. * @param {Array<number>} r - An array to store the transposed matrix elements.
  1578. * @return {Matrix3} A reference to this matrix.
  1579. */
  1580. transposeIntoArray( r ) {
  1581. const m = this.elements;
  1582. r[ 0 ] = m[ 0 ];
  1583. r[ 1 ] = m[ 3 ];
  1584. r[ 2 ] = m[ 6 ];
  1585. r[ 3 ] = m[ 1 ];
  1586. r[ 4 ] = m[ 4 ];
  1587. r[ 5 ] = m[ 7 ];
  1588. r[ 6 ] = m[ 2 ];
  1589. r[ 7 ] = m[ 5 ];
  1590. r[ 8 ] = m[ 8 ];
  1591. return this;
  1592. }
  1593. /**
  1594. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  1595. *
  1596. * @param {number} tx - Offset x.
  1597. * @param {number} ty - Offset y.
  1598. * @param {number} sx - Repeat x.
  1599. * @param {number} sy - Repeat y.
  1600. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  1601. * @param {number} cx - Center x of rotation.
  1602. * @param {number} cy - Center y of rotation
  1603. * @return {Matrix3} A reference to this matrix.
  1604. */
  1605. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1606. const c = Math.cos( rotation );
  1607. const s = Math.sin( rotation );
  1608. this.set(
  1609. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1610. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1611. 0, 0, 1
  1612. );
  1613. return this;
  1614. }
  1615. /**
  1616. * Scales this matrix with the given scalar values.
  1617. *
  1618. * @param {number} sx - The amount to scale in the X axis.
  1619. * @param {number} sy - The amount to scale in the Y axis.
  1620. * @return {Matrix3} A reference to this matrix.
  1621. */
  1622. scale( sx, sy ) {
  1623. this.premultiply( _m3.makeScale( sx, sy ) );
  1624. return this;
  1625. }
  1626. /**
  1627. * Rotates this matrix by the given angle.
  1628. *
  1629. * @param {number} theta - The rotation in radians.
  1630. * @return {Matrix3} A reference to this matrix.
  1631. */
  1632. rotate( theta ) {
  1633. this.premultiply( _m3.makeRotation( - theta ) );
  1634. return this;
  1635. }
  1636. /**
  1637. * Translates this matrix by the given scalar values.
  1638. *
  1639. * @param {number} tx - The amount to translate in the X axis.
  1640. * @param {number} ty - The amount to translate in the Y axis.
  1641. * @return {Matrix3} A reference to this matrix.
  1642. */
  1643. translate( tx, ty ) {
  1644. this.premultiply( _m3.makeTranslation( tx, ty ) );
  1645. return this;
  1646. }
  1647. // for 2D Transforms
  1648. /**
  1649. * Sets this matrix as a 2D translation transform.
  1650. *
  1651. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  1652. * @param {number} y - The amount to translate in the Y axis.
  1653. * @return {Matrix3} A reference to this matrix.
  1654. */
  1655. makeTranslation( x, y ) {
  1656. if ( x.isVector2 ) {
  1657. this.set(
  1658. 1, 0, x.x,
  1659. 0, 1, x.y,
  1660. 0, 0, 1
  1661. );
  1662. } else {
  1663. this.set(
  1664. 1, 0, x,
  1665. 0, 1, y,
  1666. 0, 0, 1
  1667. );
  1668. }
  1669. return this;
  1670. }
  1671. /**
  1672. * Sets this matrix as a 2D rotational transformation.
  1673. *
  1674. * @param {number} theta - The rotation in radians.
  1675. * @return {Matrix3} A reference to this matrix.
  1676. */
  1677. makeRotation( theta ) {
  1678. // counterclockwise
  1679. const c = Math.cos( theta );
  1680. const s = Math.sin( theta );
  1681. this.set(
  1682. c, - s, 0,
  1683. s, c, 0,
  1684. 0, 0, 1
  1685. );
  1686. return this;
  1687. }
  1688. /**
  1689. * Sets this matrix as a 2D scale transform.
  1690. *
  1691. * @param {number} x - The amount to scale in the X axis.
  1692. * @param {number} y - The amount to scale in the Y axis.
  1693. * @return {Matrix3} A reference to this matrix.
  1694. */
  1695. makeScale( x, y ) {
  1696. this.set(
  1697. x, 0, 0,
  1698. 0, y, 0,
  1699. 0, 0, 1
  1700. );
  1701. return this;
  1702. }
  1703. /**
  1704. * Returns `true` if this matrix is equal with the given one.
  1705. *
  1706. * @param {Matrix3} matrix - The matrix to test for equality.
  1707. * @return {boolean} Whether this matrix is equal with the given one.
  1708. */
  1709. equals( matrix ) {
  1710. const te = this.elements;
  1711. const me = matrix.elements;
  1712. for ( let i = 0; i < 9; i ++ ) {
  1713. if ( te[ i ] !== me[ i ] ) return false;
  1714. }
  1715. return true;
  1716. }
  1717. /**
  1718. * Sets the elements of the matrix from the given array.
  1719. *
  1720. * @param {Array<number>} array - The matrix elements in column-major order.
  1721. * @param {number} [offset=0] - Index of the first element in the array.
  1722. * @return {Matrix3} A reference to this matrix.
  1723. */
  1724. fromArray( array, offset = 0 ) {
  1725. for ( let i = 0; i < 9; i ++ ) {
  1726. this.elements[ i ] = array[ i + offset ];
  1727. }
  1728. return this;
  1729. }
  1730. /**
  1731. * Writes the elements of this matrix to the given array. If no array is provided,
  1732. * the method returns a new instance.
  1733. *
  1734. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  1735. * @param {number} [offset=0] - Index of the first element in the array.
  1736. * @return {Array<number>} The matrix elements in column-major order.
  1737. */
  1738. toArray( array = [], offset = 0 ) {
  1739. const te = this.elements;
  1740. array[ offset ] = te[ 0 ];
  1741. array[ offset + 1 ] = te[ 1 ];
  1742. array[ offset + 2 ] = te[ 2 ];
  1743. array[ offset + 3 ] = te[ 3 ];
  1744. array[ offset + 4 ] = te[ 4 ];
  1745. array[ offset + 5 ] = te[ 5 ];
  1746. array[ offset + 6 ] = te[ 6 ];
  1747. array[ offset + 7 ] = te[ 7 ];
  1748. array[ offset + 8 ] = te[ 8 ];
  1749. return array;
  1750. }
  1751. /**
  1752. * Returns a matrix with copied values from this instance.
  1753. *
  1754. * @return {Matrix3} A clone of this instance.
  1755. */
  1756. clone() {
  1757. return new this.constructor().fromArray( this.elements );
  1758. }
  1759. }
  1760. const _m3 = /*@__PURE__*/ new Matrix3();
  1761. function arrayNeedsUint32( array ) {
  1762. // assumes larger values usually on last
  1763. for ( let i = array.length - 1; i >= 0; -- i ) {
  1764. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1765. }
  1766. return false;
  1767. }
  1768. const TYPED_ARRAYS = {
  1769. Int8Array: Int8Array,
  1770. Uint8Array: Uint8Array,
  1771. Uint8ClampedArray: Uint8ClampedArray,
  1772. Int16Array: Int16Array,
  1773. Uint16Array: Uint16Array,
  1774. Int32Array: Int32Array,
  1775. Uint32Array: Uint32Array,
  1776. Float32Array: Float32Array,
  1777. Float64Array: Float64Array
  1778. };
  1779. function getTypedArray( type, buffer ) {
  1780. return new TYPED_ARRAYS[ type ]( buffer );
  1781. }
  1782. function createElementNS( name ) {
  1783. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1784. }
  1785. function createCanvasElement() {
  1786. const canvas = createElementNS( 'canvas' );
  1787. canvas.style.display = 'block';
  1788. return canvas;
  1789. }
  1790. const _cache = {};
  1791. function warnOnce( message ) {
  1792. if ( message in _cache ) return;
  1793. _cache[ message ] = true;
  1794. console.warn( message );
  1795. }
  1796. function probeAsync( gl, sync, interval ) {
  1797. return new Promise( function ( resolve, reject ) {
  1798. function probe() {
  1799. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1800. case gl.WAIT_FAILED:
  1801. reject();
  1802. break;
  1803. case gl.TIMEOUT_EXPIRED:
  1804. setTimeout( probe, interval );
  1805. break;
  1806. default:
  1807. resolve();
  1808. }
  1809. }
  1810. setTimeout( probe, interval );
  1811. } );
  1812. }
  1813. function toNormalizedProjectionMatrix( projectionMatrix ) {
  1814. const m = projectionMatrix.elements;
  1815. // Convert [-1, 1] to [0, 1] projection matrix
  1816. m[ 2 ] = 0.5 * m[ 2 ] + 0.5 * m[ 3 ];
  1817. m[ 6 ] = 0.5 * m[ 6 ] + 0.5 * m[ 7 ];
  1818. m[ 10 ] = 0.5 * m[ 10 ] + 0.5 * m[ 11 ];
  1819. m[ 14 ] = 0.5 * m[ 14 ] + 0.5 * m[ 15 ];
  1820. }
  1821. function toReversedProjectionMatrix( projectionMatrix ) {
  1822. const m = projectionMatrix.elements;
  1823. const isPerspectiveMatrix = m[ 11 ] === -1;
  1824. // Reverse [0, 1] projection matrix
  1825. if ( isPerspectiveMatrix ) {
  1826. m[ 10 ] = - m[ 10 ] - 1;
  1827. m[ 14 ] = - m[ 14 ];
  1828. } else {
  1829. m[ 10 ] = - m[ 10 ];
  1830. m[ 14 ] = - m[ 14 ] + 1;
  1831. }
  1832. }
  1833. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1834. 0.4123908, 0.3575843, 0.1804808,
  1835. 0.2126390, 0.7151687, 0.0721923,
  1836. 0.0193308, 0.1191948, 0.9505322
  1837. );
  1838. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1839. 3.2409699, -1.5373832, -0.4986108,
  1840. -0.9692436, 1.8759675, 0.0415551,
  1841. 0.0556301, -0.203977, 1.0569715
  1842. );
  1843. function createColorManagement() {
  1844. const ColorManagement = {
  1845. enabled: true,
  1846. workingColorSpace: LinearSRGBColorSpace,
  1847. /**
  1848. * Implementations of supported color spaces.
  1849. *
  1850. * Required:
  1851. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  1852. * - whitePoint: reference white [ x y ]
  1853. * - transfer: transfer function (pre-defined)
  1854. * - toXYZ: Matrix3 RGB to XYZ transform
  1855. * - fromXYZ: Matrix3 XYZ to RGB transform
  1856. * - luminanceCoefficients: RGB luminance coefficients
  1857. *
  1858. * Optional:
  1859. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  1860. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  1861. *
  1862. * Reference:
  1863. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  1864. */
  1865. spaces: {},
  1866. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1867. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1868. return color;
  1869. }
  1870. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1871. color.r = SRGBToLinear( color.r );
  1872. color.g = SRGBToLinear( color.g );
  1873. color.b = SRGBToLinear( color.b );
  1874. }
  1875. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1876. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1877. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1878. }
  1879. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1880. color.r = LinearToSRGB( color.r );
  1881. color.g = LinearToSRGB( color.g );
  1882. color.b = LinearToSRGB( color.b );
  1883. }
  1884. return color;
  1885. },
  1886. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1887. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1888. },
  1889. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1890. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1891. },
  1892. getPrimaries: function ( colorSpace ) {
  1893. return this.spaces[ colorSpace ].primaries;
  1894. },
  1895. getTransfer: function ( colorSpace ) {
  1896. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1897. return this.spaces[ colorSpace ].transfer;
  1898. },
  1899. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1900. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1901. },
  1902. define: function ( colorSpaces ) {
  1903. Object.assign( this.spaces, colorSpaces );
  1904. },
  1905. // Internal APIs
  1906. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1907. return targetMatrix
  1908. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1909. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1910. },
  1911. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1912. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1913. },
  1914. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1915. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1916. }
  1917. };
  1918. /******************************************************************************
  1919. * sRGB definitions
  1920. */
  1921. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1922. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1923. const D65 = [ 0.3127, 0.3290 ];
  1924. ColorManagement.define( {
  1925. [ LinearSRGBColorSpace ]: {
  1926. primaries: REC709_PRIMARIES,
  1927. whitePoint: D65,
  1928. transfer: LinearTransfer,
  1929. toXYZ: LINEAR_REC709_TO_XYZ,
  1930. fromXYZ: XYZ_TO_LINEAR_REC709,
  1931. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1932. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1933. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1934. },
  1935. [ SRGBColorSpace ]: {
  1936. primaries: REC709_PRIMARIES,
  1937. whitePoint: D65,
  1938. transfer: SRGBTransfer,
  1939. toXYZ: LINEAR_REC709_TO_XYZ,
  1940. fromXYZ: XYZ_TO_LINEAR_REC709,
  1941. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1942. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1943. },
  1944. } );
  1945. return ColorManagement;
  1946. }
  1947. const ColorManagement = /*@__PURE__*/ createColorManagement();
  1948. function SRGBToLinear( c ) {
  1949. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1950. }
  1951. function LinearToSRGB( c ) {
  1952. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1953. }
  1954. let _canvas;
  1955. /**
  1956. * A class containing utility functions for images.
  1957. *
  1958. * @hideconstructor
  1959. */
  1960. class ImageUtils {
  1961. /**
  1962. * Returns a data URI containing a representation of the given image.
  1963. *
  1964. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  1965. * @return {string} The data URI.
  1966. */
  1967. static getDataURL( image ) {
  1968. if ( /^data:/i.test( image.src ) ) {
  1969. return image.src;
  1970. }
  1971. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1972. return image.src;
  1973. }
  1974. let canvas;
  1975. if ( image instanceof HTMLCanvasElement ) {
  1976. canvas = image;
  1977. } else {
  1978. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1979. _canvas.width = image.width;
  1980. _canvas.height = image.height;
  1981. const context = _canvas.getContext( '2d' );
  1982. if ( image instanceof ImageData ) {
  1983. context.putImageData( image, 0, 0 );
  1984. } else {
  1985. context.drawImage( image, 0, 0, image.width, image.height );
  1986. }
  1987. canvas = _canvas;
  1988. }
  1989. return canvas.toDataURL( 'image/png' );
  1990. }
  1991. /**
  1992. * Converts the given sRGB image data to linear color space.
  1993. *
  1994. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  1995. * @return {HTMLCanvasElement|Object} The converted image.
  1996. */
  1997. static sRGBToLinear( image ) {
  1998. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1999. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2000. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2001. const canvas = createElementNS( 'canvas' );
  2002. canvas.width = image.width;
  2003. canvas.height = image.height;
  2004. const context = canvas.getContext( '2d' );
  2005. context.drawImage( image, 0, 0, image.width, image.height );
  2006. const imageData = context.getImageData( 0, 0, image.width, image.height );
  2007. const data = imageData.data;
  2008. for ( let i = 0; i < data.length; i ++ ) {
  2009. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  2010. }
  2011. context.putImageData( imageData, 0, 0 );
  2012. return canvas;
  2013. } else if ( image.data ) {
  2014. const data = image.data.slice( 0 );
  2015. for ( let i = 0; i < data.length; i ++ ) {
  2016. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  2017. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  2018. } else {
  2019. // assuming float
  2020. data[ i ] = SRGBToLinear( data[ i ] );
  2021. }
  2022. }
  2023. return {
  2024. data: data,
  2025. width: image.width,
  2026. height: image.height
  2027. };
  2028. } else {
  2029. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  2030. return image;
  2031. }
  2032. }
  2033. }
  2034. let _sourceId = 0;
  2035. class Source {
  2036. constructor( data = null ) {
  2037. this.isSource = true;
  2038. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  2039. this.uuid = generateUUID();
  2040. this.data = data;
  2041. this.dataReady = true;
  2042. this.version = 0;
  2043. }
  2044. set needsUpdate( value ) {
  2045. if ( value === true ) this.version ++;
  2046. }
  2047. toJSON( meta ) {
  2048. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2049. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  2050. return meta.images[ this.uuid ];
  2051. }
  2052. const output = {
  2053. uuid: this.uuid,
  2054. url: ''
  2055. };
  2056. const data = this.data;
  2057. if ( data !== null ) {
  2058. let url;
  2059. if ( Array.isArray( data ) ) {
  2060. // cube texture
  2061. url = [];
  2062. for ( let i = 0, l = data.length; i < l; i ++ ) {
  2063. if ( data[ i ].isDataTexture ) {
  2064. url.push( serializeImage( data[ i ].image ) );
  2065. } else {
  2066. url.push( serializeImage( data[ i ] ) );
  2067. }
  2068. }
  2069. } else {
  2070. // texture
  2071. url = serializeImage( data );
  2072. }
  2073. output.url = url;
  2074. }
  2075. if ( ! isRootObject ) {
  2076. meta.images[ this.uuid ] = output;
  2077. }
  2078. return output;
  2079. }
  2080. }
  2081. function serializeImage( image ) {
  2082. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  2083. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  2084. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  2085. // default images
  2086. return ImageUtils.getDataURL( image );
  2087. } else {
  2088. if ( image.data ) {
  2089. // images of DataTexture
  2090. return {
  2091. data: Array.from( image.data ),
  2092. width: image.width,
  2093. height: image.height,
  2094. type: image.data.constructor.name
  2095. };
  2096. } else {
  2097. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  2098. return {};
  2099. }
  2100. }
  2101. }
  2102. let _textureId = 0;
  2103. /**
  2104. * Base class for all textures.
  2105. *
  2106. * Note: After the initial use of a texture, its dimensions, format, and type
  2107. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  2108. *
  2109. * @augments EventDispatcher
  2110. */
  2111. class Texture extends EventDispatcher {
  2112. /**
  2113. * Constructs a new texture.
  2114. *
  2115. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  2116. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  2117. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  2118. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  2119. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  2120. * @param {number} [minFilter=LinearFilter] - The min filter value.
  2121. * @param {number} [format=RGBAFormat] - The min filter value.
  2122. * @param {number} [type=UnsignedByteType] - The min filter value.
  2123. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The min filter value.
  2124. * @param {string} [colorSpace=NoColorSpace] - The min filter value.
  2125. */
  2126. 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 ) {
  2127. super();
  2128. /**
  2129. * This flag can be used for type testing.
  2130. *
  2131. * @type {boolean}
  2132. * @readonly
  2133. * @default true
  2134. */
  2135. this.isTexture = true;
  2136. /**
  2137. * The ID of the texture.
  2138. *
  2139. * @name Texture#id
  2140. * @type {number}
  2141. * @readonly
  2142. */
  2143. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  2144. /**
  2145. * The UUID of the material.
  2146. *
  2147. * @type {string}
  2148. * @readonly
  2149. */
  2150. this.uuid = generateUUID();
  2151. /**
  2152. * The name of the material.
  2153. *
  2154. * @type {string}
  2155. */
  2156. this.name = '';
  2157. /**
  2158. * The data definition of a texture. A reference to the data source can be
  2159. * shared across textures. This is often useful in context of spritesheets
  2160. * where multiple textures render the same data but with different texture
  2161. * transformations.
  2162. *
  2163. * @type {Source}
  2164. */
  2165. this.source = new Source( image );
  2166. /**
  2167. * An array holding user-defined mipmaps.
  2168. *
  2169. * @type {Array<Object>}
  2170. */
  2171. this.mipmaps = [];
  2172. /**
  2173. * How the texture is applied to the object. The value `UVMapping`
  2174. * is the default, where texture or uv coordinates are used to apply the map.
  2175. *
  2176. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  2177. * @default UVMapping
  2178. */
  2179. this.mapping = mapping;
  2180. /**
  2181. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  2182. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  2183. *
  2184. * @type {number}
  2185. * @default 0
  2186. */
  2187. this.channel = 0;
  2188. /**
  2189. * This defines how the texture is wrapped horizontally and corresponds to
  2190. * *U* in UV mapping.
  2191. *
  2192. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2193. * @default ClampToEdgeWrapping
  2194. */
  2195. this.wrapS = wrapS;
  2196. /**
  2197. * This defines how the texture is wrapped horizontally and corresponds to
  2198. * *V* in UV mapping.
  2199. *
  2200. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  2201. * @default ClampToEdgeWrapping
  2202. */
  2203. this.wrapT = wrapT;
  2204. /**
  2205. * How the texture is sampled when a texel covers more than one pixel.
  2206. *
  2207. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2208. * @default LinearFilter
  2209. */
  2210. this.magFilter = magFilter;
  2211. /**
  2212. * How the texture is sampled when a texel covers less than one pixel.
  2213. *
  2214. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  2215. * @default LinearMipmapLinearFilter
  2216. */
  2217. this.minFilter = minFilter;
  2218. /**
  2219. * The number of samples taken along the axis through the pixel that has the
  2220. * highest density of texels. By default, this value is `1`. A higher value
  2221. * gives a less blurry result than a basic mipmap, at the cost of more
  2222. * texture samples being used.
  2223. *
  2224. * @type {number}
  2225. * @default 0
  2226. */
  2227. this.anisotropy = anisotropy;
  2228. /**
  2229. * The format of the texture.
  2230. *
  2231. * @type {number}
  2232. * @default RGBAFormat
  2233. */
  2234. this.format = format;
  2235. /**
  2236. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  2237. * defines how the texture data is going to be stored on the GPU.
  2238. *
  2239. * This property allows to overwrite the default format.
  2240. *
  2241. * @type {?string}
  2242. * @default null
  2243. */
  2244. this.internalFormat = null;
  2245. /**
  2246. * The data type of the texture.
  2247. *
  2248. * @type {number}
  2249. * @default UnsignedByteType
  2250. */
  2251. this.type = type;
  2252. /**
  2253. * How much a single repetition of the texture is offset from the beginning,
  2254. * in each direction U and V. Typical range is `0.0` to `1.0`.
  2255. *
  2256. * @type {Vector2}
  2257. * @default (0,0)
  2258. */
  2259. this.offset = new Vector2( 0, 0 );
  2260. /**
  2261. * How many times the texture is repeated across the surface, in each
  2262. * direction U and V. If repeat is set greater than `1` in either direction,
  2263. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  2264. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  2265. *
  2266. * @type {Vector2}
  2267. * @default (1,1)
  2268. */
  2269. this.repeat = new Vector2( 1, 1 );
  2270. /**
  2271. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  2272. * to the center of the texture. Default is `(0, 0)`, the lower left.
  2273. *
  2274. * @type {Vector2}
  2275. * @default (0,0)
  2276. */
  2277. this.center = new Vector2( 0, 0 );
  2278. /**
  2279. * How much the texture is rotated around the center point, in radians.
  2280. * Positive values are counter-clockwise.
  2281. *
  2282. * @type {number}
  2283. * @default 0
  2284. */
  2285. this.rotation = 0;
  2286. /**
  2287. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  2288. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  2289. * {@link Texture#rotation}, and {@link Texture#center}.
  2290. *
  2291. * Set this to `false` if you are specifying the uv-transform matrix directly.
  2292. *
  2293. * @type {boolean}
  2294. * @default true
  2295. */
  2296. this.matrixAutoUpdate = true;
  2297. /**
  2298. * The uv-transformation matrix of the texture.
  2299. *
  2300. * @type {Matrix3}
  2301. */
  2302. this.matrix = new Matrix3();
  2303. /**
  2304. * Whether to generate mipmaps (if possible) for a texture.
  2305. *
  2306. * Set this to `false` if you are creating mipmaps manually.
  2307. *
  2308. * @type {boolean}
  2309. * @default true
  2310. */
  2311. this.generateMipmaps = true;
  2312. /**
  2313. * If set to `true`, the alpha channel, if present, is multiplied into the
  2314. * color channels when the texture is uploaded to the GPU.
  2315. *
  2316. * Note that this property has no effect when using `ImageBitmap`. You need to
  2317. * configure premultiply alpha on bitmap creation instead.
  2318. *
  2319. * @type {boolean}
  2320. * @default false
  2321. */
  2322. this.premultiplyAlpha = false;
  2323. /**
  2324. * If set to `true`, the texture is flipped along the vertical axis when
  2325. * uploaded to the GPU.
  2326. *
  2327. * Note that this property has no effect when using `ImageBitmap`. You need to
  2328. * configure the flip on bitmap creation instead.
  2329. *
  2330. * @type {boolean}
  2331. * @default true
  2332. */
  2333. this.flipY = true;
  2334. /**
  2335. * Specifies the alignment requirements for the start of each pixel row in memory.
  2336. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  2337. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  2338. *
  2339. * @type {number}
  2340. * @default 4
  2341. */
  2342. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2343. /**
  2344. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  2345. *
  2346. * @type {string}
  2347. * @default NoColorSpace
  2348. */
  2349. this.colorSpace = colorSpace;
  2350. /**
  2351. * An object that can be used to store custom data about the texture. It
  2352. * should not hold references to functions as these will not be cloned.
  2353. *
  2354. * @type {Object}
  2355. */
  2356. this.userData = {};
  2357. /**
  2358. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  2359. *
  2360. * @type {number}
  2361. * @readonly
  2362. * @default 0
  2363. */
  2364. this.version = 0;
  2365. /**
  2366. * A callback function, called when the texture is updated (e.g., when
  2367. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  2368. *
  2369. * @type {?Function}
  2370. * @default null
  2371. */
  2372. this.onUpdate = null;
  2373. /**
  2374. * An optional back reference to the textures render target.
  2375. *
  2376. * @type {?(RenderTarget|WebGLRenderTarget)}
  2377. * @default null
  2378. */
  2379. this.renderTarget = null;
  2380. /**
  2381. * Indicates whether a texture belongs to a render target or not.
  2382. *
  2383. * @type {boolean}
  2384. * @readonly
  2385. * @default false
  2386. */
  2387. this.isRenderTargetTexture = false;
  2388. /**
  2389. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  2390. * (only relevant for render target textures).
  2391. *
  2392. * @type {number}
  2393. * @readonly
  2394. * @default 0
  2395. */
  2396. this.pmremVersion = 0;
  2397. }
  2398. /**
  2399. * The image object holding the texture data.
  2400. *
  2401. * @type {?Object}
  2402. */
  2403. get image() {
  2404. return this.source.data;
  2405. }
  2406. set image( value = null ) {
  2407. this.source.data = value;
  2408. }
  2409. /**
  2410. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  2411. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  2412. */
  2413. updateMatrix() {
  2414. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2415. }
  2416. /**
  2417. * Returns a new texture with copied values from this instance.
  2418. *
  2419. * @return {Texture} A clone of this instance.
  2420. */
  2421. clone() {
  2422. return new this.constructor().copy( this );
  2423. }
  2424. /**
  2425. * Copies the values of the given texture to this instance.
  2426. *
  2427. * @param {Texture} source - The texture to copy.
  2428. * @return {Texture} A reference to this instance.
  2429. */
  2430. copy( source ) {
  2431. this.name = source.name;
  2432. this.source = source.source;
  2433. this.mipmaps = source.mipmaps.slice( 0 );
  2434. this.mapping = source.mapping;
  2435. this.channel = source.channel;
  2436. this.wrapS = source.wrapS;
  2437. this.wrapT = source.wrapT;
  2438. this.magFilter = source.magFilter;
  2439. this.minFilter = source.minFilter;
  2440. this.anisotropy = source.anisotropy;
  2441. this.format = source.format;
  2442. this.internalFormat = source.internalFormat;
  2443. this.type = source.type;
  2444. this.offset.copy( source.offset );
  2445. this.repeat.copy( source.repeat );
  2446. this.center.copy( source.center );
  2447. this.rotation = source.rotation;
  2448. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2449. this.matrix.copy( source.matrix );
  2450. this.generateMipmaps = source.generateMipmaps;
  2451. this.premultiplyAlpha = source.premultiplyAlpha;
  2452. this.flipY = source.flipY;
  2453. this.unpackAlignment = source.unpackAlignment;
  2454. this.colorSpace = source.colorSpace;
  2455. this.renderTarget = source.renderTarget;
  2456. this.isRenderTargetTexture = source.isRenderTargetTexture;
  2457. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2458. this.needsUpdate = true;
  2459. return this;
  2460. }
  2461. /**
  2462. * Serializes the texture into JSON.
  2463. *
  2464. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  2465. * @return {Object} A JSON object representing the serialized texture.
  2466. * @see {@link ObjectLoader#parse}
  2467. */
  2468. toJSON( meta ) {
  2469. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2470. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2471. return meta.textures[ this.uuid ];
  2472. }
  2473. const output = {
  2474. metadata: {
  2475. version: 4.6,
  2476. type: 'Texture',
  2477. generator: 'Texture.toJSON'
  2478. },
  2479. uuid: this.uuid,
  2480. name: this.name,
  2481. image: this.source.toJSON( meta ).uuid,
  2482. mapping: this.mapping,
  2483. channel: this.channel,
  2484. repeat: [ this.repeat.x, this.repeat.y ],
  2485. offset: [ this.offset.x, this.offset.y ],
  2486. center: [ this.center.x, this.center.y ],
  2487. rotation: this.rotation,
  2488. wrap: [ this.wrapS, this.wrapT ],
  2489. format: this.format,
  2490. internalFormat: this.internalFormat,
  2491. type: this.type,
  2492. colorSpace: this.colorSpace,
  2493. minFilter: this.minFilter,
  2494. magFilter: this.magFilter,
  2495. anisotropy: this.anisotropy,
  2496. flipY: this.flipY,
  2497. generateMipmaps: this.generateMipmaps,
  2498. premultiplyAlpha: this.premultiplyAlpha,
  2499. unpackAlignment: this.unpackAlignment
  2500. };
  2501. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2502. if ( ! isRootObject ) {
  2503. meta.textures[ this.uuid ] = output;
  2504. }
  2505. return output;
  2506. }
  2507. /**
  2508. * Frees the GPU-related resources allocated by this instance. Call this
  2509. * method whenever this instance is no longer used in your app.
  2510. *
  2511. * @fires Texture#dispose
  2512. */
  2513. dispose() {
  2514. /**
  2515. * Fires when the texture has been disposed of.
  2516. *
  2517. * @event Texture#dispose
  2518. * @type {Object}
  2519. */
  2520. this.dispatchEvent( { type: 'dispose' } );
  2521. }
  2522. /**
  2523. * Transforms the given uv vector with the textures uv transformation matrix.
  2524. *
  2525. * @param {Vector2} uv - The uv vector.
  2526. * @return {Vector2} The transformed uv vector.
  2527. */
  2528. transformUv( uv ) {
  2529. if ( this.mapping !== UVMapping ) return uv;
  2530. uv.applyMatrix3( this.matrix );
  2531. if ( uv.x < 0 || uv.x > 1 ) {
  2532. switch ( this.wrapS ) {
  2533. case RepeatWrapping:
  2534. uv.x = uv.x - Math.floor( uv.x );
  2535. break;
  2536. case ClampToEdgeWrapping:
  2537. uv.x = uv.x < 0 ? 0 : 1;
  2538. break;
  2539. case MirroredRepeatWrapping:
  2540. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2541. uv.x = Math.ceil( uv.x ) - uv.x;
  2542. } else {
  2543. uv.x = uv.x - Math.floor( uv.x );
  2544. }
  2545. break;
  2546. }
  2547. }
  2548. if ( uv.y < 0 || uv.y > 1 ) {
  2549. switch ( this.wrapT ) {
  2550. case RepeatWrapping:
  2551. uv.y = uv.y - Math.floor( uv.y );
  2552. break;
  2553. case ClampToEdgeWrapping:
  2554. uv.y = uv.y < 0 ? 0 : 1;
  2555. break;
  2556. case MirroredRepeatWrapping:
  2557. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2558. uv.y = Math.ceil( uv.y ) - uv.y;
  2559. } else {
  2560. uv.y = uv.y - Math.floor( uv.y );
  2561. }
  2562. break;
  2563. }
  2564. }
  2565. if ( this.flipY ) {
  2566. uv.y = 1 - uv.y;
  2567. }
  2568. return uv;
  2569. }
  2570. /**
  2571. * Setting this property to `true` indicates the engine the texture
  2572. * must be updated in the next render. This triggers a texture upload
  2573. * to the GPU and ensures correct texture parameter configuration.
  2574. *
  2575. * @type {boolean}
  2576. * @default false
  2577. * @param {boolean} value
  2578. */
  2579. set needsUpdate( value ) {
  2580. if ( value === true ) {
  2581. this.version ++;
  2582. this.source.needsUpdate = true;
  2583. }
  2584. }
  2585. /**
  2586. * Setting this property to `true` indicates the engine the PMREM
  2587. * must be regenerated.
  2588. *
  2589. * @type {boolean}
  2590. * @default false
  2591. * @param {boolean} value
  2592. */
  2593. set needsPMREMUpdate( value ) {
  2594. if ( value === true ) {
  2595. this.pmremVersion ++;
  2596. }
  2597. }
  2598. }
  2599. /**
  2600. * The default image for all textures.
  2601. *
  2602. * @static
  2603. * @type {?Image}
  2604. * @default null
  2605. */
  2606. Texture.DEFAULT_IMAGE = null;
  2607. /**
  2608. * The default mapping for all textures.
  2609. *
  2610. * @static
  2611. * @type {number}
  2612. * @default UVMapping
  2613. */
  2614. Texture.DEFAULT_MAPPING = UVMapping;
  2615. /**
  2616. * The default anisotropy value for all textures.
  2617. *
  2618. * @static
  2619. * @type {number}
  2620. * @default 1
  2621. */
  2622. Texture.DEFAULT_ANISOTROPY = 1;
  2623. /**
  2624. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  2625. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  2626. *
  2627. * - A point in 4D space.
  2628. * - A direction and length in 4D space. In three.js the length will
  2629. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  2630. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  2631. * - Any arbitrary ordered quadruplet of numbers.
  2632. *
  2633. * There are other things a 4D vector can be used to represent, however these
  2634. * are the most common uses in *three.js*.
  2635. *
  2636. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2637. * the corresponding order.
  2638. * ```js
  2639. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  2640. *
  2641. * //no arguments; will be initialised to (0, 0, 0, 1)
  2642. * const b = new THREE.Vector4( );
  2643. *
  2644. * const d = a.dot( b );
  2645. * ```
  2646. */
  2647. class Vector4 {
  2648. /**
  2649. * Constructs a new 4D vector.
  2650. *
  2651. * @param {number} [x=0] - The x value of this vector.
  2652. * @param {number} [y=0] - The y value of this vector.
  2653. * @param {number} [z=0] - The z value of this vector.
  2654. * @param {number} [w=1] - The w value of this vector.
  2655. */
  2656. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2657. /**
  2658. * This flag can be used for type testing.
  2659. *
  2660. * @type {boolean}
  2661. * @readonly
  2662. * @default true
  2663. */
  2664. Vector4.prototype.isVector4 = true;
  2665. /**
  2666. * The x value of this vector.
  2667. *
  2668. * @type {number}
  2669. */
  2670. this.x = x;
  2671. /**
  2672. * The y value of this vector.
  2673. *
  2674. * @type {number}
  2675. */
  2676. this.y = y;
  2677. /**
  2678. * The z value of this vector.
  2679. *
  2680. * @type {number}
  2681. */
  2682. this.z = z;
  2683. /**
  2684. * The w value of this vector.
  2685. *
  2686. * @type {number}
  2687. */
  2688. this.w = w;
  2689. }
  2690. /**
  2691. * Alias for {@link Vector4#z}.
  2692. *
  2693. * @type {number}
  2694. */
  2695. get width() {
  2696. return this.z;
  2697. }
  2698. set width( value ) {
  2699. this.z = value;
  2700. }
  2701. /**
  2702. * Alias for {@link Vector4#w}.
  2703. *
  2704. * @type {number}
  2705. */
  2706. get height() {
  2707. return this.w;
  2708. }
  2709. set height( value ) {
  2710. this.w = value;
  2711. }
  2712. /**
  2713. * Sets the vector components.
  2714. *
  2715. * @param {number} x - The value of the x component.
  2716. * @param {number} y - The value of the y component.
  2717. * @param {number} z - The value of the z component.
  2718. * @param {number} w - The value of the w component.
  2719. * @return {Vector4} A reference to this vector.
  2720. */
  2721. set( x, y, z, w ) {
  2722. this.x = x;
  2723. this.y = y;
  2724. this.z = z;
  2725. this.w = w;
  2726. return this;
  2727. }
  2728. /**
  2729. * Sets the vector components to the same value.
  2730. *
  2731. * @param {number} scalar - The value to set for all vector components.
  2732. * @return {Vector4} A reference to this vector.
  2733. */
  2734. setScalar( scalar ) {
  2735. this.x = scalar;
  2736. this.y = scalar;
  2737. this.z = scalar;
  2738. this.w = scalar;
  2739. return this;
  2740. }
  2741. /**
  2742. * Sets the vector's x component to the given value
  2743. *
  2744. * @param {number} x - The value to set.
  2745. * @return {Vector4} A reference to this vector.
  2746. */
  2747. setX( x ) {
  2748. this.x = x;
  2749. return this;
  2750. }
  2751. /**
  2752. * Sets the vector's y component to the given value
  2753. *
  2754. * @param {number} y - The value to set.
  2755. * @return {Vector4} A reference to this vector.
  2756. */
  2757. setY( y ) {
  2758. this.y = y;
  2759. return this;
  2760. }
  2761. /**
  2762. * Sets the vector's z component to the given value
  2763. *
  2764. * @param {number} z - The value to set.
  2765. * @return {Vector4} A reference to this vector.
  2766. */
  2767. setZ( z ) {
  2768. this.z = z;
  2769. return this;
  2770. }
  2771. /**
  2772. * Sets the vector's w component to the given value
  2773. *
  2774. * @param {number} w - The value to set.
  2775. * @return {Vector4} A reference to this vector.
  2776. */
  2777. setW( w ) {
  2778. this.w = w;
  2779. return this;
  2780. }
  2781. /**
  2782. * Allows to set a vector component with an index.
  2783. *
  2784. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2785. * `2` equals to z, `3` equals to w.
  2786. * @param {number} value - The value to set.
  2787. * @return {Vector4} A reference to this vector.
  2788. */
  2789. setComponent( index, value ) {
  2790. switch ( index ) {
  2791. case 0: this.x = value; break;
  2792. case 1: this.y = value; break;
  2793. case 2: this.z = value; break;
  2794. case 3: this.w = value; break;
  2795. default: throw new Error( 'index is out of range: ' + index );
  2796. }
  2797. return this;
  2798. }
  2799. /**
  2800. * Returns the value of the vector component which matches the given index.
  2801. *
  2802. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  2803. * `2` equals to z, `3` equals to w.
  2804. * @return {number} A vector component value.
  2805. */
  2806. getComponent( index ) {
  2807. switch ( index ) {
  2808. case 0: return this.x;
  2809. case 1: return this.y;
  2810. case 2: return this.z;
  2811. case 3: return this.w;
  2812. default: throw new Error( 'index is out of range: ' + index );
  2813. }
  2814. }
  2815. /**
  2816. * Returns a new vector with copied values from this instance.
  2817. *
  2818. * @return {Vector4} A clone of this instance.
  2819. */
  2820. clone() {
  2821. return new this.constructor( this.x, this.y, this.z, this.w );
  2822. }
  2823. /**
  2824. * Copies the values of the given vector to this instance.
  2825. *
  2826. * @param {Vector3|Vector4} v - The vector to copy.
  2827. * @return {Vector4} A reference to this vector.
  2828. */
  2829. copy( v ) {
  2830. this.x = v.x;
  2831. this.y = v.y;
  2832. this.z = v.z;
  2833. this.w = ( v.w !== undefined ) ? v.w : 1;
  2834. return this;
  2835. }
  2836. /**
  2837. * Adds the given vector to this instance.
  2838. *
  2839. * @param {Vector4} v - The vector to add.
  2840. * @return {Vector4} A reference to this vector.
  2841. */
  2842. add( v ) {
  2843. this.x += v.x;
  2844. this.y += v.y;
  2845. this.z += v.z;
  2846. this.w += v.w;
  2847. return this;
  2848. }
  2849. /**
  2850. * Adds the given scalar value to all components of this instance.
  2851. *
  2852. * @param {number} s - The scalar to add.
  2853. * @return {Vector4} A reference to this vector.
  2854. */
  2855. addScalar( s ) {
  2856. this.x += s;
  2857. this.y += s;
  2858. this.z += s;
  2859. this.w += s;
  2860. return this;
  2861. }
  2862. /**
  2863. * Adds the given vectors and stores the result in this instance.
  2864. *
  2865. * @param {Vector4} a - The first vector.
  2866. * @param {Vector4} b - The second vector.
  2867. * @return {Vector4} A reference to this vector.
  2868. */
  2869. addVectors( a, b ) {
  2870. this.x = a.x + b.x;
  2871. this.y = a.y + b.y;
  2872. this.z = a.z + b.z;
  2873. this.w = a.w + b.w;
  2874. return this;
  2875. }
  2876. /**
  2877. * Adds the given vector scaled by the given factor to this instance.
  2878. *
  2879. * @param {Vector4} v - The vector.
  2880. * @param {number} s - The factor that scales `v`.
  2881. * @return {Vector4} A reference to this vector.
  2882. */
  2883. addScaledVector( v, s ) {
  2884. this.x += v.x * s;
  2885. this.y += v.y * s;
  2886. this.z += v.z * s;
  2887. this.w += v.w * s;
  2888. return this;
  2889. }
  2890. /**
  2891. * Subtracts the given vector from this instance.
  2892. *
  2893. * @param {Vector4} v - The vector to subtract.
  2894. * @return {Vector4} A reference to this vector.
  2895. */
  2896. sub( v ) {
  2897. this.x -= v.x;
  2898. this.y -= v.y;
  2899. this.z -= v.z;
  2900. this.w -= v.w;
  2901. return this;
  2902. }
  2903. /**
  2904. * Subtracts the given scalar value from all components of this instance.
  2905. *
  2906. * @param {number} s - The scalar to subtract.
  2907. * @return {Vector4} A reference to this vector.
  2908. */
  2909. subScalar( s ) {
  2910. this.x -= s;
  2911. this.y -= s;
  2912. this.z -= s;
  2913. this.w -= s;
  2914. return this;
  2915. }
  2916. /**
  2917. * Subtracts the given vectors and stores the result in this instance.
  2918. *
  2919. * @param {Vector4} a - The first vector.
  2920. * @param {Vector4} b - The second vector.
  2921. * @return {Vector4} A reference to this vector.
  2922. */
  2923. subVectors( a, b ) {
  2924. this.x = a.x - b.x;
  2925. this.y = a.y - b.y;
  2926. this.z = a.z - b.z;
  2927. this.w = a.w - b.w;
  2928. return this;
  2929. }
  2930. /**
  2931. * Multiplies the given vector with this instance.
  2932. *
  2933. * @param {Vector4} v - The vector to multiply.
  2934. * @return {Vector4} A reference to this vector.
  2935. */
  2936. multiply( v ) {
  2937. this.x *= v.x;
  2938. this.y *= v.y;
  2939. this.z *= v.z;
  2940. this.w *= v.w;
  2941. return this;
  2942. }
  2943. /**
  2944. * Multiplies the given scalar value with all components of this instance.
  2945. *
  2946. * @param {number} scalar - The scalar to multiply.
  2947. * @return {Vector4} A reference to this vector.
  2948. */
  2949. multiplyScalar( scalar ) {
  2950. this.x *= scalar;
  2951. this.y *= scalar;
  2952. this.z *= scalar;
  2953. this.w *= scalar;
  2954. return this;
  2955. }
  2956. /**
  2957. * Multiplies this vector with the given 4x4 matrix.
  2958. *
  2959. * @param {Matrix4} m - The 4x4 matrix.
  2960. * @return {Vector4} A reference to this vector.
  2961. */
  2962. applyMatrix4( m ) {
  2963. const x = this.x, y = this.y, z = this.z, w = this.w;
  2964. const e = m.elements;
  2965. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2966. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2967. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2968. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2969. return this;
  2970. }
  2971. /**
  2972. * Divides this instance by the given vector.
  2973. *
  2974. * @param {Vector4} v - The vector to divide.
  2975. * @return {Vector4} A reference to this vector.
  2976. */
  2977. divide( v ) {
  2978. this.x /= v.x;
  2979. this.y /= v.y;
  2980. this.z /= v.z;
  2981. this.w /= v.w;
  2982. return this;
  2983. }
  2984. /**
  2985. * Divides this vector by the given scalar.
  2986. *
  2987. * @param {number} scalar - The scalar to divide.
  2988. * @return {Vector4} A reference to this vector.
  2989. */
  2990. divideScalar( scalar ) {
  2991. return this.multiplyScalar( 1 / scalar );
  2992. }
  2993. /**
  2994. * Sets the x, y and z components of this
  2995. * vector to the quaternion's axis and w to the angle.
  2996. *
  2997. * @param {Quaternion} q - The Quaternion to set.
  2998. * @return {Vector4} A reference to this vector.
  2999. */
  3000. setAxisAngleFromQuaternion( q ) {
  3001. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  3002. // q is assumed to be normalized
  3003. this.w = 2 * Math.acos( q.w );
  3004. const s = Math.sqrt( 1 - q.w * q.w );
  3005. if ( s < 0.0001 ) {
  3006. this.x = 1;
  3007. this.y = 0;
  3008. this.z = 0;
  3009. } else {
  3010. this.x = q.x / s;
  3011. this.y = q.y / s;
  3012. this.z = q.z / s;
  3013. }
  3014. return this;
  3015. }
  3016. /**
  3017. * Sets the x, y and z components of this
  3018. * vector to the axis of rotation and w to the angle.
  3019. *
  3020. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  3021. * @return {Vector4} A reference to this vector.
  3022. */
  3023. setAxisAngleFromRotationMatrix( m ) {
  3024. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  3025. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3026. let angle, x, y, z; // variables for result
  3027. const epsilon = 0.01, // margin to allow for rounding errors
  3028. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  3029. te = m.elements,
  3030. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3031. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3032. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  3033. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  3034. ( Math.abs( m13 - m31 ) < epsilon ) &&
  3035. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  3036. // singularity found
  3037. // first check for identity matrix which must have +1 for all terms
  3038. // in leading diagonal and zero in other terms
  3039. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  3040. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  3041. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  3042. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  3043. // this singularity is identity matrix so angle = 0
  3044. this.set( 1, 0, 0, 0 );
  3045. return this; // zero angle, arbitrary axis
  3046. }
  3047. // otherwise this singularity is angle = 180
  3048. angle = Math.PI;
  3049. const xx = ( m11 + 1 ) / 2;
  3050. const yy = ( m22 + 1 ) / 2;
  3051. const zz = ( m33 + 1 ) / 2;
  3052. const xy = ( m12 + m21 ) / 4;
  3053. const xz = ( m13 + m31 ) / 4;
  3054. const yz = ( m23 + m32 ) / 4;
  3055. if ( ( xx > yy ) && ( xx > zz ) ) {
  3056. // m11 is the largest diagonal term
  3057. if ( xx < epsilon ) {
  3058. x = 0;
  3059. y = 0.707106781;
  3060. z = 0.707106781;
  3061. } else {
  3062. x = Math.sqrt( xx );
  3063. y = xy / x;
  3064. z = xz / x;
  3065. }
  3066. } else if ( yy > zz ) {
  3067. // m22 is the largest diagonal term
  3068. if ( yy < epsilon ) {
  3069. x = 0.707106781;
  3070. y = 0;
  3071. z = 0.707106781;
  3072. } else {
  3073. y = Math.sqrt( yy );
  3074. x = xy / y;
  3075. z = yz / y;
  3076. }
  3077. } else {
  3078. // m33 is the largest diagonal term so base result on this
  3079. if ( zz < epsilon ) {
  3080. x = 0.707106781;
  3081. y = 0.707106781;
  3082. z = 0;
  3083. } else {
  3084. z = Math.sqrt( zz );
  3085. x = xz / z;
  3086. y = yz / z;
  3087. }
  3088. }
  3089. this.set( x, y, z, angle );
  3090. return this; // return 180 deg rotation
  3091. }
  3092. // as we have reached here there are no singularities so we can handle normally
  3093. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  3094. ( m13 - m31 ) * ( m13 - m31 ) +
  3095. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  3096. if ( Math.abs( s ) < 0.001 ) s = 1;
  3097. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  3098. // caught by singularity test above, but I've left it in just in case
  3099. this.x = ( m32 - m23 ) / s;
  3100. this.y = ( m13 - m31 ) / s;
  3101. this.z = ( m21 - m12 ) / s;
  3102. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  3103. return this;
  3104. }
  3105. /**
  3106. * Sets the vector components to the position elements of the
  3107. * given transformation matrix.
  3108. *
  3109. * @param {Matrix4} m - The 4x4 matrix.
  3110. * @return {Vector4} A reference to this vector.
  3111. */
  3112. setFromMatrixPosition( m ) {
  3113. const e = m.elements;
  3114. this.x = e[ 12 ];
  3115. this.y = e[ 13 ];
  3116. this.z = e[ 14 ];
  3117. this.w = e[ 15 ];
  3118. return this;
  3119. }
  3120. /**
  3121. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  3122. * value, replace that value with the corresponding min value.
  3123. *
  3124. * @param {Vector4} v - The vector.
  3125. * @return {Vector4} A reference to this vector.
  3126. */
  3127. min( v ) {
  3128. this.x = Math.min( this.x, v.x );
  3129. this.y = Math.min( this.y, v.y );
  3130. this.z = Math.min( this.z, v.z );
  3131. this.w = Math.min( this.w, v.w );
  3132. return this;
  3133. }
  3134. /**
  3135. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  3136. * value, replace that value with the corresponding max value.
  3137. *
  3138. * @param {Vector4} v - The vector.
  3139. * @return {Vector4} A reference to this vector.
  3140. */
  3141. max( v ) {
  3142. this.x = Math.max( this.x, v.x );
  3143. this.y = Math.max( this.y, v.y );
  3144. this.z = Math.max( this.z, v.z );
  3145. this.w = Math.max( this.w, v.w );
  3146. return this;
  3147. }
  3148. /**
  3149. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  3150. * value, it is replaced by the corresponding value.
  3151. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  3152. * it is replaced by the corresponding value.
  3153. *
  3154. * @param {Vector4} min - The minimum x, y and z values.
  3155. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  3156. * @return {Vector4} A reference to this vector.
  3157. */
  3158. clamp( min, max ) {
  3159. // assumes min < max, componentwise
  3160. this.x = clamp( this.x, min.x, max.x );
  3161. this.y = clamp( this.y, min.y, max.y );
  3162. this.z = clamp( this.z, min.z, max.z );
  3163. this.w = clamp( this.w, min.w, max.w );
  3164. return this;
  3165. }
  3166. /**
  3167. * If this vector's x, y, z or w values are greater than the max value, they are
  3168. * replaced by the max value.
  3169. * If this vector's x, y, z or w values are less than the min value, they are
  3170. * replaced by the min value.
  3171. *
  3172. * @param {number} minVal - The minimum value the components will be clamped to.
  3173. * @param {number} maxVal - The maximum value the components will be clamped to.
  3174. * @return {Vector4} A reference to this vector.
  3175. */
  3176. clampScalar( minVal, maxVal ) {
  3177. this.x = clamp( this.x, minVal, maxVal );
  3178. this.y = clamp( this.y, minVal, maxVal );
  3179. this.z = clamp( this.z, minVal, maxVal );
  3180. this.w = clamp( this.w, minVal, maxVal );
  3181. return this;
  3182. }
  3183. /**
  3184. * If this vector's length is greater than the max value, it is replaced by
  3185. * the max value.
  3186. * If this vector's length is less than the min value, it is replaced by the
  3187. * min value.
  3188. *
  3189. * @param {number} min - The minimum value the vector length will be clamped to.
  3190. * @param {number} max - The maximum value the vector length will be clamped to.
  3191. * @return {Vector4} A reference to this vector.
  3192. */
  3193. clampLength( min, max ) {
  3194. const length = this.length();
  3195. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  3196. }
  3197. /**
  3198. * The components of this vector are rounded down to the nearest integer value.
  3199. *
  3200. * @return {Vector4} A reference to this vector.
  3201. */
  3202. floor() {
  3203. this.x = Math.floor( this.x );
  3204. this.y = Math.floor( this.y );
  3205. this.z = Math.floor( this.z );
  3206. this.w = Math.floor( this.w );
  3207. return this;
  3208. }
  3209. /**
  3210. * The components of this vector are rounded up to the nearest integer value.
  3211. *
  3212. * @return {Vector4} A reference to this vector.
  3213. */
  3214. ceil() {
  3215. this.x = Math.ceil( this.x );
  3216. this.y = Math.ceil( this.y );
  3217. this.z = Math.ceil( this.z );
  3218. this.w = Math.ceil( this.w );
  3219. return this;
  3220. }
  3221. /**
  3222. * The components of this vector are rounded to the nearest integer value
  3223. *
  3224. * @return {Vector4} A reference to this vector.
  3225. */
  3226. round() {
  3227. this.x = Math.round( this.x );
  3228. this.y = Math.round( this.y );
  3229. this.z = Math.round( this.z );
  3230. this.w = Math.round( this.w );
  3231. return this;
  3232. }
  3233. /**
  3234. * The components of this vector are rounded towards zero (up if negative,
  3235. * down if positive) to an integer value.
  3236. *
  3237. * @return {Vector4} A reference to this vector.
  3238. */
  3239. roundToZero() {
  3240. this.x = Math.trunc( this.x );
  3241. this.y = Math.trunc( this.y );
  3242. this.z = Math.trunc( this.z );
  3243. this.w = Math.trunc( this.w );
  3244. return this;
  3245. }
  3246. /**
  3247. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  3248. *
  3249. * @return {Vector4} A reference to this vector.
  3250. */
  3251. negate() {
  3252. this.x = - this.x;
  3253. this.y = - this.y;
  3254. this.z = - this.z;
  3255. this.w = - this.w;
  3256. return this;
  3257. }
  3258. /**
  3259. * Calculates the dot product of the given vector with this instance.
  3260. *
  3261. * @param {Vector4} v - The vector to compute the dot product with.
  3262. * @return {number} The result of the dot product.
  3263. */
  3264. dot( v ) {
  3265. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  3266. }
  3267. /**
  3268. * Computes the square of the Euclidean length (straight-line length) from
  3269. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  3270. * compare the length squared instead as it is slightly more efficient to calculate.
  3271. *
  3272. * @return {number} The square length of this vector.
  3273. */
  3274. lengthSq() {
  3275. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3276. }
  3277. /**
  3278. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  3279. *
  3280. * @return {number} The length of this vector.
  3281. */
  3282. length() {
  3283. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3284. }
  3285. /**
  3286. * Computes the Manhattan length of this vector.
  3287. *
  3288. * @return {number} The length of this vector.
  3289. */
  3290. manhattanLength() {
  3291. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  3292. }
  3293. /**
  3294. * Converts this vector to a unit vector - that is, sets it equal to a vector
  3295. * with the same direction as this one, but with a vector length of `1`.
  3296. *
  3297. * @return {Vector4} A reference to this vector.
  3298. */
  3299. normalize() {
  3300. return this.divideScalar( this.length() || 1 );
  3301. }
  3302. /**
  3303. * Sets this vector to a vector with the same direction as this one, but
  3304. * with the specified length.
  3305. *
  3306. * @param {number} length - The new length of this vector.
  3307. * @return {Vector4} A reference to this vector.
  3308. */
  3309. setLength( length ) {
  3310. return this.normalize().multiplyScalar( length );
  3311. }
  3312. /**
  3313. * Linearly interpolates between the given vector and this instance, where
  3314. * alpha is the percent distance along the line - alpha = 0 will be this
  3315. * vector, and alpha = 1 will be the given one.
  3316. *
  3317. * @param {Vector4} v - The vector to interpolate towards.
  3318. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3319. * @return {Vector4} A reference to this vector.
  3320. */
  3321. lerp( v, alpha ) {
  3322. this.x += ( v.x - this.x ) * alpha;
  3323. this.y += ( v.y - this.y ) * alpha;
  3324. this.z += ( v.z - this.z ) * alpha;
  3325. this.w += ( v.w - this.w ) * alpha;
  3326. return this;
  3327. }
  3328. /**
  3329. * Linearly interpolates between the given vectors, where alpha is the percent
  3330. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3331. * be the second one. The result is stored in this instance.
  3332. *
  3333. * @param {Vector4} v1 - The first vector.
  3334. * @param {Vector4} v2 - The second vector.
  3335. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3336. * @return {Vector4} A reference to this vector.
  3337. */
  3338. lerpVectors( v1, v2, alpha ) {
  3339. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3340. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3341. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  3342. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  3343. return this;
  3344. }
  3345. /**
  3346. * Returns `true` if this vector is equal with the given one.
  3347. *
  3348. * @param {Vector4} v - The vector to test for equality.
  3349. * @return {boolean} Whether this vector is equal with the given one.
  3350. */
  3351. equals( v ) {
  3352. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3353. }
  3354. /**
  3355. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  3356. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  3357. *
  3358. * @param {Array<number>} array - An array holding the vector component values.
  3359. * @param {number} [offset=0] - The offset into the array.
  3360. * @return {Vector4} A reference to this vector.
  3361. */
  3362. fromArray( array, offset = 0 ) {
  3363. this.x = array[ offset ];
  3364. this.y = array[ offset + 1 ];
  3365. this.z = array[ offset + 2 ];
  3366. this.w = array[ offset + 3 ];
  3367. return this;
  3368. }
  3369. /**
  3370. * Writes the components of this vector to the given array. If no array is provided,
  3371. * the method returns a new instance.
  3372. *
  3373. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3374. * @param {number} [offset=0] - Index of the first element in the array.
  3375. * @return {Array<number>} The vector components.
  3376. */
  3377. toArray( array = [], offset = 0 ) {
  3378. array[ offset ] = this.x;
  3379. array[ offset + 1 ] = this.y;
  3380. array[ offset + 2 ] = this.z;
  3381. array[ offset + 3 ] = this.w;
  3382. return array;
  3383. }
  3384. /**
  3385. * Sets the components of this vector from the given buffer attribute.
  3386. *
  3387. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3388. * @param {number} index - The index into the attribute.
  3389. * @return {Vector4} A reference to this vector.
  3390. */
  3391. fromBufferAttribute( attribute, index ) {
  3392. this.x = attribute.getX( index );
  3393. this.y = attribute.getY( index );
  3394. this.z = attribute.getZ( index );
  3395. this.w = attribute.getW( index );
  3396. return this;
  3397. }
  3398. /**
  3399. * Sets each component of this vector to a pseudo-random value between `0` and
  3400. * `1`, excluding `1`.
  3401. *
  3402. * @return {Vector4} A reference to this vector.
  3403. */
  3404. random() {
  3405. this.x = Math.random();
  3406. this.y = Math.random();
  3407. this.z = Math.random();
  3408. this.w = Math.random();
  3409. return this;
  3410. }
  3411. *[ Symbol.iterator ]() {
  3412. yield this.x;
  3413. yield this.y;
  3414. yield this.z;
  3415. yield this.w;
  3416. }
  3417. }
  3418. /*
  3419. In options, we can specify:
  3420. * Texture parameters for an auto-generated target texture
  3421. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  3422. */
  3423. class RenderTarget extends EventDispatcher {
  3424. constructor( width = 1, height = 1, options = {} ) {
  3425. super();
  3426. this.isRenderTarget = true;
  3427. this.width = width;
  3428. this.height = height;
  3429. this.depth = 1;
  3430. this.scissor = new Vector4( 0, 0, width, height );
  3431. this.scissorTest = false;
  3432. this.viewport = new Vector4( 0, 0, width, height );
  3433. const image = { width: width, height: height, depth: 1 };
  3434. options = Object.assign( {
  3435. generateMipmaps: false,
  3436. internalFormat: null,
  3437. minFilter: LinearFilter,
  3438. depthBuffer: true,
  3439. stencilBuffer: false,
  3440. resolveDepthBuffer: true,
  3441. resolveStencilBuffer: true,
  3442. depthTexture: null,
  3443. samples: 0,
  3444. count: 1
  3445. }, options );
  3446. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  3447. texture.flipY = false;
  3448. texture.generateMipmaps = options.generateMipmaps;
  3449. texture.internalFormat = options.internalFormat;
  3450. this.textures = [];
  3451. const count = options.count;
  3452. for ( let i = 0; i < count; i ++ ) {
  3453. this.textures[ i ] = texture.clone();
  3454. this.textures[ i ].isRenderTargetTexture = true;
  3455. this.textures[ i ].renderTarget = this;
  3456. }
  3457. this.depthBuffer = options.depthBuffer;
  3458. this.stencilBuffer = options.stencilBuffer;
  3459. this.resolveDepthBuffer = options.resolveDepthBuffer;
  3460. this.resolveStencilBuffer = options.resolveStencilBuffer;
  3461. this._depthTexture = null;
  3462. this.depthTexture = options.depthTexture;
  3463. this.samples = options.samples;
  3464. }
  3465. get texture() {
  3466. return this.textures[ 0 ];
  3467. }
  3468. set texture( value ) {
  3469. this.textures[ 0 ] = value;
  3470. }
  3471. set depthTexture( current ) {
  3472. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  3473. if ( current !== null ) current.renderTarget = this;
  3474. this._depthTexture = current;
  3475. }
  3476. get depthTexture() {
  3477. return this._depthTexture;
  3478. }
  3479. setSize( width, height, depth = 1 ) {
  3480. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  3481. this.width = width;
  3482. this.height = height;
  3483. this.depth = depth;
  3484. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  3485. this.textures[ i ].image.width = width;
  3486. this.textures[ i ].image.height = height;
  3487. this.textures[ i ].image.depth = depth;
  3488. }
  3489. this.dispose();
  3490. }
  3491. this.viewport.set( 0, 0, width, height );
  3492. this.scissor.set( 0, 0, width, height );
  3493. }
  3494. clone() {
  3495. return new this.constructor().copy( this );
  3496. }
  3497. copy( source ) {
  3498. this.width = source.width;
  3499. this.height = source.height;
  3500. this.depth = source.depth;
  3501. this.scissor.copy( source.scissor );
  3502. this.scissorTest = source.scissorTest;
  3503. this.viewport.copy( source.viewport );
  3504. this.textures.length = 0;
  3505. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  3506. this.textures[ i ] = source.textures[ i ].clone();
  3507. this.textures[ i ].isRenderTargetTexture = true;
  3508. this.textures[ i ].renderTarget = this;
  3509. // ensure image object is not shared, see #20328
  3510. const image = Object.assign( {}, source.textures[ i ].image );
  3511. this.textures[ i ].source = new Source( image );
  3512. }
  3513. this.depthBuffer = source.depthBuffer;
  3514. this.stencilBuffer = source.stencilBuffer;
  3515. this.resolveDepthBuffer = source.resolveDepthBuffer;
  3516. this.resolveStencilBuffer = source.resolveStencilBuffer;
  3517. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  3518. this.samples = source.samples;
  3519. return this;
  3520. }
  3521. dispose() {
  3522. this.dispatchEvent( { type: 'dispose' } );
  3523. }
  3524. }
  3525. class WebGLRenderTarget extends RenderTarget {
  3526. constructor( width = 1, height = 1, options = {} ) {
  3527. super( width, height, options );
  3528. this.isWebGLRenderTarget = true;
  3529. }
  3530. }
  3531. class DataArrayTexture extends Texture {
  3532. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3533. super( null );
  3534. this.isDataArrayTexture = true;
  3535. this.image = { data, width, height, depth };
  3536. this.magFilter = NearestFilter;
  3537. this.minFilter = NearestFilter;
  3538. this.wrapR = ClampToEdgeWrapping;
  3539. this.generateMipmaps = false;
  3540. this.flipY = false;
  3541. this.unpackAlignment = 1;
  3542. this.layerUpdates = new Set();
  3543. }
  3544. addLayerUpdate( layerIndex ) {
  3545. this.layerUpdates.add( layerIndex );
  3546. }
  3547. clearLayerUpdates() {
  3548. this.layerUpdates.clear();
  3549. }
  3550. }
  3551. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  3552. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3553. super( width, height, options );
  3554. this.isWebGLArrayRenderTarget = true;
  3555. this.depth = depth;
  3556. this.texture = new DataArrayTexture( null, width, height, depth );
  3557. this.texture.isRenderTargetTexture = true;
  3558. }
  3559. }
  3560. class Data3DTexture extends Texture {
  3561. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  3562. // We're going to add .setXXX() methods for setting properties later.
  3563. // Users can still set in Data3DTexture directly.
  3564. //
  3565. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  3566. // texture.anisotropy = 16;
  3567. //
  3568. // See #14839
  3569. super( null );
  3570. this.isData3DTexture = true;
  3571. this.image = { data, width, height, depth };
  3572. this.magFilter = NearestFilter;
  3573. this.minFilter = NearestFilter;
  3574. this.wrapR = ClampToEdgeWrapping;
  3575. this.generateMipmaps = false;
  3576. this.flipY = false;
  3577. this.unpackAlignment = 1;
  3578. }
  3579. }
  3580. class WebGL3DRenderTarget extends WebGLRenderTarget {
  3581. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  3582. super( width, height, options );
  3583. this.isWebGL3DRenderTarget = true;
  3584. this.depth = depth;
  3585. this.texture = new Data3DTexture( null, width, height, depth );
  3586. this.texture.isRenderTargetTexture = true;
  3587. }
  3588. }
  3589. /**
  3590. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3591. *
  3592. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3593. * the corresponding order.
  3594. *
  3595. * Note that three.js expects Quaternions to be normalized.
  3596. * ```js
  3597. * const quaternion = new THREE.Quaternion();
  3598. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3599. *
  3600. * const vector = new THREE.Vector3( 1, 0, 0 );
  3601. * vector.applyQuaternion( quaternion );
  3602. * ```
  3603. */
  3604. class Quaternion {
  3605. /**
  3606. * Constructs a new quaternion.
  3607. *
  3608. * @param {number} [x=0] - The x value of this quaternion.
  3609. * @param {number} [y=0] - The y value of this quaternion.
  3610. * @param {number} [z=0] - The z value of this quaternion.
  3611. * @param {number} [w=1] - The w value of this quaternion.
  3612. */
  3613. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3614. /**
  3615. * This flag can be used for type testing.
  3616. *
  3617. * @type {boolean}
  3618. * @readonly
  3619. * @default true
  3620. */
  3621. this.isQuaternion = true;
  3622. this._x = x;
  3623. this._y = y;
  3624. this._z = z;
  3625. this._w = w;
  3626. }
  3627. /**
  3628. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3629. * quaternion data are managed in flat arrays.
  3630. *
  3631. * @param {Array<number>} dst - The destination array.
  3632. * @param {number} dstOffset - An offset into the destination array.
  3633. * @param {Array<number>} src0 - The source array of the first quaternion.
  3634. * @param {number} srcOffset0 - An offset into the first source array.
  3635. * @param {Array<number>} src1 - The source array of the second quaternion.
  3636. * @param {number} srcOffset1 - An offset into the second source array.
  3637. * @param {number} t - The interpolation factor in the range `[0,1]`.
  3638. * @see {@link Quaternion#slerp}
  3639. */
  3640. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3641. // fuzz-free, array-based Quaternion SLERP operation
  3642. let x0 = src0[ srcOffset0 + 0 ],
  3643. y0 = src0[ srcOffset0 + 1 ],
  3644. z0 = src0[ srcOffset0 + 2 ],
  3645. w0 = src0[ srcOffset0 + 3 ];
  3646. const x1 = src1[ srcOffset1 + 0 ],
  3647. y1 = src1[ srcOffset1 + 1 ],
  3648. z1 = src1[ srcOffset1 + 2 ],
  3649. w1 = src1[ srcOffset1 + 3 ];
  3650. if ( t === 0 ) {
  3651. dst[ dstOffset + 0 ] = x0;
  3652. dst[ dstOffset + 1 ] = y0;
  3653. dst[ dstOffset + 2 ] = z0;
  3654. dst[ dstOffset + 3 ] = w0;
  3655. return;
  3656. }
  3657. if ( t === 1 ) {
  3658. dst[ dstOffset + 0 ] = x1;
  3659. dst[ dstOffset + 1 ] = y1;
  3660. dst[ dstOffset + 2 ] = z1;
  3661. dst[ dstOffset + 3 ] = w1;
  3662. return;
  3663. }
  3664. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3665. let s = 1 - t;
  3666. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  3667. dir = ( cos >= 0 ? 1 : -1 ),
  3668. sqrSin = 1 - cos * cos;
  3669. // Skip the Slerp for tiny steps to avoid numeric problems:
  3670. if ( sqrSin > Number.EPSILON ) {
  3671. const sin = Math.sqrt( sqrSin ),
  3672. len = Math.atan2( sin, cos * dir );
  3673. s = Math.sin( s * len ) / sin;
  3674. t = Math.sin( t * len ) / sin;
  3675. }
  3676. const tDir = t * dir;
  3677. x0 = x0 * s + x1 * tDir;
  3678. y0 = y0 * s + y1 * tDir;
  3679. z0 = z0 * s + z1 * tDir;
  3680. w0 = w0 * s + w1 * tDir;
  3681. // Normalize in case we just did a lerp:
  3682. if ( s === 1 - t ) {
  3683. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3684. x0 *= f;
  3685. y0 *= f;
  3686. z0 *= f;
  3687. w0 *= f;
  3688. }
  3689. }
  3690. dst[ dstOffset ] = x0;
  3691. dst[ dstOffset + 1 ] = y0;
  3692. dst[ dstOffset + 2 ] = z0;
  3693. dst[ dstOffset + 3 ] = w0;
  3694. }
  3695. /**
  3696. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3697. * in flat arrays.
  3698. *
  3699. * @param {Array<number>} dst - The destination array.
  3700. * @param {number} dstOffset - An offset into the destination array.
  3701. * @param {Array<number>} src0 - The source array of the first quaternion.
  3702. * @param {number} srcOffset0 - An offset into the first source array.
  3703. * @param {Array<number>} src1 - The source array of the second quaternion.
  3704. * @param {number} srcOffset1 - An offset into the second source array.
  3705. * @return {Array<number>} The destination array.
  3706. * @see {@link Quaternion#multiplyQuaternions}.
  3707. */
  3708. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3709. const x0 = src0[ srcOffset0 ];
  3710. const y0 = src0[ srcOffset0 + 1 ];
  3711. const z0 = src0[ srcOffset0 + 2 ];
  3712. const w0 = src0[ srcOffset0 + 3 ];
  3713. const x1 = src1[ srcOffset1 ];
  3714. const y1 = src1[ srcOffset1 + 1 ];
  3715. const z1 = src1[ srcOffset1 + 2 ];
  3716. const w1 = src1[ srcOffset1 + 3 ];
  3717. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3718. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3719. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3720. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3721. return dst;
  3722. }
  3723. /**
  3724. * The x value of this quaternion.
  3725. *
  3726. * @type {number}
  3727. * @default 0
  3728. */
  3729. get x() {
  3730. return this._x;
  3731. }
  3732. set x( value ) {
  3733. this._x = value;
  3734. this._onChangeCallback();
  3735. }
  3736. /**
  3737. * The y value of this quaternion.
  3738. *
  3739. * @type {number}
  3740. * @default 0
  3741. */
  3742. get y() {
  3743. return this._y;
  3744. }
  3745. set y( value ) {
  3746. this._y = value;
  3747. this._onChangeCallback();
  3748. }
  3749. /**
  3750. * The z value of this quaternion.
  3751. *
  3752. * @type {number}
  3753. * @default 0
  3754. */
  3755. get z() {
  3756. return this._z;
  3757. }
  3758. set z( value ) {
  3759. this._z = value;
  3760. this._onChangeCallback();
  3761. }
  3762. /**
  3763. * The w value of this quaternion.
  3764. *
  3765. * @type {number}
  3766. * @default 1
  3767. */
  3768. get w() {
  3769. return this._w;
  3770. }
  3771. set w( value ) {
  3772. this._w = value;
  3773. this._onChangeCallback();
  3774. }
  3775. /**
  3776. * Sets the quaternion components.
  3777. *
  3778. * @param {number} x - The x value of this quaternion.
  3779. * @param {number} y - The y value of this quaternion.
  3780. * @param {number} z - The z value of this quaternion.
  3781. * @param {number} w - The w value of this quaternion.
  3782. * @return {Quaternion} A reference to this quaternion.
  3783. */
  3784. set( x, y, z, w ) {
  3785. this._x = x;
  3786. this._y = y;
  3787. this._z = z;
  3788. this._w = w;
  3789. this._onChangeCallback();
  3790. return this;
  3791. }
  3792. /**
  3793. * Returns a new quaternion with copied values from this instance.
  3794. *
  3795. * @return {Quaternion} A clone of this instance.
  3796. */
  3797. clone() {
  3798. return new this.constructor( this._x, this._y, this._z, this._w );
  3799. }
  3800. /**
  3801. * Copies the values of the given quaternion to this instance.
  3802. *
  3803. * @param {Quaternion} quaternion - The quaternion to copy.
  3804. * @return {Quaternion} A reference to this quaternion.
  3805. */
  3806. copy( quaternion ) {
  3807. this._x = quaternion.x;
  3808. this._y = quaternion.y;
  3809. this._z = quaternion.z;
  3810. this._w = quaternion.w;
  3811. this._onChangeCallback();
  3812. return this;
  3813. }
  3814. /**
  3815. * Sets this quaternion from the rotation specified by the given
  3816. * Euler angles.
  3817. *
  3818. * @param {Euler} euler - The Euler angles.
  3819. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3820. * @return {Quaternion} A reference to this quaternion.
  3821. */
  3822. setFromEuler( euler, update = true ) {
  3823. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3824. // http://www.mathworks.com/matlabcentral/fileexchange/
  3825. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3826. // content/SpinCalc.m
  3827. const cos = Math.cos;
  3828. const sin = Math.sin;
  3829. const c1 = cos( x / 2 );
  3830. const c2 = cos( y / 2 );
  3831. const c3 = cos( z / 2 );
  3832. const s1 = sin( x / 2 );
  3833. const s2 = sin( y / 2 );
  3834. const s3 = sin( z / 2 );
  3835. switch ( order ) {
  3836. case 'XYZ':
  3837. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3838. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3839. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3840. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3841. break;
  3842. case 'YXZ':
  3843. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3844. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3845. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3846. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3847. break;
  3848. case 'ZXY':
  3849. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3850. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3851. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3852. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3853. break;
  3854. case 'ZYX':
  3855. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3856. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3857. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3858. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3859. break;
  3860. case 'YZX':
  3861. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3862. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3863. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3864. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3865. break;
  3866. case 'XZY':
  3867. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3868. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3869. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3870. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3871. break;
  3872. default:
  3873. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3874. }
  3875. if ( update === true ) this._onChangeCallback();
  3876. return this;
  3877. }
  3878. /**
  3879. * Sets this quaternion from the given axis and angle.
  3880. *
  3881. * @param {Vector3} axis - The normalized axis.
  3882. * @param {number} angle - The angle in radians.
  3883. * @return {Quaternion} A reference to this quaternion.
  3884. */
  3885. setFromAxisAngle( axis, angle ) {
  3886. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3887. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3888. this._x = axis.x * s;
  3889. this._y = axis.y * s;
  3890. this._z = axis.z * s;
  3891. this._w = Math.cos( halfAngle );
  3892. this._onChangeCallback();
  3893. return this;
  3894. }
  3895. /**
  3896. * Sets this quaternion from the given rotation matrix.
  3897. *
  3898. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3899. * @return {Quaternion} A reference to this quaternion.
  3900. */
  3901. setFromRotationMatrix( m ) {
  3902. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3903. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3904. const te = m.elements,
  3905. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3906. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3907. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3908. trace = m11 + m22 + m33;
  3909. if ( trace > 0 ) {
  3910. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3911. this._w = 0.25 / s;
  3912. this._x = ( m32 - m23 ) * s;
  3913. this._y = ( m13 - m31 ) * s;
  3914. this._z = ( m21 - m12 ) * s;
  3915. } else if ( m11 > m22 && m11 > m33 ) {
  3916. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3917. this._w = ( m32 - m23 ) / s;
  3918. this._x = 0.25 * s;
  3919. this._y = ( m12 + m21 ) / s;
  3920. this._z = ( m13 + m31 ) / s;
  3921. } else if ( m22 > m33 ) {
  3922. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3923. this._w = ( m13 - m31 ) / s;
  3924. this._x = ( m12 + m21 ) / s;
  3925. this._y = 0.25 * s;
  3926. this._z = ( m23 + m32 ) / s;
  3927. } else {
  3928. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3929. this._w = ( m21 - m12 ) / s;
  3930. this._x = ( m13 + m31 ) / s;
  3931. this._y = ( m23 + m32 ) / s;
  3932. this._z = 0.25 * s;
  3933. }
  3934. this._onChangeCallback();
  3935. return this;
  3936. }
  3937. /**
  3938. * Sets this quaternion to the rotation required to rotate the direction vector
  3939. * `vFrom` to the direction vector `vTo`.
  3940. *
  3941. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3942. * @param {Vector3} vTo - The second (normalized) direction vector.
  3943. * @return {Quaternion} A reference to this quaternion.
  3944. */
  3945. setFromUnitVectors( vFrom, vTo ) {
  3946. // assumes direction vectors vFrom and vTo are normalized
  3947. let r = vFrom.dot( vTo ) + 1;
  3948. if ( r < Number.EPSILON ) {
  3949. // vFrom and vTo point in opposite directions
  3950. r = 0;
  3951. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3952. this._x = - vFrom.y;
  3953. this._y = vFrom.x;
  3954. this._z = 0;
  3955. this._w = r;
  3956. } else {
  3957. this._x = 0;
  3958. this._y = - vFrom.z;
  3959. this._z = vFrom.y;
  3960. this._w = r;
  3961. }
  3962. } else {
  3963. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3964. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3965. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3966. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3967. this._w = r;
  3968. }
  3969. return this.normalize();
  3970. }
  3971. /**
  3972. * Returns the angle between this quaternion and the given one in radians.
  3973. *
  3974. * @param {Quaternion} q - The quaternion to compute the angle with.
  3975. * @return {number} The angle in radians.
  3976. */
  3977. angleTo( q ) {
  3978. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3979. }
  3980. /**
  3981. * Rotates this quaternion by a given angular step to the given quaternion.
  3982. * The method ensures that the final quaternion will not overshoot `q`.
  3983. *
  3984. * @param {Quaternion} q - The target quaternion.
  3985. * @param {number} step - The angular step in radians.
  3986. * @return {Quaternion} A reference to this quaternion.
  3987. */
  3988. rotateTowards( q, step ) {
  3989. const angle = this.angleTo( q );
  3990. if ( angle === 0 ) return this;
  3991. const t = Math.min( 1, step / angle );
  3992. this.slerp( q, t );
  3993. return this;
  3994. }
  3995. /**
  3996. * Sets this quaternion to the identity quaternion; that is, to the
  3997. * quaternion that represents "no rotation".
  3998. *
  3999. * @return {Quaternion} A reference to this quaternion.
  4000. */
  4001. identity() {
  4002. return this.set( 0, 0, 0, 1 );
  4003. }
  4004. /**
  4005. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  4006. * quaternion is assumed to have unit length.
  4007. *
  4008. * @return {Quaternion} A reference to this quaternion.
  4009. */
  4010. invert() {
  4011. return this.conjugate();
  4012. }
  4013. /**
  4014. * Returns the rotational conjugate of this quaternion. The conjugate of a
  4015. * quaternion represents the same rotation in the opposite direction about
  4016. * the rotational axis.
  4017. *
  4018. * @return {Quaternion} A reference to this quaternion.
  4019. */
  4020. conjugate() {
  4021. this._x *= -1;
  4022. this._y *= -1;
  4023. this._z *= -1;
  4024. this._onChangeCallback();
  4025. return this;
  4026. }
  4027. /**
  4028. * Calculates the dot product of this quaternion and the given one.
  4029. *
  4030. * @param {Quaternion} v - The quaternion to compute the dot product with.
  4031. * @return {number} The result of the dot product.
  4032. */
  4033. dot( v ) {
  4034. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  4035. }
  4036. /**
  4037. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  4038. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  4039. * lengths of two quaternions, as this is a slightly more efficient calculation than
  4040. * {@link Quaternion#length}.
  4041. *
  4042. * @return {number} The squared Euclidean length.
  4043. */
  4044. lengthSq() {
  4045. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  4046. }
  4047. /**
  4048. * Computes the Euclidean length (straight-line length) of this quaternion,
  4049. * considered as a 4 dimensional vector.
  4050. *
  4051. * @return {number} The Euclidean length.
  4052. */
  4053. length() {
  4054. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  4055. }
  4056. /**
  4057. * Normalizes this quaternion - that is, calculated the quaternion that performs
  4058. * the same rotation as this one, but has a length equal to `1`.
  4059. *
  4060. * @return {Quaternion} A reference to this quaternion.
  4061. */
  4062. normalize() {
  4063. let l = this.length();
  4064. if ( l === 0 ) {
  4065. this._x = 0;
  4066. this._y = 0;
  4067. this._z = 0;
  4068. this._w = 1;
  4069. } else {
  4070. l = 1 / l;
  4071. this._x = this._x * l;
  4072. this._y = this._y * l;
  4073. this._z = this._z * l;
  4074. this._w = this._w * l;
  4075. }
  4076. this._onChangeCallback();
  4077. return this;
  4078. }
  4079. /**
  4080. * Multiplies this quaternion by the given one.
  4081. *
  4082. * @param {Quaternion} q - The quaternion.
  4083. * @return {Quaternion} A reference to this quaternion.
  4084. */
  4085. multiply( q ) {
  4086. return this.multiplyQuaternions( this, q );
  4087. }
  4088. /**
  4089. * Pre-multiplies this quaternion by the given one.
  4090. *
  4091. * @param {Quaternion} q - The quaternion.
  4092. * @return {Quaternion} A reference to this quaternion.
  4093. */
  4094. premultiply( q ) {
  4095. return this.multiplyQuaternions( q, this );
  4096. }
  4097. /**
  4098. * Multiplies the given quaternions and stores the result in this instance.
  4099. *
  4100. * @param {Quaternion} a - The first quaternion.
  4101. * @param {Quaternion} b - The second quaternion.
  4102. * @return {Quaternion} A reference to this quaternion.
  4103. */
  4104. multiplyQuaternions( a, b ) {
  4105. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  4106. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  4107. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  4108. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  4109. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  4110. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  4111. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  4112. this._onChangeCallback();
  4113. return this;
  4114. }
  4115. /**
  4116. * Performs a spherical linear interpolation between quaternions.
  4117. *
  4118. * @param {Quaternion} qb - The target quaternion.
  4119. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4120. * @return {Quaternion} A reference to this quaternion.
  4121. */
  4122. slerp( qb, t ) {
  4123. if ( t === 0 ) return this;
  4124. if ( t === 1 ) return this.copy( qb );
  4125. const x = this._x, y = this._y, z = this._z, w = this._w;
  4126. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  4127. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  4128. if ( cosHalfTheta < 0 ) {
  4129. this._w = - qb._w;
  4130. this._x = - qb._x;
  4131. this._y = - qb._y;
  4132. this._z = - qb._z;
  4133. cosHalfTheta = - cosHalfTheta;
  4134. } else {
  4135. this.copy( qb );
  4136. }
  4137. if ( cosHalfTheta >= 1.0 ) {
  4138. this._w = w;
  4139. this._x = x;
  4140. this._y = y;
  4141. this._z = z;
  4142. return this;
  4143. }
  4144. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  4145. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  4146. const s = 1 - t;
  4147. this._w = s * w + t * this._w;
  4148. this._x = s * x + t * this._x;
  4149. this._y = s * y + t * this._y;
  4150. this._z = s * z + t * this._z;
  4151. this.normalize(); // normalize calls _onChangeCallback()
  4152. return this;
  4153. }
  4154. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  4155. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  4156. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  4157. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  4158. this._w = ( w * ratioA + this._w * ratioB );
  4159. this._x = ( x * ratioA + this._x * ratioB );
  4160. this._y = ( y * ratioA + this._y * ratioB );
  4161. this._z = ( z * ratioA + this._z * ratioB );
  4162. this._onChangeCallback();
  4163. return this;
  4164. }
  4165. /**
  4166. * Performs a spherical linear interpolation between the given quaternions
  4167. * and stores the result in this quaternion.
  4168. *
  4169. * @param {Quaternion} qa - The source quaternion.
  4170. * @param {Quaternion} qb - The target quaternion.
  4171. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  4172. * @return {Quaternion} A reference to this quaternion.
  4173. */
  4174. slerpQuaternions( qa, qb, t ) {
  4175. return this.copy( qa ).slerp( qb, t );
  4176. }
  4177. /**
  4178. * Sets this quaternion to a uniformly random, normalized quaternion.
  4179. *
  4180. * @return {Quaternion} A reference to this quaternion.
  4181. */
  4182. random() {
  4183. // Ken Shoemake
  4184. // Uniform random rotations
  4185. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  4186. const theta1 = 2 * Math.PI * Math.random();
  4187. const theta2 = 2 * Math.PI * Math.random();
  4188. const x0 = Math.random();
  4189. const r1 = Math.sqrt( 1 - x0 );
  4190. const r2 = Math.sqrt( x0 );
  4191. return this.set(
  4192. r1 * Math.sin( theta1 ),
  4193. r1 * Math.cos( theta1 ),
  4194. r2 * Math.sin( theta2 ),
  4195. r2 * Math.cos( theta2 ),
  4196. );
  4197. }
  4198. /**
  4199. * Returns `true` if this quaternion is equal with the given one.
  4200. *
  4201. * @param {Quaternion} quaternion - The quaternion to test for equality.
  4202. * @return {boolean} Whether this quaternion is equal with the given one.
  4203. */
  4204. equals( quaternion ) {
  4205. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  4206. }
  4207. /**
  4208. * Sets this quaternion's components from the given array.
  4209. *
  4210. * @param {Array<number>} array - An array holding the quaternion component values.
  4211. * @param {number} [offset=0] - The offset into the array.
  4212. * @return {Quaternion} A reference to this quaternion.
  4213. */
  4214. fromArray( array, offset = 0 ) {
  4215. this._x = array[ offset ];
  4216. this._y = array[ offset + 1 ];
  4217. this._z = array[ offset + 2 ];
  4218. this._w = array[ offset + 3 ];
  4219. this._onChangeCallback();
  4220. return this;
  4221. }
  4222. /**
  4223. * Writes the components of this quaternion to the given array. If no array is provided,
  4224. * the method returns a new instance.
  4225. *
  4226. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  4227. * @param {number} [offset=0] - Index of the first element in the array.
  4228. * @return {Array<number>} The quaternion components.
  4229. */
  4230. toArray( array = [], offset = 0 ) {
  4231. array[ offset ] = this._x;
  4232. array[ offset + 1 ] = this._y;
  4233. array[ offset + 2 ] = this._z;
  4234. array[ offset + 3 ] = this._w;
  4235. return array;
  4236. }
  4237. /**
  4238. * Sets the components of this quaternion from the given buffer attribute.
  4239. *
  4240. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  4241. * @param {number} index - The index into the attribute.
  4242. * @return {Quaternion} A reference to this quaternion.
  4243. */
  4244. fromBufferAttribute( attribute, index ) {
  4245. this._x = attribute.getX( index );
  4246. this._y = attribute.getY( index );
  4247. this._z = attribute.getZ( index );
  4248. this._w = attribute.getW( index );
  4249. this._onChangeCallback();
  4250. return this;
  4251. }
  4252. /**
  4253. * This methods defines the serialization result of this class. Returns the
  4254. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  4255. *
  4256. * @return {Array<number>} The serialized quaternion.
  4257. */
  4258. toJSON() {
  4259. return this.toArray();
  4260. }
  4261. _onChange( callback ) {
  4262. this._onChangeCallback = callback;
  4263. return this;
  4264. }
  4265. _onChangeCallback() {}
  4266. *[ Symbol.iterator ]() {
  4267. yield this._x;
  4268. yield this._y;
  4269. yield this._z;
  4270. yield this._w;
  4271. }
  4272. }
  4273. /**
  4274. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  4275. * (labeled x, y and z), which can be used to represent a number of things, such as:
  4276. *
  4277. * - A point in 3D space.
  4278. * - A direction and length in 3D space. In three.js the length will
  4279. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  4280. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  4281. * - Any arbitrary ordered triplet of numbers.
  4282. *
  4283. * There are other things a 3D vector can be used to represent, such as
  4284. * momentum vectors and so on, however these are the most
  4285. * common uses in three.js.
  4286. *
  4287. * Iterating through a vector instance will yield its components `(x, y, z)` in
  4288. * the corresponding order.
  4289. * ```js
  4290. * const a = new THREE.Vector3( 0, 1, 0 );
  4291. *
  4292. * //no arguments; will be initialised to (0, 0, 0)
  4293. * const b = new THREE.Vector3( );
  4294. *
  4295. * const d = a.distanceTo( b );
  4296. * ```
  4297. */
  4298. class Vector3 {
  4299. /**
  4300. * Constructs a new 3D vector.
  4301. *
  4302. * @param {number} [x=0] - The x value of this vector.
  4303. * @param {number} [y=0] - The y value of this vector.
  4304. * @param {number} [z=0] - The z value of this vector.
  4305. */
  4306. constructor( x = 0, y = 0, z = 0 ) {
  4307. /**
  4308. * This flag can be used for type testing.
  4309. *
  4310. * @type {boolean}
  4311. * @readonly
  4312. * @default true
  4313. */
  4314. Vector3.prototype.isVector3 = true;
  4315. /**
  4316. * The x value of this vector.
  4317. *
  4318. * @type {number}
  4319. */
  4320. this.x = x;
  4321. /**
  4322. * The y value of this vector.
  4323. *
  4324. * @type {number}
  4325. */
  4326. this.y = y;
  4327. /**
  4328. * The z value of this vector.
  4329. *
  4330. * @type {number}
  4331. */
  4332. this.z = z;
  4333. }
  4334. /**
  4335. * Sets the vector components.
  4336. *
  4337. * @param {number} x - The value of the x component.
  4338. * @param {number} y - The value of the y component.
  4339. * @param {number} z - The value of the z component.
  4340. * @return {Vector3} A reference to this vector.
  4341. */
  4342. set( x, y, z ) {
  4343. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  4344. this.x = x;
  4345. this.y = y;
  4346. this.z = z;
  4347. return this;
  4348. }
  4349. /**
  4350. * Sets the vector components to the same value.
  4351. *
  4352. * @param {number} scalar - The value to set for all vector components.
  4353. * @return {Vector3} A reference to this vector.
  4354. */
  4355. setScalar( scalar ) {
  4356. this.x = scalar;
  4357. this.y = scalar;
  4358. this.z = scalar;
  4359. return this;
  4360. }
  4361. /**
  4362. * Sets the vector's x component to the given value
  4363. *
  4364. * @param {number} x - The value to set.
  4365. * @return {Vector3} A reference to this vector.
  4366. */
  4367. setX( x ) {
  4368. this.x = x;
  4369. return this;
  4370. }
  4371. /**
  4372. * Sets the vector's y component to the given value
  4373. *
  4374. * @param {number} y - The value to set.
  4375. * @return {Vector3} A reference to this vector.
  4376. */
  4377. setY( y ) {
  4378. this.y = y;
  4379. return this;
  4380. }
  4381. /**
  4382. * Sets the vector's z component to the given value
  4383. *
  4384. * @param {number} z - The value to set.
  4385. * @return {Vector3} A reference to this vector.
  4386. */
  4387. setZ( z ) {
  4388. this.z = z;
  4389. return this;
  4390. }
  4391. /**
  4392. * Allows to set a vector component with an index.
  4393. *
  4394. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4395. * @param {number} value - The value to set.
  4396. * @return {Vector3} A reference to this vector.
  4397. */
  4398. setComponent( index, value ) {
  4399. switch ( index ) {
  4400. case 0: this.x = value; break;
  4401. case 1: this.y = value; break;
  4402. case 2: this.z = value; break;
  4403. default: throw new Error( 'index is out of range: ' + index );
  4404. }
  4405. return this;
  4406. }
  4407. /**
  4408. * Returns the value of the vector component which matches the given index.
  4409. *
  4410. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  4411. * @return {number} A vector component value.
  4412. */
  4413. getComponent( index ) {
  4414. switch ( index ) {
  4415. case 0: return this.x;
  4416. case 1: return this.y;
  4417. case 2: return this.z;
  4418. default: throw new Error( 'index is out of range: ' + index );
  4419. }
  4420. }
  4421. /**
  4422. * Returns a new vector with copied values from this instance.
  4423. *
  4424. * @return {Vector3} A clone of this instance.
  4425. */
  4426. clone() {
  4427. return new this.constructor( this.x, this.y, this.z );
  4428. }
  4429. /**
  4430. * Copies the values of the given vector to this instance.
  4431. *
  4432. * @param {Vector3} v - The vector to copy.
  4433. * @return {Vector3} A reference to this vector.
  4434. */
  4435. copy( v ) {
  4436. this.x = v.x;
  4437. this.y = v.y;
  4438. this.z = v.z;
  4439. return this;
  4440. }
  4441. /**
  4442. * Adds the given vector to this instance.
  4443. *
  4444. * @param {Vector3} v - The vector to add.
  4445. * @return {Vector3} A reference to this vector.
  4446. */
  4447. add( v ) {
  4448. this.x += v.x;
  4449. this.y += v.y;
  4450. this.z += v.z;
  4451. return this;
  4452. }
  4453. /**
  4454. * Adds the given scalar value to all components of this instance.
  4455. *
  4456. * @param {number} s - The scalar to add.
  4457. * @return {Vector3} A reference to this vector.
  4458. */
  4459. addScalar( s ) {
  4460. this.x += s;
  4461. this.y += s;
  4462. this.z += s;
  4463. return this;
  4464. }
  4465. /**
  4466. * Adds the given vectors and stores the result in this instance.
  4467. *
  4468. * @param {Vector3} a - The first vector.
  4469. * @param {Vector3} b - The second vector.
  4470. * @return {Vector3} A reference to this vector.
  4471. */
  4472. addVectors( a, b ) {
  4473. this.x = a.x + b.x;
  4474. this.y = a.y + b.y;
  4475. this.z = a.z + b.z;
  4476. return this;
  4477. }
  4478. /**
  4479. * Adds the given vector scaled by the given factor to this instance.
  4480. *
  4481. * @param {Vector3|Vector4} v - The vector.
  4482. * @param {number} s - The factor that scales `v`.
  4483. * @return {Vector3} A reference to this vector.
  4484. */
  4485. addScaledVector( v, s ) {
  4486. this.x += v.x * s;
  4487. this.y += v.y * s;
  4488. this.z += v.z * s;
  4489. return this;
  4490. }
  4491. /**
  4492. * Subtracts the given vector from this instance.
  4493. *
  4494. * @param {Vector3} v - The vector to subtract.
  4495. * @return {Vector3} A reference to this vector.
  4496. */
  4497. sub( v ) {
  4498. this.x -= v.x;
  4499. this.y -= v.y;
  4500. this.z -= v.z;
  4501. return this;
  4502. }
  4503. /**
  4504. * Subtracts the given scalar value from all components of this instance.
  4505. *
  4506. * @param {number} s - The scalar to subtract.
  4507. * @return {Vector3} A reference to this vector.
  4508. */
  4509. subScalar( s ) {
  4510. this.x -= s;
  4511. this.y -= s;
  4512. this.z -= s;
  4513. return this;
  4514. }
  4515. /**
  4516. * Subtracts the given vectors and stores the result in this instance.
  4517. *
  4518. * @param {Vector3} a - The first vector.
  4519. * @param {Vector3} b - The second vector.
  4520. * @return {Vector3} A reference to this vector.
  4521. */
  4522. subVectors( a, b ) {
  4523. this.x = a.x - b.x;
  4524. this.y = a.y - b.y;
  4525. this.z = a.z - b.z;
  4526. return this;
  4527. }
  4528. /**
  4529. * Multiplies the given vector with this instance.
  4530. *
  4531. * @param {Vector3} v - The vector to multiply.
  4532. * @return {Vector3} A reference to this vector.
  4533. */
  4534. multiply( v ) {
  4535. this.x *= v.x;
  4536. this.y *= v.y;
  4537. this.z *= v.z;
  4538. return this;
  4539. }
  4540. /**
  4541. * Multiplies the given scalar value with all components of this instance.
  4542. *
  4543. * @param {number} scalar - The scalar to multiply.
  4544. * @return {Vector3} A reference to this vector.
  4545. */
  4546. multiplyScalar( scalar ) {
  4547. this.x *= scalar;
  4548. this.y *= scalar;
  4549. this.z *= scalar;
  4550. return this;
  4551. }
  4552. /**
  4553. * Multiplies the given vectors and stores the result in this instance.
  4554. *
  4555. * @param {Vector3} a - The first vector.
  4556. * @param {Vector3} b - The second vector.
  4557. * @return {Vector3} A reference to this vector.
  4558. */
  4559. multiplyVectors( a, b ) {
  4560. this.x = a.x * b.x;
  4561. this.y = a.y * b.y;
  4562. this.z = a.z * b.z;
  4563. return this;
  4564. }
  4565. /**
  4566. * Applies the given Euler rotation to this vector.
  4567. *
  4568. * @param {Euler} euler - The Euler angles.
  4569. * @return {Vector3} A reference to this vector.
  4570. */
  4571. applyEuler( euler ) {
  4572. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  4573. }
  4574. /**
  4575. * Applies a rotation specified by an axis and an angle to this vector.
  4576. *
  4577. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4578. * @param {number} angle - The angle in radians.
  4579. * @return {Vector3} A reference to this vector.
  4580. */
  4581. applyAxisAngle( axis, angle ) {
  4582. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  4583. }
  4584. /**
  4585. * Multiplies this vector with the given 3x3 matrix.
  4586. *
  4587. * @param {Matrix3} m - The 3x3 matrix.
  4588. * @return {Vector3} A reference to this vector.
  4589. */
  4590. applyMatrix3( m ) {
  4591. const x = this.x, y = this.y, z = this.z;
  4592. const e = m.elements;
  4593. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4594. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4595. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4596. return this;
  4597. }
  4598. /**
  4599. * Multiplies this vector by the given normal matrix and normalizes
  4600. * the result.
  4601. *
  4602. * @param {Matrix3} m - The normal matrix.
  4603. * @return {Vector3} A reference to this vector.
  4604. */
  4605. applyNormalMatrix( m ) {
  4606. return this.applyMatrix3( m ).normalize();
  4607. }
  4608. /**
  4609. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4610. * divides by perspective.
  4611. *
  4612. * @param {Matrix4} m - The matrix to apply.
  4613. * @return {Vector3} A reference to this vector.
  4614. */
  4615. applyMatrix4( m ) {
  4616. const x = this.x, y = this.y, z = this.z;
  4617. const e = m.elements;
  4618. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4619. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4620. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4621. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4622. return this;
  4623. }
  4624. /**
  4625. * Applies the given Quaternion to this vector.
  4626. *
  4627. * @param {Quaternion} q - The Quaternion.
  4628. * @return {Vector3} A reference to this vector.
  4629. */
  4630. applyQuaternion( q ) {
  4631. // quaternion q is assumed to have unit length
  4632. const vx = this.x, vy = this.y, vz = this.z;
  4633. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4634. // t = 2 * cross( q.xyz, v );
  4635. const tx = 2 * ( qy * vz - qz * vy );
  4636. const ty = 2 * ( qz * vx - qx * vz );
  4637. const tz = 2 * ( qx * vy - qy * vx );
  4638. // v + q.w * t + cross( q.xyz, t );
  4639. this.x = vx + qw * tx + qy * tz - qz * ty;
  4640. this.y = vy + qw * ty + qz * tx - qx * tz;
  4641. this.z = vz + qw * tz + qx * ty - qy * tx;
  4642. return this;
  4643. }
  4644. /**
  4645. * Projects this vector from world space into the camera's normalized
  4646. * device coordinate (NDC) space.
  4647. *
  4648. * @param {Camera} camera - The camera.
  4649. * @return {Vector3} A reference to this vector.
  4650. */
  4651. project( camera ) {
  4652. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4653. }
  4654. /**
  4655. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4656. * space into world space.
  4657. *
  4658. * @param {Camera} camera - The camera.
  4659. * @return {Vector3} A reference to this vector.
  4660. */
  4661. unproject( camera ) {
  4662. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4663. }
  4664. /**
  4665. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4666. * subset of the given 4x4 matrix and then normalizes the result.
  4667. *
  4668. * @param {Matrix4} m - The matrix.
  4669. * @return {Vector3} A reference to this vector.
  4670. */
  4671. transformDirection( m ) {
  4672. // input: THREE.Matrix4 affine matrix
  4673. // vector interpreted as a direction
  4674. const x = this.x, y = this.y, z = this.z;
  4675. const e = m.elements;
  4676. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4677. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4678. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4679. return this.normalize();
  4680. }
  4681. /**
  4682. * Divides this instance by the given vector.
  4683. *
  4684. * @param {Vector3} v - The vector to divide.
  4685. * @return {Vector3} A reference to this vector.
  4686. */
  4687. divide( v ) {
  4688. this.x /= v.x;
  4689. this.y /= v.y;
  4690. this.z /= v.z;
  4691. return this;
  4692. }
  4693. /**
  4694. * Divides this vector by the given scalar.
  4695. *
  4696. * @param {number} scalar - The scalar to divide.
  4697. * @return {Vector3} A reference to this vector.
  4698. */
  4699. divideScalar( scalar ) {
  4700. return this.multiplyScalar( 1 / scalar );
  4701. }
  4702. /**
  4703. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4704. * value, replace that value with the corresponding min value.
  4705. *
  4706. * @param {Vector3} v - The vector.
  4707. * @return {Vector3} A reference to this vector.
  4708. */
  4709. min( v ) {
  4710. this.x = Math.min( this.x, v.x );
  4711. this.y = Math.min( this.y, v.y );
  4712. this.z = Math.min( this.z, v.z );
  4713. return this;
  4714. }
  4715. /**
  4716. * If this vector's x, y or z value is less than the given vector's x, y or z
  4717. * value, replace that value with the corresponding max value.
  4718. *
  4719. * @param {Vector3} v - The vector.
  4720. * @return {Vector3} A reference to this vector.
  4721. */
  4722. max( v ) {
  4723. this.x = Math.max( this.x, v.x );
  4724. this.y = Math.max( this.y, v.y );
  4725. this.z = Math.max( this.z, v.z );
  4726. return this;
  4727. }
  4728. /**
  4729. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4730. * value, it is replaced by the corresponding value.
  4731. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4732. * it is replaced by the corresponding value.
  4733. *
  4734. * @param {Vector3} min - The minimum x, y and z values.
  4735. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4736. * @return {Vector3} A reference to this vector.
  4737. */
  4738. clamp( min, max ) {
  4739. // assumes min < max, componentwise
  4740. this.x = clamp( this.x, min.x, max.x );
  4741. this.y = clamp( this.y, min.y, max.y );
  4742. this.z = clamp( this.z, min.z, max.z );
  4743. return this;
  4744. }
  4745. /**
  4746. * If this vector's x, y or z values are greater than the max value, they are
  4747. * replaced by the max value.
  4748. * If this vector's x, y or z values are less than the min value, they are
  4749. * replaced by the min value.
  4750. *
  4751. * @param {number} minVal - The minimum value the components will be clamped to.
  4752. * @param {number} maxVal - The maximum value the components will be clamped to.
  4753. * @return {Vector3} A reference to this vector.
  4754. */
  4755. clampScalar( minVal, maxVal ) {
  4756. this.x = clamp( this.x, minVal, maxVal );
  4757. this.y = clamp( this.y, minVal, maxVal );
  4758. this.z = clamp( this.z, minVal, maxVal );
  4759. return this;
  4760. }
  4761. /**
  4762. * If this vector's length is greater than the max value, it is replaced by
  4763. * the max value.
  4764. * If this vector's length is less than the min value, it is replaced by the
  4765. * min value.
  4766. *
  4767. * @param {number} min - The minimum value the vector length will be clamped to.
  4768. * @param {number} max - The maximum value the vector length will be clamped to.
  4769. * @return {Vector3} A reference to this vector.
  4770. */
  4771. clampLength( min, max ) {
  4772. const length = this.length();
  4773. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4774. }
  4775. /**
  4776. * The components of this vector are rounded down to the nearest integer value.
  4777. *
  4778. * @return {Vector3} A reference to this vector.
  4779. */
  4780. floor() {
  4781. this.x = Math.floor( this.x );
  4782. this.y = Math.floor( this.y );
  4783. this.z = Math.floor( this.z );
  4784. return this;
  4785. }
  4786. /**
  4787. * The components of this vector are rounded up to the nearest integer value.
  4788. *
  4789. * @return {Vector3} A reference to this vector.
  4790. */
  4791. ceil() {
  4792. this.x = Math.ceil( this.x );
  4793. this.y = Math.ceil( this.y );
  4794. this.z = Math.ceil( this.z );
  4795. return this;
  4796. }
  4797. /**
  4798. * The components of this vector are rounded to the nearest integer value
  4799. *
  4800. * @return {Vector3} A reference to this vector.
  4801. */
  4802. round() {
  4803. this.x = Math.round( this.x );
  4804. this.y = Math.round( this.y );
  4805. this.z = Math.round( this.z );
  4806. return this;
  4807. }
  4808. /**
  4809. * The components of this vector are rounded towards zero (up if negative,
  4810. * down if positive) to an integer value.
  4811. *
  4812. * @return {Vector3} A reference to this vector.
  4813. */
  4814. roundToZero() {
  4815. this.x = Math.trunc( this.x );
  4816. this.y = Math.trunc( this.y );
  4817. this.z = Math.trunc( this.z );
  4818. return this;
  4819. }
  4820. /**
  4821. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4822. *
  4823. * @return {Vector3} A reference to this vector.
  4824. */
  4825. negate() {
  4826. this.x = - this.x;
  4827. this.y = - this.y;
  4828. this.z = - this.z;
  4829. return this;
  4830. }
  4831. /**
  4832. * Calculates the dot product of the given vector with this instance.
  4833. *
  4834. * @param {Vector3} v - The vector to compute the dot product with.
  4835. * @return {number} The result of the dot product.
  4836. */
  4837. dot( v ) {
  4838. return this.x * v.x + this.y * v.y + this.z * v.z;
  4839. }
  4840. // TODO lengthSquared?
  4841. /**
  4842. * Computes the square of the Euclidean length (straight-line length) from
  4843. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4844. * compare the length squared instead as it is slightly more efficient to calculate.
  4845. *
  4846. * @return {number} The square length of this vector.
  4847. */
  4848. lengthSq() {
  4849. return this.x * this.x + this.y * this.y + this.z * this.z;
  4850. }
  4851. /**
  4852. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4853. *
  4854. * @return {number} The length of this vector.
  4855. */
  4856. length() {
  4857. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4858. }
  4859. /**
  4860. * Computes the Manhattan length of this vector.
  4861. *
  4862. * @return {number} The length of this vector.
  4863. */
  4864. manhattanLength() {
  4865. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4866. }
  4867. /**
  4868. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4869. * with the same direction as this one, but with a vector length of `1`.
  4870. *
  4871. * @return {Vector3} A reference to this vector.
  4872. */
  4873. normalize() {
  4874. return this.divideScalar( this.length() || 1 );
  4875. }
  4876. /**
  4877. * Sets this vector to a vector with the same direction as this one, but
  4878. * with the specified length.
  4879. *
  4880. * @param {number} length - The new length of this vector.
  4881. * @return {Vector3} A reference to this vector.
  4882. */
  4883. setLength( length ) {
  4884. return this.normalize().multiplyScalar( length );
  4885. }
  4886. /**
  4887. * Linearly interpolates between the given vector and this instance, where
  4888. * alpha is the percent distance along the line - alpha = 0 will be this
  4889. * vector, and alpha = 1 will be the given one.
  4890. *
  4891. * @param {Vector3} v - The vector to interpolate towards.
  4892. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4893. * @return {Vector3} A reference to this vector.
  4894. */
  4895. lerp( v, alpha ) {
  4896. this.x += ( v.x - this.x ) * alpha;
  4897. this.y += ( v.y - this.y ) * alpha;
  4898. this.z += ( v.z - this.z ) * alpha;
  4899. return this;
  4900. }
  4901. /**
  4902. * Linearly interpolates between the given vectors, where alpha is the percent
  4903. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4904. * be the second one. The result is stored in this instance.
  4905. *
  4906. * @param {Vector3} v1 - The first vector.
  4907. * @param {Vector3} v2 - The second vector.
  4908. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4909. * @return {Vector3} A reference to this vector.
  4910. */
  4911. lerpVectors( v1, v2, alpha ) {
  4912. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4913. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4914. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4915. return this;
  4916. }
  4917. /**
  4918. * Calculates the cross product of the given vector with this instance.
  4919. *
  4920. * @param {Vector3} v - The vector to compute the cross product with.
  4921. * @return {Vector3} The result of the cross product.
  4922. */
  4923. cross( v ) {
  4924. return this.crossVectors( this, v );
  4925. }
  4926. /**
  4927. * Calculates the cross product of the given vectors and stores the result
  4928. * in this instance.
  4929. *
  4930. * @param {Vector3} a - The first vector.
  4931. * @param {Vector3} b - The second vector.
  4932. * @return {Vector3} A reference to this vector.
  4933. */
  4934. crossVectors( a, b ) {
  4935. const ax = a.x, ay = a.y, az = a.z;
  4936. const bx = b.x, by = b.y, bz = b.z;
  4937. this.x = ay * bz - az * by;
  4938. this.y = az * bx - ax * bz;
  4939. this.z = ax * by - ay * bx;
  4940. return this;
  4941. }
  4942. /**
  4943. * Projects this vector onto the given one.
  4944. *
  4945. * @param {Vector3} v - The vector to project to.
  4946. * @return {Vector3} A reference to this vector.
  4947. */
  4948. projectOnVector( v ) {
  4949. const denominator = v.lengthSq();
  4950. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4951. const scalar = v.dot( this ) / denominator;
  4952. return this.copy( v ).multiplyScalar( scalar );
  4953. }
  4954. /**
  4955. * Projects this vector onto a plane by subtracting this
  4956. * vector projected onto the plane's normal from this vector.
  4957. *
  4958. * @param {Vector3} planeNormal - The plane normal.
  4959. * @return {Vector3} A reference to this vector.
  4960. */
  4961. projectOnPlane( planeNormal ) {
  4962. _vector$c.copy( this ).projectOnVector( planeNormal );
  4963. return this.sub( _vector$c );
  4964. }
  4965. /**
  4966. * Reflects this vector off a plane orthogonal to the given normal vector.
  4967. *
  4968. * @param {Vector3} normal - The (normalized) normal vector.
  4969. * @return {Vector3} A reference to this vector.
  4970. */
  4971. reflect( normal ) {
  4972. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4973. }
  4974. /**
  4975. * Returns the angle between the given vector and this instance in radians.
  4976. *
  4977. * @param {Vector3} v - The vector to compute the angle with.
  4978. * @return {number} The angle in radians.
  4979. */
  4980. angleTo( v ) {
  4981. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4982. if ( denominator === 0 ) return Math.PI / 2;
  4983. const theta = this.dot( v ) / denominator;
  4984. // clamp, to handle numerical problems
  4985. return Math.acos( clamp( theta, -1, 1 ) );
  4986. }
  4987. /**
  4988. * Computes the distance from the given vector to this instance.
  4989. *
  4990. * @param {Vector3} v - The vector to compute the distance to.
  4991. * @return {number} The distance.
  4992. */
  4993. distanceTo( v ) {
  4994. return Math.sqrt( this.distanceToSquared( v ) );
  4995. }
  4996. /**
  4997. * Computes the squared distance from the given vector to this instance.
  4998. * If you are just comparing the distance with another distance, you should compare
  4999. * the distance squared instead as it is slightly more efficient to calculate.
  5000. *
  5001. * @param {Vector3} v - The vector to compute the squared distance to.
  5002. * @return {number} The squared distance.
  5003. */
  5004. distanceToSquared( v ) {
  5005. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  5006. return dx * dx + dy * dy + dz * dz;
  5007. }
  5008. /**
  5009. * Computes the Manhattan distance from the given vector to this instance.
  5010. *
  5011. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  5012. * @return {number} The Manhattan distance.
  5013. */
  5014. manhattanDistanceTo( v ) {
  5015. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  5016. }
  5017. /**
  5018. * Sets the vector components from the given spherical coordinates.
  5019. *
  5020. * @param {Spherical} s - The spherical coordinates.
  5021. * @return {Vector3} A reference to this vector.
  5022. */
  5023. setFromSpherical( s ) {
  5024. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  5025. }
  5026. /**
  5027. * Sets the vector components from the given spherical coordinates.
  5028. *
  5029. * @param {number} radius - The radius.
  5030. * @param {number} phi - The phi angle in radians.
  5031. * @param {number} theta - The theta angle in radians.
  5032. * @return {Vector3} A reference to this vector.
  5033. */
  5034. setFromSphericalCoords( radius, phi, theta ) {
  5035. const sinPhiRadius = Math.sin( phi ) * radius;
  5036. this.x = sinPhiRadius * Math.sin( theta );
  5037. this.y = Math.cos( phi ) * radius;
  5038. this.z = sinPhiRadius * Math.cos( theta );
  5039. return this;
  5040. }
  5041. /**
  5042. * Sets the vector components from the given cylindrical coordinates.
  5043. *
  5044. * @param {Cylindrical} c - The cylindrical coordinates.
  5045. * @return {Vector3} A reference to this vector.
  5046. */
  5047. setFromCylindrical( c ) {
  5048. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  5049. }
  5050. /**
  5051. * Sets the vector components from the given cylindrical coordinates.
  5052. *
  5053. * @param {number} radius - The radius.
  5054. * @param {number} theta - The theta angle in radians.
  5055. * @param {number} y - The y value.
  5056. * @return {Vector3} A reference to this vector.
  5057. */
  5058. setFromCylindricalCoords( radius, theta, y ) {
  5059. this.x = radius * Math.sin( theta );
  5060. this.y = y;
  5061. this.z = radius * Math.cos( theta );
  5062. return this;
  5063. }
  5064. /**
  5065. * Sets the vector components to the position elements of the
  5066. * given transformation matrix.
  5067. *
  5068. * @param {Matrix4} m - The 4x4 matrix.
  5069. * @return {Vector3} A reference to this vector.
  5070. */
  5071. setFromMatrixPosition( m ) {
  5072. const e = m.elements;
  5073. this.x = e[ 12 ];
  5074. this.y = e[ 13 ];
  5075. this.z = e[ 14 ];
  5076. return this;
  5077. }
  5078. /**
  5079. * Sets the vector components to the scale elements of the
  5080. * given transformation matrix.
  5081. *
  5082. * @param {Matrix4} m - The 4x4 matrix.
  5083. * @return {Vector3} A reference to this vector.
  5084. */
  5085. setFromMatrixScale( m ) {
  5086. const sx = this.setFromMatrixColumn( m, 0 ).length();
  5087. const sy = this.setFromMatrixColumn( m, 1 ).length();
  5088. const sz = this.setFromMatrixColumn( m, 2 ).length();
  5089. this.x = sx;
  5090. this.y = sy;
  5091. this.z = sz;
  5092. return this;
  5093. }
  5094. /**
  5095. * Sets the vector components from the specified matrix column.
  5096. *
  5097. * @param {Matrix4} m - The 4x4 matrix.
  5098. * @param {number} index - The column index.
  5099. * @return {Vector3} A reference to this vector.
  5100. */
  5101. setFromMatrixColumn( m, index ) {
  5102. return this.fromArray( m.elements, index * 4 );
  5103. }
  5104. /**
  5105. * Sets the vector components from the specified matrix column.
  5106. *
  5107. * @param {Matrix3} m - The 3x3 matrix.
  5108. * @param {number} index - The column index.
  5109. * @return {Vector3} A reference to this vector.
  5110. */
  5111. setFromMatrix3Column( m, index ) {
  5112. return this.fromArray( m.elements, index * 3 );
  5113. }
  5114. /**
  5115. * Sets the vector components from the given Euler angles.
  5116. *
  5117. * @param {Euler} e - The Euler angles to set.
  5118. * @return {Vector3} A reference to this vector.
  5119. */
  5120. setFromEuler( e ) {
  5121. this.x = e._x;
  5122. this.y = e._y;
  5123. this.z = e._z;
  5124. return this;
  5125. }
  5126. /**
  5127. * Sets the vector components from the RGB components of the
  5128. * given color.
  5129. *
  5130. * @param {Color} c - The color to set.
  5131. * @return {Vector3} A reference to this vector.
  5132. */
  5133. setFromColor( c ) {
  5134. this.x = c.r;
  5135. this.y = c.g;
  5136. this.z = c.b;
  5137. return this;
  5138. }
  5139. /**
  5140. * Returns `true` if this vector is equal with the given one.
  5141. *
  5142. * @param {Vector3} v - The vector to test for equality.
  5143. * @return {boolean} Whether this vector is equal with the given one.
  5144. */
  5145. equals( v ) {
  5146. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  5147. }
  5148. /**
  5149. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  5150. * and z value to be `array[ offset + 2 ]`.
  5151. *
  5152. * @param {Array<number>} array - An array holding the vector component values.
  5153. * @param {number} [offset=0] - The offset into the array.
  5154. * @return {Vector3} A reference to this vector.
  5155. */
  5156. fromArray( array, offset = 0 ) {
  5157. this.x = array[ offset ];
  5158. this.y = array[ offset + 1 ];
  5159. this.z = array[ offset + 2 ];
  5160. return this;
  5161. }
  5162. /**
  5163. * Writes the components of this vector to the given array. If no array is provided,
  5164. * the method returns a new instance.
  5165. *
  5166. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  5167. * @param {number} [offset=0] - Index of the first element in the array.
  5168. * @return {Array<number>} The vector components.
  5169. */
  5170. toArray( array = [], offset = 0 ) {
  5171. array[ offset ] = this.x;
  5172. array[ offset + 1 ] = this.y;
  5173. array[ offset + 2 ] = this.z;
  5174. return array;
  5175. }
  5176. /**
  5177. * Sets the components of this vector from the given buffer attribute.
  5178. *
  5179. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  5180. * @param {number} index - The index into the attribute.
  5181. * @return {Vector3} A reference to this vector.
  5182. */
  5183. fromBufferAttribute( attribute, index ) {
  5184. this.x = attribute.getX( index );
  5185. this.y = attribute.getY( index );
  5186. this.z = attribute.getZ( index );
  5187. return this;
  5188. }
  5189. /**
  5190. * Sets each component of this vector to a pseudo-random value between `0` and
  5191. * `1`, excluding `1`.
  5192. *
  5193. * @return {Vector3} A reference to this vector.
  5194. */
  5195. random() {
  5196. this.x = Math.random();
  5197. this.y = Math.random();
  5198. this.z = Math.random();
  5199. return this;
  5200. }
  5201. /**
  5202. * Sets this vector to a uniformly random point on a unit sphere.
  5203. *
  5204. * @return {Vector3} A reference to this vector.
  5205. */
  5206. randomDirection() {
  5207. // https://mathworld.wolfram.com/SpherePointPicking.html
  5208. const theta = Math.random() * Math.PI * 2;
  5209. const u = Math.random() * 2 - 1;
  5210. const c = Math.sqrt( 1 - u * u );
  5211. this.x = c * Math.cos( theta );
  5212. this.y = u;
  5213. this.z = c * Math.sin( theta );
  5214. return this;
  5215. }
  5216. *[ Symbol.iterator ]() {
  5217. yield this.x;
  5218. yield this.y;
  5219. yield this.z;
  5220. }
  5221. }
  5222. const _vector$c = /*@__PURE__*/ new Vector3();
  5223. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  5224. /**
  5225. * Represents an axis-aligned bounding box (AABB) in 3D space.
  5226. */
  5227. class Box3 {
  5228. /**
  5229. * Constructs a new bounding box.
  5230. *
  5231. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  5232. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  5233. */
  5234. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  5235. /**
  5236. * This flag can be used for type testing.
  5237. *
  5238. * @type {boolean}
  5239. * @readonly
  5240. * @default true
  5241. */
  5242. this.isBox3 = true;
  5243. /**
  5244. * The lower boundary of the box.
  5245. *
  5246. * @type {Vector3}
  5247. */
  5248. this.min = min;
  5249. /**
  5250. * The upper boundary of the box.
  5251. *
  5252. * @type {Vector3}
  5253. */
  5254. this.max = max;
  5255. }
  5256. /**
  5257. * Sets the lower and upper boundaries of this box.
  5258. * Please note that this method only copies the values from the given objects.
  5259. *
  5260. * @param {Vector3} min - The lower boundary of the box.
  5261. * @param {Vector3} max - The upper boundary of the box.
  5262. * @return {Box3} A reference to this bounding box.
  5263. */
  5264. set( min, max ) {
  5265. this.min.copy( min );
  5266. this.max.copy( max );
  5267. return this;
  5268. }
  5269. /**
  5270. * Sets the upper and lower bounds of this box so it encloses the position data
  5271. * in the given array.
  5272. *
  5273. * @param {Array<number>} array - An array holding 3D position data.
  5274. * @return {Box3} A reference to this bounding box.
  5275. */
  5276. setFromArray( array ) {
  5277. this.makeEmpty();
  5278. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  5279. this.expandByPoint( _vector$b.fromArray( array, i ) );
  5280. }
  5281. return this;
  5282. }
  5283. /**
  5284. * Sets the upper and lower bounds of this box so it encloses the position data
  5285. * in the given buffer attribute.
  5286. *
  5287. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  5288. * @return {Box3} A reference to this bounding box.
  5289. */
  5290. setFromBufferAttribute( attribute ) {
  5291. this.makeEmpty();
  5292. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  5293. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  5294. }
  5295. return this;
  5296. }
  5297. /**
  5298. * Sets the upper and lower bounds of this box so it encloses the position data
  5299. * in the given array.
  5300. *
  5301. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  5302. * @return {Box3} A reference to this bounding box.
  5303. */
  5304. setFromPoints( points ) {
  5305. this.makeEmpty();
  5306. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5307. this.expandByPoint( points[ i ] );
  5308. }
  5309. return this;
  5310. }
  5311. /**
  5312. * Centers this box on the given center vector and sets this box's width, height and
  5313. * depth to the given size values.
  5314. *
  5315. * @param {Vector3} center - The center of the box.
  5316. * @param {Vector3} size - The x, y and z dimensions of the box.
  5317. * @return {Box3} A reference to this bounding box.
  5318. */
  5319. setFromCenterAndSize( center, size ) {
  5320. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  5321. this.min.copy( center ).sub( halfSize );
  5322. this.max.copy( center ).add( halfSize );
  5323. return this;
  5324. }
  5325. /**
  5326. * Computes the world-axis-aligned bounding box for the given 3D object
  5327. * (including its children), accounting for the object's, and children's,
  5328. * world transforms. The function may result in a larger box than strictly necessary.
  5329. *
  5330. * @param {Object3D} object - The 3D object to compute the bounding box for.
  5331. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  5332. * world-axis-aligned bounding box at the expense of more computation.
  5333. * @return {Box3} A reference to this bounding box.
  5334. */
  5335. setFromObject( object, precise = false ) {
  5336. this.makeEmpty();
  5337. return this.expandByObject( object, precise );
  5338. }
  5339. /**
  5340. * Returns a new box with copied values from this instance.
  5341. *
  5342. * @return {Box3} A clone of this instance.
  5343. */
  5344. clone() {
  5345. return new this.constructor().copy( this );
  5346. }
  5347. /**
  5348. * Copies the values of the given box to this instance.
  5349. *
  5350. * @param {Box3} box - The box to copy.
  5351. * @return {Box3} A reference to this bounding box.
  5352. */
  5353. copy( box ) {
  5354. this.min.copy( box.min );
  5355. this.max.copy( box.max );
  5356. return this;
  5357. }
  5358. /**
  5359. * Makes this box empty which means in encloses a zero space in 3D.
  5360. *
  5361. * @return {Box3} A reference to this bounding box.
  5362. */
  5363. makeEmpty() {
  5364. this.min.x = this.min.y = this.min.z = + Infinity;
  5365. this.max.x = this.max.y = this.max.z = - Infinity;
  5366. return this;
  5367. }
  5368. /**
  5369. * Returns true if this box includes zero points within its bounds.
  5370. * Note that a box with equal lower and upper bounds still includes one
  5371. * point, the one both bounds share.
  5372. *
  5373. * @return {boolean} Whether this box is empty or not.
  5374. */
  5375. isEmpty() {
  5376. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5377. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  5378. }
  5379. /**
  5380. * Returns the center point of this box.
  5381. *
  5382. * @param {Vector3} target - The target vector that is used to store the method's result.
  5383. * @return {Vector3} The center point.
  5384. */
  5385. getCenter( target ) {
  5386. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  5387. }
  5388. /**
  5389. * Returns the dimensions of this box.
  5390. *
  5391. * @param {Vector3} target - The target vector that is used to store the method's result.
  5392. * @return {Vector3} The size.
  5393. */
  5394. getSize( target ) {
  5395. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  5396. }
  5397. /**
  5398. * Expands the boundaries of this box to include the given point.
  5399. *
  5400. * @param {Vector3} point - The point that should be included by the bounding box.
  5401. * @return {Box3} A reference to this bounding box.
  5402. */
  5403. expandByPoint( point ) {
  5404. this.min.min( point );
  5405. this.max.max( point );
  5406. return this;
  5407. }
  5408. /**
  5409. * Expands this box equilaterally by the given vector. The width of this
  5410. * box will be expanded by the x component of the vector in both
  5411. * directions. The height of this box will be expanded by the y component of
  5412. * the vector in both directions. The depth of this box will be
  5413. * expanded by the z component of the vector in both directions.
  5414. *
  5415. * @param {Vector3} vector - The vector that should expand the bounding box.
  5416. * @return {Box3} A reference to this bounding box.
  5417. */
  5418. expandByVector( vector ) {
  5419. this.min.sub( vector );
  5420. this.max.add( vector );
  5421. return this;
  5422. }
  5423. /**
  5424. * Expands each dimension of the box by the given scalar. If negative, the
  5425. * dimensions of the box will be contracted.
  5426. *
  5427. * @param {number} scalar - The scalar value that should expand the bounding box.
  5428. * @return {Box3} A reference to this bounding box.
  5429. */
  5430. expandByScalar( scalar ) {
  5431. this.min.addScalar( - scalar );
  5432. this.max.addScalar( scalar );
  5433. return this;
  5434. }
  5435. /**
  5436. * Expands the boundaries of this box to include the given 3D object and
  5437. * its children, accounting for the object's, and children's, world
  5438. * transforms. The function may result in a larger box than strictly
  5439. * necessary (unless the precise parameter is set to true).
  5440. *
  5441. * @param {Object3D} object - The 3D object that should expand the bounding box.
  5442. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  5443. * as little as necessary at the expense of more computation.
  5444. * @return {Box3} A reference to this bounding box.
  5445. */
  5446. expandByObject( object, precise = false ) {
  5447. // Computes the world-axis-aligned bounding box of an object (including its children),
  5448. // accounting for both the object's, and children's, world transforms
  5449. object.updateWorldMatrix( false, false );
  5450. const geometry = object.geometry;
  5451. if ( geometry !== undefined ) {
  5452. const positionAttribute = geometry.getAttribute( 'position' );
  5453. // precise AABB computation based on vertex data requires at least a position attribute.
  5454. // instancing isn't supported so far and uses the normal (conservative) code path.
  5455. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  5456. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  5457. if ( object.isMesh === true ) {
  5458. object.getVertexPosition( i, _vector$b );
  5459. } else {
  5460. _vector$b.fromBufferAttribute( positionAttribute, i );
  5461. }
  5462. _vector$b.applyMatrix4( object.matrixWorld );
  5463. this.expandByPoint( _vector$b );
  5464. }
  5465. } else {
  5466. if ( object.boundingBox !== undefined ) {
  5467. // object-level bounding box
  5468. if ( object.boundingBox === null ) {
  5469. object.computeBoundingBox();
  5470. }
  5471. _box$4.copy( object.boundingBox );
  5472. } else {
  5473. // geometry-level bounding box
  5474. if ( geometry.boundingBox === null ) {
  5475. geometry.computeBoundingBox();
  5476. }
  5477. _box$4.copy( geometry.boundingBox );
  5478. }
  5479. _box$4.applyMatrix4( object.matrixWorld );
  5480. this.union( _box$4 );
  5481. }
  5482. }
  5483. const children = object.children;
  5484. for ( let i = 0, l = children.length; i < l; i ++ ) {
  5485. this.expandByObject( children[ i ], precise );
  5486. }
  5487. return this;
  5488. }
  5489. /**
  5490. * Returns `true` if the given point lies within or on the boundaries of this box.
  5491. *
  5492. * @param {Vector3} point - The point to test.
  5493. * @return {boolean} Whether the bounding box contains the given point or not.
  5494. */
  5495. containsPoint( point ) {
  5496. return point.x >= this.min.x && point.x <= this.max.x &&
  5497. point.y >= this.min.y && point.y <= this.max.y &&
  5498. point.z >= this.min.z && point.z <= this.max.z;
  5499. }
  5500. /**
  5501. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  5502. * If this box and the given one are identical, this function also returns `true`.
  5503. *
  5504. * @param {Box3} box - The bounding box to test.
  5505. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  5506. */
  5507. containsBox( box ) {
  5508. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  5509. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  5510. this.min.z <= box.min.z && box.max.z <= this.max.z;
  5511. }
  5512. /**
  5513. * Returns a point as a proportion of this box's width, height and depth.
  5514. *
  5515. * @param {Vector3} point - A point in 3D space.
  5516. * @param {Vector3} target - The target vector that is used to store the method's result.
  5517. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  5518. */
  5519. getParameter( point, target ) {
  5520. // This can potentially have a divide by zero if the box
  5521. // has a size dimension of 0.
  5522. return target.set(
  5523. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  5524. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  5525. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  5526. );
  5527. }
  5528. /**
  5529. * Returns `true` if the given bounding box intersects with this bounding box.
  5530. *
  5531. * @param {Box3} box - The bounding box to test.
  5532. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  5533. */
  5534. intersectsBox( box ) {
  5535. // using 6 splitting planes to rule out intersections.
  5536. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  5537. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  5538. box.max.z >= this.min.z && box.min.z <= this.max.z;
  5539. }
  5540. /**
  5541. * Returns `true` if the given bounding sphere intersects with this bounding box.
  5542. *
  5543. * @param {Sphere} sphere - The bounding sphere to test.
  5544. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  5545. */
  5546. intersectsSphere( sphere ) {
  5547. // Find the point on the AABB closest to the sphere center.
  5548. this.clampPoint( sphere.center, _vector$b );
  5549. // If that point is inside the sphere, the AABB and sphere intersect.
  5550. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  5551. }
  5552. /**
  5553. * Returns `true` if the given plane intersects with this bounding box.
  5554. *
  5555. * @param {Plane} plane - The plane to test.
  5556. * @return {boolean} Whether the given plane intersects with this bounding box.
  5557. */
  5558. intersectsPlane( plane ) {
  5559. // We compute the minimum and maximum dot product values. If those values
  5560. // are on the same side (back or front) of the plane, then there is no intersection.
  5561. let min, max;
  5562. if ( plane.normal.x > 0 ) {
  5563. min = plane.normal.x * this.min.x;
  5564. max = plane.normal.x * this.max.x;
  5565. } else {
  5566. min = plane.normal.x * this.max.x;
  5567. max = plane.normal.x * this.min.x;
  5568. }
  5569. if ( plane.normal.y > 0 ) {
  5570. min += plane.normal.y * this.min.y;
  5571. max += plane.normal.y * this.max.y;
  5572. } else {
  5573. min += plane.normal.y * this.max.y;
  5574. max += plane.normal.y * this.min.y;
  5575. }
  5576. if ( plane.normal.z > 0 ) {
  5577. min += plane.normal.z * this.min.z;
  5578. max += plane.normal.z * this.max.z;
  5579. } else {
  5580. min += plane.normal.z * this.max.z;
  5581. max += plane.normal.z * this.min.z;
  5582. }
  5583. return ( min <= - plane.constant && max >= - plane.constant );
  5584. }
  5585. /**
  5586. * Returns `true` if the given triangle intersects with this bounding box.
  5587. *
  5588. * @param {Triangle} triangle - The triangle to test.
  5589. * @return {boolean} Whether the given triangle intersects with this bounding box.
  5590. */
  5591. intersectsTriangle( triangle ) {
  5592. if ( this.isEmpty() ) {
  5593. return false;
  5594. }
  5595. // compute box center and extents
  5596. this.getCenter( _center );
  5597. _extents.subVectors( this.max, _center );
  5598. // translate triangle to aabb origin
  5599. _v0$2.subVectors( triangle.a, _center );
  5600. _v1$7.subVectors( triangle.b, _center );
  5601. _v2$4.subVectors( triangle.c, _center );
  5602. // compute edge vectors for triangle
  5603. _f0.subVectors( _v1$7, _v0$2 );
  5604. _f1.subVectors( _v2$4, _v1$7 );
  5605. _f2.subVectors( _v0$2, _v2$4 );
  5606. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  5607. // 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
  5608. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  5609. let axes = [
  5610. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  5611. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  5612. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  5613. ];
  5614. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  5615. return false;
  5616. }
  5617. // test 3 face normals from the aabb
  5618. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  5619. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  5620. return false;
  5621. }
  5622. // finally testing the face normal of the triangle
  5623. // use already existing triangle edge vectors here
  5624. _triangleNormal.crossVectors( _f0, _f1 );
  5625. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  5626. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  5627. }
  5628. /**
  5629. * Clamps the given point within the bounds of this box.
  5630. *
  5631. * @param {Vector3} point - The point to clamp.
  5632. * @param {Vector3} target - The target vector that is used to store the method's result.
  5633. * @return {Vector3} The clamped point.
  5634. */
  5635. clampPoint( point, target ) {
  5636. return target.copy( point ).clamp( this.min, this.max );
  5637. }
  5638. /**
  5639. * Returns the euclidean distance from any edge of this box to the specified point. If
  5640. * the given point lies inside of this box, the distance will be `0`.
  5641. *
  5642. * @param {Vector3} point - The point to compute the distance to.
  5643. * @return {number} The euclidean distance.
  5644. */
  5645. distanceToPoint( point ) {
  5646. return this.clampPoint( point, _vector$b ).distanceTo( point );
  5647. }
  5648. /**
  5649. * Returns a bounding sphere that encloses this bounding box.
  5650. *
  5651. * @param {Sphere} target - The target sphere that is used to store the method's result.
  5652. * @return {Sphere} The bounding sphere that encloses this bounding box.
  5653. */
  5654. getBoundingSphere( target ) {
  5655. if ( this.isEmpty() ) {
  5656. target.makeEmpty();
  5657. } else {
  5658. this.getCenter( target.center );
  5659. target.radius = this.getSize( _vector$b ).length() * 0.5;
  5660. }
  5661. return target;
  5662. }
  5663. /**
  5664. * Computes the intersection of this bounding box and the given one, setting the upper
  5665. * bound of this box to the lesser of the two boxes' upper bounds and the
  5666. * lower bound of this box to the greater of the two boxes' lower bounds. If
  5667. * there's no overlap, makes this box empty.
  5668. *
  5669. * @param {Box3} box - The bounding box to intersect with.
  5670. * @return {Box3} A reference to this bounding box.
  5671. */
  5672. intersect( box ) {
  5673. this.min.max( box.min );
  5674. this.max.min( box.max );
  5675. // 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.
  5676. if ( this.isEmpty() ) this.makeEmpty();
  5677. return this;
  5678. }
  5679. /**
  5680. * Computes the union of this box and another and the given one, setting the upper
  5681. * bound of this box to the greater of the two boxes' upper bounds and the
  5682. * lower bound of this box to the lesser of the two boxes' lower bounds.
  5683. *
  5684. * @param {Box3} box - The bounding box that will be unioned with this instance.
  5685. * @return {Box3} A reference to this bounding box.
  5686. */
  5687. union( box ) {
  5688. this.min.min( box.min );
  5689. this.max.max( box.max );
  5690. return this;
  5691. }
  5692. /**
  5693. * Transforms this bounding box by the given 4x4 transformation matrix.
  5694. *
  5695. * @param {Matrix4} matrix - The transformation matrix.
  5696. * @return {Box3} A reference to this bounding box.
  5697. */
  5698. applyMatrix4( matrix ) {
  5699. // transform of empty box is an empty box.
  5700. if ( this.isEmpty() ) return this;
  5701. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  5702. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  5703. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  5704. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  5705. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  5706. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  5707. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  5708. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  5709. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  5710. this.setFromPoints( _points );
  5711. return this;
  5712. }
  5713. /**
  5714. * Adds the given offset to both the upper and lower bounds of this bounding box,
  5715. * effectively moving it in 3D space.
  5716. *
  5717. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  5718. * @return {Box3} A reference to this bounding box.
  5719. */
  5720. translate( offset ) {
  5721. this.min.add( offset );
  5722. this.max.add( offset );
  5723. return this;
  5724. }
  5725. /**
  5726. * Returns `true` if this bounding box is equal with the given one.
  5727. *
  5728. * @param {Box3} box - The box to test for equality.
  5729. * @return {boolean} Whether this bounding box is equal with the given one.
  5730. */
  5731. equals( box ) {
  5732. return box.min.equals( this.min ) && box.max.equals( this.max );
  5733. }
  5734. }
  5735. const _points = [
  5736. /*@__PURE__*/ new Vector3(),
  5737. /*@__PURE__*/ new Vector3(),
  5738. /*@__PURE__*/ new Vector3(),
  5739. /*@__PURE__*/ new Vector3(),
  5740. /*@__PURE__*/ new Vector3(),
  5741. /*@__PURE__*/ new Vector3(),
  5742. /*@__PURE__*/ new Vector3(),
  5743. /*@__PURE__*/ new Vector3()
  5744. ];
  5745. const _vector$b = /*@__PURE__*/ new Vector3();
  5746. const _box$4 = /*@__PURE__*/ new Box3();
  5747. // triangle centered vertices
  5748. const _v0$2 = /*@__PURE__*/ new Vector3();
  5749. const _v1$7 = /*@__PURE__*/ new Vector3();
  5750. const _v2$4 = /*@__PURE__*/ new Vector3();
  5751. // triangle edge vectors
  5752. const _f0 = /*@__PURE__*/ new Vector3();
  5753. const _f1 = /*@__PURE__*/ new Vector3();
  5754. const _f2 = /*@__PURE__*/ new Vector3();
  5755. const _center = /*@__PURE__*/ new Vector3();
  5756. const _extents = /*@__PURE__*/ new Vector3();
  5757. const _triangleNormal = /*@__PURE__*/ new Vector3();
  5758. const _testAxis = /*@__PURE__*/ new Vector3();
  5759. function satForAxes( axes, v0, v1, v2, extents ) {
  5760. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  5761. _testAxis.fromArray( axes, i );
  5762. // project the aabb onto the separating axis
  5763. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  5764. // project all 3 vertices of the triangle onto the separating axis
  5765. const p0 = v0.dot( _testAxis );
  5766. const p1 = v1.dot( _testAxis );
  5767. const p2 = v2.dot( _testAxis );
  5768. // actual test, basically see if either of the most extreme of the triangle points intersects r
  5769. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  5770. // points of the projected triangle are outside the projected half-length of the aabb
  5771. // the axis is separating and we can exit
  5772. return false;
  5773. }
  5774. }
  5775. return true;
  5776. }
  5777. const _box$3 = /*@__PURE__*/ new Box3();
  5778. const _v1$6 = /*@__PURE__*/ new Vector3();
  5779. const _v2$3 = /*@__PURE__*/ new Vector3();
  5780. /**
  5781. * An analytical 3D sphere defined by a center and radius. This class is mainly
  5782. * used as a Bounding Sphere for 3D objects.
  5783. */
  5784. class Sphere {
  5785. /**
  5786. * Constructs a new sphere.
  5787. *
  5788. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  5789. * @param {number} [radius=-1] - The radius of the sphere.
  5790. */
  5791. constructor( center = new Vector3(), radius = -1 ) {
  5792. /**
  5793. * This flag can be used for type testing.
  5794. *
  5795. * @type {boolean}
  5796. * @readonly
  5797. * @default true
  5798. */
  5799. this.isSphere = true;
  5800. /**
  5801. * The center of the sphere
  5802. *
  5803. * @type {Vector3}
  5804. */
  5805. this.center = center;
  5806. /**
  5807. * The radius of the sphere.
  5808. *
  5809. * @type {number}
  5810. */
  5811. this.radius = radius;
  5812. }
  5813. /**
  5814. * Sets the sphere's components by copying the given values.
  5815. *
  5816. * @param {Vector3} center - The center.
  5817. * @param {number} radius - The radius.
  5818. * @return {Sphere} A reference to this sphere.
  5819. */
  5820. set( center, radius ) {
  5821. this.center.copy( center );
  5822. this.radius = radius;
  5823. return this;
  5824. }
  5825. /**
  5826. * Computes the minimum bounding sphere for list of points.
  5827. * If the optional center point is given, it is used as the sphere's
  5828. * center. Otherwise, the center of the axis-aligned bounding box
  5829. * encompassing the points is calculated.
  5830. *
  5831. * @param {Array<Vector3>} points - A list of points in 3D space.
  5832. * @param {Vector3} [optionalCenter] - The center of the sphere.
  5833. * @return {Sphere} A reference to this sphere.
  5834. */
  5835. setFromPoints( points, optionalCenter ) {
  5836. const center = this.center;
  5837. if ( optionalCenter !== undefined ) {
  5838. center.copy( optionalCenter );
  5839. } else {
  5840. _box$3.setFromPoints( points ).getCenter( center );
  5841. }
  5842. let maxRadiusSq = 0;
  5843. for ( let i = 0, il = points.length; i < il; i ++ ) {
  5844. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  5845. }
  5846. this.radius = Math.sqrt( maxRadiusSq );
  5847. return this;
  5848. }
  5849. /**
  5850. * Copies the values of the given sphere to this instance.
  5851. *
  5852. * @param {Sphere} sphere - The sphere to copy.
  5853. * @return {Sphere} A reference to this sphere.
  5854. */
  5855. copy( sphere ) {
  5856. this.center.copy( sphere.center );
  5857. this.radius = sphere.radius;
  5858. return this;
  5859. }
  5860. /**
  5861. * Returns `true` if the sphere is empty (the radius set to a negative number).
  5862. *
  5863. * Spheres with a radius of `0` contain only their center point and are not
  5864. * considered to be empty.
  5865. *
  5866. * @return {boolean} Whether this sphere is empty or not.
  5867. */
  5868. isEmpty() {
  5869. return ( this.radius < 0 );
  5870. }
  5871. /**
  5872. * Makes this sphere empty which means in encloses a zero space in 3D.
  5873. *
  5874. * @return {Sphere} A reference to this sphere.
  5875. */
  5876. makeEmpty() {
  5877. this.center.set( 0, 0, 0 );
  5878. this.radius = -1;
  5879. return this;
  5880. }
  5881. /**
  5882. * Returns `true` if this sphere contains the given point inclusive of
  5883. * the surface of the sphere.
  5884. *
  5885. * @param {Vector3} point - The point to check.
  5886. * @return {boolean} Whether this sphere contains the given point or not.
  5887. */
  5888. containsPoint( point ) {
  5889. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  5890. }
  5891. /**
  5892. * Returns the closest distance from the boundary of the sphere to the
  5893. * given point. If the sphere contains the point, the distance will
  5894. * be negative.
  5895. *
  5896. * @param {Vector3} point - The point to compute the distance to.
  5897. * @return {number} The distance to the point.
  5898. */
  5899. distanceToPoint( point ) {
  5900. return ( point.distanceTo( this.center ) - this.radius );
  5901. }
  5902. /**
  5903. * Returns `true` if this sphere intersects with the given one.
  5904. *
  5905. * @param {Sphere} sphere - The sphere to test.
  5906. * @return {boolean} Whether this sphere intersects with the given one or not.
  5907. */
  5908. intersectsSphere( sphere ) {
  5909. const radiusSum = this.radius + sphere.radius;
  5910. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  5911. }
  5912. /**
  5913. * Returns `true` if this sphere intersects with the given box.
  5914. *
  5915. * @param {Box3} box - The box to test.
  5916. * @return {boolean} Whether this sphere intersects with the given box or not.
  5917. */
  5918. intersectsBox( box ) {
  5919. return box.intersectsSphere( this );
  5920. }
  5921. /**
  5922. * Returns `true` if this sphere intersects with the given plane.
  5923. *
  5924. * @param {Plane} plane - The plane to test.
  5925. * @return {boolean} Whether this sphere intersects with the given plane or not.
  5926. */
  5927. intersectsPlane( plane ) {
  5928. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  5929. }
  5930. /**
  5931. * Clamps a point within the sphere. If the point is outside the sphere, it
  5932. * will clamp it to the closest point on the edge of the sphere. Points
  5933. * already inside the sphere will not be affected.
  5934. *
  5935. * @param {Vector3} point - The plane to clamp.
  5936. * @param {Vector3} target - The target vector that is used to store the method's result.
  5937. * @return {Vector3} The clamped point.
  5938. */
  5939. clampPoint( point, target ) {
  5940. const deltaLengthSq = this.center.distanceToSquared( point );
  5941. target.copy( point );
  5942. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  5943. target.sub( this.center ).normalize();
  5944. target.multiplyScalar( this.radius ).add( this.center );
  5945. }
  5946. return target;
  5947. }
  5948. /**
  5949. * Returns a bounding box that encloses this sphere.
  5950. *
  5951. * @param {Box3} target - The target box that is used to store the method's result.
  5952. * @return {Box3} The bounding box that encloses this sphere.
  5953. */
  5954. getBoundingBox( target ) {
  5955. if ( this.isEmpty() ) {
  5956. // Empty sphere produces empty bounding box
  5957. target.makeEmpty();
  5958. return target;
  5959. }
  5960. target.set( this.center, this.center );
  5961. target.expandByScalar( this.radius );
  5962. return target;
  5963. }
  5964. /**
  5965. * Transforms this sphere with the given 4x4 transformation matrix.
  5966. *
  5967. * @param {Matrix4} matrix - The transformation matrix.
  5968. * @return {Sphere} A reference to this sphere.
  5969. */
  5970. applyMatrix4( matrix ) {
  5971. this.center.applyMatrix4( matrix );
  5972. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  5973. return this;
  5974. }
  5975. /**
  5976. * Translates the sphere's center by the given offset.
  5977. *
  5978. * @param {Vector3} offset - The offset.
  5979. * @return {Sphere} A reference to this sphere.
  5980. */
  5981. translate( offset ) {
  5982. this.center.add( offset );
  5983. return this;
  5984. }
  5985. /**
  5986. * Expands the boundaries of this sphere to include the given point.
  5987. *
  5988. * @param {Vector3} point - The point to include.
  5989. * @return {Sphere} A reference to this sphere.
  5990. */
  5991. expandByPoint( point ) {
  5992. if ( this.isEmpty() ) {
  5993. this.center.copy( point );
  5994. this.radius = 0;
  5995. return this;
  5996. }
  5997. _v1$6.subVectors( point, this.center );
  5998. const lengthSq = _v1$6.lengthSq();
  5999. if ( lengthSq > ( this.radius * this.radius ) ) {
  6000. // calculate the minimal sphere
  6001. const length = Math.sqrt( lengthSq );
  6002. const delta = ( length - this.radius ) * 0.5;
  6003. this.center.addScaledVector( _v1$6, delta / length );
  6004. this.radius += delta;
  6005. }
  6006. return this;
  6007. }
  6008. /**
  6009. * Expands this sphere to enclose both the original sphere and the given sphere.
  6010. *
  6011. * @param {Sphere} sphere - The sphere to include.
  6012. * @return {Sphere} A reference to this sphere.
  6013. */
  6014. union( sphere ) {
  6015. if ( sphere.isEmpty() ) {
  6016. return this;
  6017. }
  6018. if ( this.isEmpty() ) {
  6019. this.copy( sphere );
  6020. return this;
  6021. }
  6022. if ( this.center.equals( sphere.center ) === true ) {
  6023. this.radius = Math.max( this.radius, sphere.radius );
  6024. } else {
  6025. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  6026. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  6027. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  6028. }
  6029. return this;
  6030. }
  6031. /**
  6032. * Returns `true` if this sphere is equal with the given one.
  6033. *
  6034. * @param {Sphere} sphere - The sphere to test for equality.
  6035. * @return {boolean} Whether this bounding sphere is equal with the given one.
  6036. */
  6037. equals( sphere ) {
  6038. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  6039. }
  6040. /**
  6041. * Returns a new sphere with copied values from this instance.
  6042. *
  6043. * @return {Sphere} A clone of this instance.
  6044. */
  6045. clone() {
  6046. return new this.constructor().copy( this );
  6047. }
  6048. }
  6049. const _vector$a = /*@__PURE__*/ new Vector3();
  6050. const _segCenter = /*@__PURE__*/ new Vector3();
  6051. const _segDir = /*@__PURE__*/ new Vector3();
  6052. const _diff = /*@__PURE__*/ new Vector3();
  6053. const _edge1 = /*@__PURE__*/ new Vector3();
  6054. const _edge2 = /*@__PURE__*/ new Vector3();
  6055. const _normal$1 = /*@__PURE__*/ new Vector3();
  6056. /**
  6057. * A ray that emits from an origin in a certain direction. The class is used by
  6058. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  6059. * mouse picking (working out what objects in the 3D space the mouse is over)
  6060. * amongst other things.
  6061. */
  6062. class Ray {
  6063. /**
  6064. * Constructs a new ray.
  6065. *
  6066. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  6067. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  6068. */
  6069. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  6070. /**
  6071. * The origin of the ray.
  6072. *
  6073. * @type {Vector3}
  6074. */
  6075. this.origin = origin;
  6076. /**
  6077. * The (normalized) direction of the ray.
  6078. *
  6079. * @type {Vector3}
  6080. */
  6081. this.direction = direction;
  6082. }
  6083. /**
  6084. * Sets the ray's components by copying the given values.
  6085. *
  6086. * @param {Vector3} origin - The origin.
  6087. * @param {Vector3} direction - The direction.
  6088. * @return {Ray} A reference to this ray.
  6089. */
  6090. set( origin, direction ) {
  6091. this.origin.copy( origin );
  6092. this.direction.copy( direction );
  6093. return this;
  6094. }
  6095. /**
  6096. * Copies the values of the given ray to this instance.
  6097. *
  6098. * @param {Ray} ray - The ray to copy.
  6099. * @return {Ray} A reference to this ray.
  6100. */
  6101. copy( ray ) {
  6102. this.origin.copy( ray.origin );
  6103. this.direction.copy( ray.direction );
  6104. return this;
  6105. }
  6106. /**
  6107. * Returns a vector that is located at a given distance along this ray.
  6108. *
  6109. * @param {number} t - The distance along the ray to retrieve a position for.
  6110. * @param {Vector3} target - The target vector that is used to store the method's result.
  6111. * @return {Vector3} A position on the ray.
  6112. */
  6113. at( t, target ) {
  6114. return target.copy( this.origin ).addScaledVector( this.direction, t );
  6115. }
  6116. /**
  6117. * Adjusts the direction of the ray to point at the given vector in world space.
  6118. *
  6119. * @param {Vector3} v - The target position.
  6120. * @return {Ray} A reference to this ray.
  6121. */
  6122. lookAt( v ) {
  6123. this.direction.copy( v ).sub( this.origin ).normalize();
  6124. return this;
  6125. }
  6126. /**
  6127. * Shift the origin of this ray along its direction by the given distance.
  6128. *
  6129. * @param {number} t - The distance along the ray to interpolate.
  6130. * @return {Ray} A reference to this ray.
  6131. */
  6132. recast( t ) {
  6133. this.origin.copy( this.at( t, _vector$a ) );
  6134. return this;
  6135. }
  6136. /**
  6137. * Returns the point along this ray that is closest to the given point.
  6138. *
  6139. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  6140. * @param {Vector3} target - The target vector that is used to store the method's result.
  6141. * @return {Vector3} The closest point on this ray.
  6142. */
  6143. closestPointToPoint( point, target ) {
  6144. target.subVectors( point, this.origin );
  6145. const directionDistance = target.dot( this.direction );
  6146. if ( directionDistance < 0 ) {
  6147. return target.copy( this.origin );
  6148. }
  6149. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6150. }
  6151. /**
  6152. * Returns the distance of the closest approach between this ray and the given point.
  6153. *
  6154. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6155. * @return {number} The distance.
  6156. */
  6157. distanceToPoint( point ) {
  6158. return Math.sqrt( this.distanceSqToPoint( point ) );
  6159. }
  6160. /**
  6161. * Returns the squared distance of the closest approach between this ray and the given point.
  6162. *
  6163. * @param {Vector3} point - A point in 3D space to compute the distance to.
  6164. * @return {number} The squared distance.
  6165. */
  6166. distanceSqToPoint( point ) {
  6167. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  6168. // point behind the ray
  6169. if ( directionDistance < 0 ) {
  6170. return this.origin.distanceToSquared( point );
  6171. }
  6172. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  6173. return _vector$a.distanceToSquared( point );
  6174. }
  6175. /**
  6176. * Returns the squared distance between this ray and the given line segment.
  6177. *
  6178. * @param {Vector3} v0 - The start point of the line segment.
  6179. * @param {Vector3} v1 - The end point of the line segment.
  6180. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  6181. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  6182. * @return {number} The squared distance.
  6183. */
  6184. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  6185. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  6186. // It returns the min distance between the ray and the segment
  6187. // defined by v0 and v1
  6188. // It can also set two optional targets :
  6189. // - The closest point on the ray
  6190. // - The closest point on the segment
  6191. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  6192. _segDir.copy( v1 ).sub( v0 ).normalize();
  6193. _diff.copy( this.origin ).sub( _segCenter );
  6194. const segExtent = v0.distanceTo( v1 ) * 0.5;
  6195. const a01 = - this.direction.dot( _segDir );
  6196. const b0 = _diff.dot( this.direction );
  6197. const b1 = - _diff.dot( _segDir );
  6198. const c = _diff.lengthSq();
  6199. const det = Math.abs( 1 - a01 * a01 );
  6200. let s0, s1, sqrDist, extDet;
  6201. if ( det > 0 ) {
  6202. // The ray and segment are not parallel.
  6203. s0 = a01 * b1 - b0;
  6204. s1 = a01 * b0 - b1;
  6205. extDet = segExtent * det;
  6206. if ( s0 >= 0 ) {
  6207. if ( s1 >= - extDet ) {
  6208. if ( s1 <= extDet ) {
  6209. // region 0
  6210. // Minimum at interior points of ray and segment.
  6211. const invDet = 1 / det;
  6212. s0 *= invDet;
  6213. s1 *= invDet;
  6214. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  6215. } else {
  6216. // region 1
  6217. s1 = segExtent;
  6218. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6219. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6220. }
  6221. } else {
  6222. // region 5
  6223. s1 = - segExtent;
  6224. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6225. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6226. }
  6227. } else {
  6228. if ( s1 <= - extDet ) {
  6229. // region 4
  6230. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  6231. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6232. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6233. } else if ( s1 <= extDet ) {
  6234. // region 3
  6235. s0 = 0;
  6236. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6237. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  6238. } else {
  6239. // region 2
  6240. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  6241. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  6242. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6243. }
  6244. }
  6245. } else {
  6246. // Ray and segment are parallel.
  6247. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  6248. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  6249. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  6250. }
  6251. if ( optionalPointOnRay ) {
  6252. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  6253. }
  6254. if ( optionalPointOnSegment ) {
  6255. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  6256. }
  6257. return sqrDist;
  6258. }
  6259. /**
  6260. * Intersects this ray with the given sphere, returning the intersection
  6261. * point or `null` if there is no intersection.
  6262. *
  6263. * @param {Sphere} sphere - The sphere to intersect.
  6264. * @param {Vector3} target - The target vector that is used to store the method's result.
  6265. * @return {?Vector3} The intersection point.
  6266. */
  6267. intersectSphere( sphere, target ) {
  6268. _vector$a.subVectors( sphere.center, this.origin );
  6269. const tca = _vector$a.dot( this.direction );
  6270. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  6271. const radius2 = sphere.radius * sphere.radius;
  6272. if ( d2 > radius2 ) return null;
  6273. const thc = Math.sqrt( radius2 - d2 );
  6274. // t0 = first intersect point - entrance on front of sphere
  6275. const t0 = tca - thc;
  6276. // t1 = second intersect point - exit point on back of sphere
  6277. const t1 = tca + thc;
  6278. // test to see if t1 is behind the ray - if so, return null
  6279. if ( t1 < 0 ) return null;
  6280. // test to see if t0 is behind the ray:
  6281. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  6282. // in order to always return an intersect point that is in front of the ray.
  6283. if ( t0 < 0 ) return this.at( t1, target );
  6284. // else t0 is in front of the ray, so return the first collision point scaled by t0
  6285. return this.at( t0, target );
  6286. }
  6287. /**
  6288. * Returns `true` if this ray intersects with the given sphere.
  6289. *
  6290. * @param {Sphere} sphere - The sphere to intersect.
  6291. * @return {boolean} Whether this ray intersects with the given sphere or not.
  6292. */
  6293. intersectsSphere( sphere ) {
  6294. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  6295. }
  6296. /**
  6297. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  6298. * does not intersect with the plane.
  6299. *
  6300. * @param {Plane} plane - The plane to compute the distance to.
  6301. * @return {?number} Whether this ray intersects with the given sphere or not.
  6302. */
  6303. distanceToPlane( plane ) {
  6304. const denominator = plane.normal.dot( this.direction );
  6305. if ( denominator === 0 ) {
  6306. // line is coplanar, return origin
  6307. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  6308. return 0;
  6309. }
  6310. // Null is preferable to undefined since undefined means.... it is undefined
  6311. return null;
  6312. }
  6313. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  6314. // Return if the ray never intersects the plane
  6315. return t >= 0 ? t : null;
  6316. }
  6317. /**
  6318. * Intersects this ray with the given plane, returning the intersection
  6319. * point or `null` if there is no intersection.
  6320. *
  6321. * @param {Plane} plane - The plane to intersect.
  6322. * @param {Vector3} target - The target vector that is used to store the method's result.
  6323. * @return {?Vector3} The intersection point.
  6324. */
  6325. intersectPlane( plane, target ) {
  6326. const t = this.distanceToPlane( plane );
  6327. if ( t === null ) {
  6328. return null;
  6329. }
  6330. return this.at( t, target );
  6331. }
  6332. /**
  6333. * Returns `true` if this ray intersects with the given plane.
  6334. *
  6335. * @param {Plane} plane - The plane to intersect.
  6336. * @return {boolean} Whether this ray intersects with the given plane or not.
  6337. */
  6338. intersectsPlane( plane ) {
  6339. // check if the ray lies on the plane first
  6340. const distToPoint = plane.distanceToPoint( this.origin );
  6341. if ( distToPoint === 0 ) {
  6342. return true;
  6343. }
  6344. const denominator = plane.normal.dot( this.direction );
  6345. if ( denominator * distToPoint < 0 ) {
  6346. return true;
  6347. }
  6348. // ray origin is behind the plane (and is pointing behind it)
  6349. return false;
  6350. }
  6351. /**
  6352. * Intersects this ray with the given bounding box, returning the intersection
  6353. * point or `null` if there is no intersection.
  6354. *
  6355. * @param {Box3} box - The box to intersect.
  6356. * @param {Vector3} target - The target vector that is used to store the method's result.
  6357. * @return {?Vector3} The intersection point.
  6358. */
  6359. intersectBox( box, target ) {
  6360. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  6361. const invdirx = 1 / this.direction.x,
  6362. invdiry = 1 / this.direction.y,
  6363. invdirz = 1 / this.direction.z;
  6364. const origin = this.origin;
  6365. if ( invdirx >= 0 ) {
  6366. tmin = ( box.min.x - origin.x ) * invdirx;
  6367. tmax = ( box.max.x - origin.x ) * invdirx;
  6368. } else {
  6369. tmin = ( box.max.x - origin.x ) * invdirx;
  6370. tmax = ( box.min.x - origin.x ) * invdirx;
  6371. }
  6372. if ( invdiry >= 0 ) {
  6373. tymin = ( box.min.y - origin.y ) * invdiry;
  6374. tymax = ( box.max.y - origin.y ) * invdiry;
  6375. } else {
  6376. tymin = ( box.max.y - origin.y ) * invdiry;
  6377. tymax = ( box.min.y - origin.y ) * invdiry;
  6378. }
  6379. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  6380. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  6381. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  6382. if ( invdirz >= 0 ) {
  6383. tzmin = ( box.min.z - origin.z ) * invdirz;
  6384. tzmax = ( box.max.z - origin.z ) * invdirz;
  6385. } else {
  6386. tzmin = ( box.max.z - origin.z ) * invdirz;
  6387. tzmax = ( box.min.z - origin.z ) * invdirz;
  6388. }
  6389. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  6390. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  6391. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  6392. //return point closest to the ray (positive side)
  6393. if ( tmax < 0 ) return null;
  6394. return this.at( tmin >= 0 ? tmin : tmax, target );
  6395. }
  6396. /**
  6397. * Returns `true` if this ray intersects with the given box.
  6398. *
  6399. * @param {Box3} box - The box to intersect.
  6400. * @return {boolean} Whether this ray intersects with the given box or not.
  6401. */
  6402. intersectsBox( box ) {
  6403. return this.intersectBox( box, _vector$a ) !== null;
  6404. }
  6405. /**
  6406. * Intersects this ray with the given triangle, returning the intersection
  6407. * point or `null` if there is no intersection.
  6408. *
  6409. * @param {Vector3} a - The first vertex of the triangle.
  6410. * @param {Vector3} b - The second vertex of the triangle.
  6411. * @param {Vector3} c - The third vertex of the triangle.
  6412. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  6413. * @param {Vector3} target - The target vector that is used to store the method's result.
  6414. * @return {?Vector3} The intersection point.
  6415. */
  6416. intersectTriangle( a, b, c, backfaceCulling, target ) {
  6417. // Compute the offset origin, edges, and normal.
  6418. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  6419. _edge1.subVectors( b, a );
  6420. _edge2.subVectors( c, a );
  6421. _normal$1.crossVectors( _edge1, _edge2 );
  6422. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  6423. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  6424. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  6425. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  6426. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  6427. let DdN = this.direction.dot( _normal$1 );
  6428. let sign;
  6429. if ( DdN > 0 ) {
  6430. if ( backfaceCulling ) return null;
  6431. sign = 1;
  6432. } else if ( DdN < 0 ) {
  6433. sign = -1;
  6434. DdN = - DdN;
  6435. } else {
  6436. return null;
  6437. }
  6438. _diff.subVectors( this.origin, a );
  6439. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  6440. // b1 < 0, no intersection
  6441. if ( DdQxE2 < 0 ) {
  6442. return null;
  6443. }
  6444. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  6445. // b2 < 0, no intersection
  6446. if ( DdE1xQ < 0 ) {
  6447. return null;
  6448. }
  6449. // b1+b2 > 1, no intersection
  6450. if ( DdQxE2 + DdE1xQ > DdN ) {
  6451. return null;
  6452. }
  6453. // Line intersects triangle, check if ray does.
  6454. const QdN = - sign * _diff.dot( _normal$1 );
  6455. // t < 0, no intersection
  6456. if ( QdN < 0 ) {
  6457. return null;
  6458. }
  6459. // Ray intersects triangle.
  6460. return this.at( QdN / DdN, target );
  6461. }
  6462. /**
  6463. * Transforms this ray with the given 4x4 transformation matrix.
  6464. *
  6465. * @param {Matrix4} matrix4 - The transformation matrix.
  6466. * @return {Ray} A reference to this ray.
  6467. */
  6468. applyMatrix4( matrix4 ) {
  6469. this.origin.applyMatrix4( matrix4 );
  6470. this.direction.transformDirection( matrix4 );
  6471. return this;
  6472. }
  6473. /**
  6474. * Returns `true` if this ray is equal with the given one.
  6475. *
  6476. * @param {Ray} ray - The ray to test for equality.
  6477. * @return {boolean} Whether this ray is equal with the given one.
  6478. */
  6479. equals( ray ) {
  6480. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  6481. }
  6482. /**
  6483. * Returns a new ray with copied values from this instance.
  6484. *
  6485. * @return {Ray} A clone of this instance.
  6486. */
  6487. clone() {
  6488. return new this.constructor().copy( this );
  6489. }
  6490. }
  6491. /**
  6492. * Represents a 4x4 matrix.
  6493. *
  6494. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  6495. * 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}
  6496. *
  6497. * This allows a 3D vector representing a point in 3D space to undergo
  6498. * transformations such as translation, rotation, shear, scale, reflection,
  6499. * orthogonal or perspective projection and so on, by being multiplied by the
  6500. * matrix. This is known as `applying` the matrix to the vector.
  6501. *
  6502. * A Note on Row-Major and Column-Major Ordering:
  6503. *
  6504. * The constructor and {@link Matrix3#set} method take arguments in
  6505. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  6506. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  6507. * This means that calling:
  6508. * ```js
  6509. * const m = new THREE.Matrix4();
  6510. * m.set( 11, 12, 13, 14,
  6511. * 21, 22, 23, 24,
  6512. * 31, 32, 33, 34,
  6513. * 41, 42, 43, 44 );
  6514. * ```
  6515. * will result in the elements array containing:
  6516. * ```js
  6517. * m.elements = [ 11, 21, 31, 41,
  6518. * 12, 22, 32, 42,
  6519. * 13, 23, 33, 43,
  6520. * 14, 24, 34, 44 ];
  6521. * ```
  6522. * and internally all calculations are performed using column-major ordering.
  6523. * However, as the actual ordering makes no difference mathematically and
  6524. * most people are used to thinking about matrices in row-major order, the
  6525. * three.js documentation shows matrices in row-major order. Just bear in
  6526. * mind that if you are reading the source code, you'll have to take the
  6527. * transpose of any matrices outlined here to make sense of the calculations.
  6528. */
  6529. class Matrix4 {
  6530. /**
  6531. * Constructs a new 4x4 matrix. The arguments are supposed to be
  6532. * in row-major order. If no arguments are provided, the constructor
  6533. * initializes the matrix as an identity matrix.
  6534. *
  6535. * @param {number} [n11] - 1-1 matrix element.
  6536. * @param {number} [n12] - 1-2 matrix element.
  6537. * @param {number} [n13] - 1-3 matrix element.
  6538. * @param {number} [n14] - 1-4 matrix element.
  6539. * @param {number} [n21] - 2-1 matrix element.
  6540. * @param {number} [n22] - 2-2 matrix element.
  6541. * @param {number} [n23] - 2-3 matrix element.
  6542. * @param {number} [n24] - 2-4 matrix element.
  6543. * @param {number} [n31] - 3-1 matrix element.
  6544. * @param {number} [n32] - 3-2 matrix element.
  6545. * @param {number} [n33] - 3-3 matrix element.
  6546. * @param {number} [n34] - 3-4 matrix element.
  6547. * @param {number} [n41] - 4-1 matrix element.
  6548. * @param {number} [n42] - 4-2 matrix element.
  6549. * @param {number} [n43] - 4-3 matrix element.
  6550. * @param {number} [n44] - 4-4 matrix element.
  6551. */
  6552. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6553. /**
  6554. * This flag can be used for type testing.
  6555. *
  6556. * @type {boolean}
  6557. * @readonly
  6558. * @default true
  6559. */
  6560. Matrix4.prototype.isMatrix4 = true;
  6561. /**
  6562. * A column-major list of matrix values.
  6563. *
  6564. * @type {Array<number>}
  6565. */
  6566. this.elements = [
  6567. 1, 0, 0, 0,
  6568. 0, 1, 0, 0,
  6569. 0, 0, 1, 0,
  6570. 0, 0, 0, 1
  6571. ];
  6572. if ( n11 !== undefined ) {
  6573. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  6574. }
  6575. }
  6576. /**
  6577. * Sets the elements of the matrix.The arguments are supposed to be
  6578. * in row-major order.
  6579. *
  6580. * @param {number} [n11] - 1-1 matrix element.
  6581. * @param {number} [n12] - 1-2 matrix element.
  6582. * @param {number} [n13] - 1-3 matrix element.
  6583. * @param {number} [n14] - 1-4 matrix element.
  6584. * @param {number} [n21] - 2-1 matrix element.
  6585. * @param {number} [n22] - 2-2 matrix element.
  6586. * @param {number} [n23] - 2-3 matrix element.
  6587. * @param {number} [n24] - 2-4 matrix element.
  6588. * @param {number} [n31] - 3-1 matrix element.
  6589. * @param {number} [n32] - 3-2 matrix element.
  6590. * @param {number} [n33] - 3-3 matrix element.
  6591. * @param {number} [n34] - 3-4 matrix element.
  6592. * @param {number} [n41] - 4-1 matrix element.
  6593. * @param {number} [n42] - 4-2 matrix element.
  6594. * @param {number} [n43] - 4-3 matrix element.
  6595. * @param {number} [n44] - 4-4 matrix element.
  6596. * @return {Matrix4} A reference to this matrix.
  6597. */
  6598. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6599. const te = this.elements;
  6600. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6601. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6602. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6603. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6604. return this;
  6605. }
  6606. /**
  6607. * Sets this matrix to the 4x4 identity matrix.
  6608. *
  6609. * @return {Matrix4} A reference to this matrix.
  6610. */
  6611. identity() {
  6612. this.set(
  6613. 1, 0, 0, 0,
  6614. 0, 1, 0, 0,
  6615. 0, 0, 1, 0,
  6616. 0, 0, 0, 1
  6617. );
  6618. return this;
  6619. }
  6620. /**
  6621. * Returns a matrix with copied values from this instance.
  6622. *
  6623. * @return {Matrix4} A clone of this instance.
  6624. */
  6625. clone() {
  6626. return new Matrix4().fromArray( this.elements );
  6627. }
  6628. /**
  6629. * Copies the values of the given matrix to this instance.
  6630. *
  6631. * @param {Matrix4} m - The matrix to copy.
  6632. * @return {Matrix4} A reference to this matrix.
  6633. */
  6634. copy( m ) {
  6635. const te = this.elements;
  6636. const me = m.elements;
  6637. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  6638. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  6639. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  6640. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  6641. return this;
  6642. }
  6643. /**
  6644. * Copies the translation component of the given matrix
  6645. * into this matrix's translation component.
  6646. *
  6647. * @param {Matrix4} m - The matrix to copy the translation component.
  6648. * @return {Matrix4} A reference to this matrix.
  6649. */
  6650. copyPosition( m ) {
  6651. const te = this.elements, me = m.elements;
  6652. te[ 12 ] = me[ 12 ];
  6653. te[ 13 ] = me[ 13 ];
  6654. te[ 14 ] = me[ 14 ];
  6655. return this;
  6656. }
  6657. /**
  6658. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  6659. *
  6660. * @param {Matrix3} m - The 3x3 matrix.
  6661. * @return {Matrix4} A reference to this matrix.
  6662. */
  6663. setFromMatrix3( m ) {
  6664. const me = m.elements;
  6665. this.set(
  6666. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  6667. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  6668. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  6669. 0, 0, 0, 1
  6670. );
  6671. return this;
  6672. }
  6673. /**
  6674. * Extracts the basis of this matrix into the three axis vectors provided.
  6675. *
  6676. * @param {Vector3} xAxis - The basis's x axis.
  6677. * @param {Vector3} yAxis - The basis's y axis.
  6678. * @param {Vector3} zAxis - The basis's z axis.
  6679. * @return {Matrix4} A reference to this matrix.
  6680. */
  6681. extractBasis( xAxis, yAxis, zAxis ) {
  6682. xAxis.setFromMatrixColumn( this, 0 );
  6683. yAxis.setFromMatrixColumn( this, 1 );
  6684. zAxis.setFromMatrixColumn( this, 2 );
  6685. return this;
  6686. }
  6687. /**
  6688. * Sets the given basis vectors to this matrix.
  6689. *
  6690. * @param {Vector3} xAxis - The basis's x axis.
  6691. * @param {Vector3} yAxis - The basis's y axis.
  6692. * @param {Vector3} zAxis - The basis's z axis.
  6693. * @return {Matrix4} A reference to this matrix.
  6694. */
  6695. makeBasis( xAxis, yAxis, zAxis ) {
  6696. this.set(
  6697. xAxis.x, yAxis.x, zAxis.x, 0,
  6698. xAxis.y, yAxis.y, zAxis.y, 0,
  6699. xAxis.z, yAxis.z, zAxis.z, 0,
  6700. 0, 0, 0, 1
  6701. );
  6702. return this;
  6703. }
  6704. /**
  6705. * Extracts the rotation component of the given matrix
  6706. * into this matrix's rotation component.
  6707. *
  6708. * Note: This method does not support reflection matrices.
  6709. *
  6710. * @param {Matrix4} m - The matrix.
  6711. * @return {Matrix4} A reference to this matrix.
  6712. */
  6713. extractRotation( m ) {
  6714. const te = this.elements;
  6715. const me = m.elements;
  6716. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  6717. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  6718. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  6719. te[ 0 ] = me[ 0 ] * scaleX;
  6720. te[ 1 ] = me[ 1 ] * scaleX;
  6721. te[ 2 ] = me[ 2 ] * scaleX;
  6722. te[ 3 ] = 0;
  6723. te[ 4 ] = me[ 4 ] * scaleY;
  6724. te[ 5 ] = me[ 5 ] * scaleY;
  6725. te[ 6 ] = me[ 6 ] * scaleY;
  6726. te[ 7 ] = 0;
  6727. te[ 8 ] = me[ 8 ] * scaleZ;
  6728. te[ 9 ] = me[ 9 ] * scaleZ;
  6729. te[ 10 ] = me[ 10 ] * scaleZ;
  6730. te[ 11 ] = 0;
  6731. te[ 12 ] = 0;
  6732. te[ 13 ] = 0;
  6733. te[ 14 ] = 0;
  6734. te[ 15 ] = 1;
  6735. return this;
  6736. }
  6737. /**
  6738. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  6739. * the rotation specified by the given Euler angles. The rest of
  6740. * the matrix is set to the identity. Depending on the {@link Euler#order},
  6741. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  6742. * for a complete list.
  6743. *
  6744. * @param {Euler} euler - The Euler angles.
  6745. * @return {Matrix4} A reference to this matrix.
  6746. */
  6747. makeRotationFromEuler( euler ) {
  6748. const te = this.elements;
  6749. const x = euler.x, y = euler.y, z = euler.z;
  6750. const a = Math.cos( x ), b = Math.sin( x );
  6751. const c = Math.cos( y ), d = Math.sin( y );
  6752. const e = Math.cos( z ), f = Math.sin( z );
  6753. if ( euler.order === 'XYZ' ) {
  6754. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6755. te[ 0 ] = c * e;
  6756. te[ 4 ] = - c * f;
  6757. te[ 8 ] = d;
  6758. te[ 1 ] = af + be * d;
  6759. te[ 5 ] = ae - bf * d;
  6760. te[ 9 ] = - b * c;
  6761. te[ 2 ] = bf - ae * d;
  6762. te[ 6 ] = be + af * d;
  6763. te[ 10 ] = a * c;
  6764. } else if ( euler.order === 'YXZ' ) {
  6765. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6766. te[ 0 ] = ce + df * b;
  6767. te[ 4 ] = de * b - cf;
  6768. te[ 8 ] = a * d;
  6769. te[ 1 ] = a * f;
  6770. te[ 5 ] = a * e;
  6771. te[ 9 ] = - b;
  6772. te[ 2 ] = cf * b - de;
  6773. te[ 6 ] = df + ce * b;
  6774. te[ 10 ] = a * c;
  6775. } else if ( euler.order === 'ZXY' ) {
  6776. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  6777. te[ 0 ] = ce - df * b;
  6778. te[ 4 ] = - a * f;
  6779. te[ 8 ] = de + cf * b;
  6780. te[ 1 ] = cf + de * b;
  6781. te[ 5 ] = a * e;
  6782. te[ 9 ] = df - ce * b;
  6783. te[ 2 ] = - a * d;
  6784. te[ 6 ] = b;
  6785. te[ 10 ] = a * c;
  6786. } else if ( euler.order === 'ZYX' ) {
  6787. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  6788. te[ 0 ] = c * e;
  6789. te[ 4 ] = be * d - af;
  6790. te[ 8 ] = ae * d + bf;
  6791. te[ 1 ] = c * f;
  6792. te[ 5 ] = bf * d + ae;
  6793. te[ 9 ] = af * d - be;
  6794. te[ 2 ] = - d;
  6795. te[ 6 ] = b * c;
  6796. te[ 10 ] = a * c;
  6797. } else if ( euler.order === 'YZX' ) {
  6798. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6799. te[ 0 ] = c * e;
  6800. te[ 4 ] = bd - ac * f;
  6801. te[ 8 ] = bc * f + ad;
  6802. te[ 1 ] = f;
  6803. te[ 5 ] = a * e;
  6804. te[ 9 ] = - b * e;
  6805. te[ 2 ] = - d * e;
  6806. te[ 6 ] = ad * f + bc;
  6807. te[ 10 ] = ac - bd * f;
  6808. } else if ( euler.order === 'XZY' ) {
  6809. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6810. te[ 0 ] = c * e;
  6811. te[ 4 ] = - f;
  6812. te[ 8 ] = d * e;
  6813. te[ 1 ] = ac * f + bd;
  6814. te[ 5 ] = a * e;
  6815. te[ 9 ] = ad * f - bc;
  6816. te[ 2 ] = bc * f - ad;
  6817. te[ 6 ] = b * e;
  6818. te[ 10 ] = bd * f + ac;
  6819. }
  6820. // bottom row
  6821. te[ 3 ] = 0;
  6822. te[ 7 ] = 0;
  6823. te[ 11 ] = 0;
  6824. // last column
  6825. te[ 12 ] = 0;
  6826. te[ 13 ] = 0;
  6827. te[ 14 ] = 0;
  6828. te[ 15 ] = 1;
  6829. return this;
  6830. }
  6831. /**
  6832. * Sets the rotation component of this matrix to the rotation specified by
  6833. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  6834. * The rest of the matrix is set to the identity.
  6835. *
  6836. * @param {Quaternion} q - The Quaternion.
  6837. * @return {Matrix4} A reference to this matrix.
  6838. */
  6839. makeRotationFromQuaternion( q ) {
  6840. return this.compose( _zero, q, _one );
  6841. }
  6842. /**
  6843. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  6844. * `target`, and oriented by the up-direction.
  6845. *
  6846. * @param {Vector3} eye - The eye vector.
  6847. * @param {Vector3} target - The target vector.
  6848. * @param {Vector3} up - The up vector.
  6849. * @return {Matrix4} A reference to this matrix.
  6850. */
  6851. lookAt( eye, target, up ) {
  6852. const te = this.elements;
  6853. _z.subVectors( eye, target );
  6854. if ( _z.lengthSq() === 0 ) {
  6855. // eye and target are in the same position
  6856. _z.z = 1;
  6857. }
  6858. _z.normalize();
  6859. _x.crossVectors( up, _z );
  6860. if ( _x.lengthSq() === 0 ) {
  6861. // up and z are parallel
  6862. if ( Math.abs( up.z ) === 1 ) {
  6863. _z.x += 0.0001;
  6864. } else {
  6865. _z.z += 0.0001;
  6866. }
  6867. _z.normalize();
  6868. _x.crossVectors( up, _z );
  6869. }
  6870. _x.normalize();
  6871. _y.crossVectors( _z, _x );
  6872. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  6873. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  6874. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  6875. return this;
  6876. }
  6877. /**
  6878. * Post-multiplies this matrix by the given 4x4 matrix.
  6879. *
  6880. * @param {Matrix4} m - The matrix to multiply with.
  6881. * @return {Matrix4} A reference to this matrix.
  6882. */
  6883. multiply( m ) {
  6884. return this.multiplyMatrices( this, m );
  6885. }
  6886. /**
  6887. * Pre-multiplies this matrix by the given 4x4 matrix.
  6888. *
  6889. * @param {Matrix4} m - The matrix to multiply with.
  6890. * @return {Matrix4} A reference to this matrix.
  6891. */
  6892. premultiply( m ) {
  6893. return this.multiplyMatrices( m, this );
  6894. }
  6895. /**
  6896. * Multiples the given 4x4 matrices and stores the result
  6897. * in this matrix.
  6898. *
  6899. * @param {Matrix4} a - The first matrix.
  6900. * @param {Matrix4} b - The second matrix.
  6901. * @return {Matrix4} A reference to this matrix.
  6902. */
  6903. multiplyMatrices( a, b ) {
  6904. const ae = a.elements;
  6905. const be = b.elements;
  6906. const te = this.elements;
  6907. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6908. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6909. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6910. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6911. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6912. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6913. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6914. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6915. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6916. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6917. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6918. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6919. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6920. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6921. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6922. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6923. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6924. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6925. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6926. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6927. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6928. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6929. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6930. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6931. return this;
  6932. }
  6933. /**
  6934. * Multiplies every component of the matrix by the given scalar.
  6935. *
  6936. * @param {number} s - The scalar.
  6937. * @return {Matrix4} A reference to this matrix.
  6938. */
  6939. multiplyScalar( s ) {
  6940. const te = this.elements;
  6941. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6942. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6943. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6944. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6945. return this;
  6946. }
  6947. /**
  6948. * Computes and returns the determinant of this matrix.
  6949. *
  6950. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  6951. *
  6952. * @return {number} The determinant.
  6953. */
  6954. determinant() {
  6955. const te = this.elements;
  6956. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6957. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6958. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6959. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6960. //TODO: make this more efficient
  6961. return (
  6962. n41 * (
  6963. + n14 * n23 * n32
  6964. - n13 * n24 * n32
  6965. - n14 * n22 * n33
  6966. + n12 * n24 * n33
  6967. + n13 * n22 * n34
  6968. - n12 * n23 * n34
  6969. ) +
  6970. n42 * (
  6971. + n11 * n23 * n34
  6972. - n11 * n24 * n33
  6973. + n14 * n21 * n33
  6974. - n13 * n21 * n34
  6975. + n13 * n24 * n31
  6976. - n14 * n23 * n31
  6977. ) +
  6978. n43 * (
  6979. + n11 * n24 * n32
  6980. - n11 * n22 * n34
  6981. - n14 * n21 * n32
  6982. + n12 * n21 * n34
  6983. + n14 * n22 * n31
  6984. - n12 * n24 * n31
  6985. ) +
  6986. n44 * (
  6987. - n13 * n22 * n31
  6988. - n11 * n23 * n32
  6989. + n11 * n22 * n33
  6990. + n13 * n21 * n32
  6991. - n12 * n21 * n33
  6992. + n12 * n23 * n31
  6993. )
  6994. );
  6995. }
  6996. /**
  6997. * Transposes this matrix in place.
  6998. *
  6999. * @return {Matrix4} A reference to this matrix.
  7000. */
  7001. transpose() {
  7002. const te = this.elements;
  7003. let tmp;
  7004. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  7005. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  7006. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  7007. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  7008. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  7009. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  7010. return this;
  7011. }
  7012. /**
  7013. * Sets the position component for this matrix from the given vector,
  7014. * without affecting the rest of the matrix.
  7015. *
  7016. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  7017. * @param {number} y - The y component of the vector.
  7018. * @param {number} z - The z component of the vector.
  7019. * @return {Matrix4} A reference to this matrix.
  7020. */
  7021. setPosition( x, y, z ) {
  7022. const te = this.elements;
  7023. if ( x.isVector3 ) {
  7024. te[ 12 ] = x.x;
  7025. te[ 13 ] = x.y;
  7026. te[ 14 ] = x.z;
  7027. } else {
  7028. te[ 12 ] = x;
  7029. te[ 13 ] = y;
  7030. te[ 14 ] = z;
  7031. }
  7032. return this;
  7033. }
  7034. /**
  7035. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  7036. * You can not invert with a determinant of zero. If you attempt this, the method produces
  7037. * a zero matrix instead.
  7038. *
  7039. * @return {Matrix4} A reference to this matrix.
  7040. */
  7041. invert() {
  7042. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  7043. const te = this.elements,
  7044. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  7045. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  7046. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  7047. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  7048. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  7049. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  7050. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  7051. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  7052. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  7053. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  7054. const detInv = 1 / det;
  7055. te[ 0 ] = t11 * detInv;
  7056. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  7057. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  7058. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  7059. te[ 4 ] = t12 * detInv;
  7060. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  7061. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  7062. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  7063. te[ 8 ] = t13 * detInv;
  7064. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  7065. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  7066. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  7067. te[ 12 ] = t14 * detInv;
  7068. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  7069. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  7070. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  7071. return this;
  7072. }
  7073. /**
  7074. * Multiplies the columns of this matrix by the given vector.
  7075. *
  7076. * @param {Vector3} v - The scale vector.
  7077. * @return {Matrix4} A reference to this matrix.
  7078. */
  7079. scale( v ) {
  7080. const te = this.elements;
  7081. const x = v.x, y = v.y, z = v.z;
  7082. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  7083. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  7084. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  7085. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  7086. return this;
  7087. }
  7088. /**
  7089. * Gets the maximum scale value of the three axes.
  7090. *
  7091. * @return {number} The maximum scale.
  7092. */
  7093. getMaxScaleOnAxis() {
  7094. const te = this.elements;
  7095. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  7096. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  7097. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  7098. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  7099. }
  7100. /**
  7101. * Sets this matrix as a translation transform from the given vector.
  7102. *
  7103. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  7104. * @param {number} y - The amount to translate in the Y axis.
  7105. * @param {number} z - The amount to translate in the z axis.
  7106. * @return {Matrix4} A reference to this matrix.
  7107. */
  7108. makeTranslation( x, y, z ) {
  7109. if ( x.isVector3 ) {
  7110. this.set(
  7111. 1, 0, 0, x.x,
  7112. 0, 1, 0, x.y,
  7113. 0, 0, 1, x.z,
  7114. 0, 0, 0, 1
  7115. );
  7116. } else {
  7117. this.set(
  7118. 1, 0, 0, x,
  7119. 0, 1, 0, y,
  7120. 0, 0, 1, z,
  7121. 0, 0, 0, 1
  7122. );
  7123. }
  7124. return this;
  7125. }
  7126. /**
  7127. * Sets this matrix as a rotational transformation around the X axis by
  7128. * the given angle.
  7129. *
  7130. * @param {number} theta - The rotation in radians.
  7131. * @return {Matrix4} A reference to this matrix.
  7132. */
  7133. makeRotationX( theta ) {
  7134. const c = Math.cos( theta ), s = Math.sin( theta );
  7135. this.set(
  7136. 1, 0, 0, 0,
  7137. 0, c, - s, 0,
  7138. 0, s, c, 0,
  7139. 0, 0, 0, 1
  7140. );
  7141. return this;
  7142. }
  7143. /**
  7144. * Sets this matrix as a rotational transformation around the Y axis by
  7145. * the given angle.
  7146. *
  7147. * @param {number} theta - The rotation in radians.
  7148. * @return {Matrix4} A reference to this matrix.
  7149. */
  7150. makeRotationY( theta ) {
  7151. const c = Math.cos( theta ), s = Math.sin( theta );
  7152. this.set(
  7153. c, 0, s, 0,
  7154. 0, 1, 0, 0,
  7155. - s, 0, c, 0,
  7156. 0, 0, 0, 1
  7157. );
  7158. return this;
  7159. }
  7160. /**
  7161. * Sets this matrix as a rotational transformation around the Z axis by
  7162. * the given angle.
  7163. *
  7164. * @param {number} theta - The rotation in radians.
  7165. * @return {Matrix4} A reference to this matrix.
  7166. */
  7167. makeRotationZ( theta ) {
  7168. const c = Math.cos( theta ), s = Math.sin( theta );
  7169. this.set(
  7170. c, - s, 0, 0,
  7171. s, c, 0, 0,
  7172. 0, 0, 1, 0,
  7173. 0, 0, 0, 1
  7174. );
  7175. return this;
  7176. }
  7177. /**
  7178. * Sets this matrix as a rotational transformation around the given axis by
  7179. * the given angle.
  7180. *
  7181. * This is a somewhat controversial but mathematically sound alternative to
  7182. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  7183. *
  7184. * @param {Vector3} axis - The normalized rotation axis.
  7185. * @param {number} angle - The rotation in radians.
  7186. * @return {Matrix4} A reference to this matrix.
  7187. */
  7188. makeRotationAxis( axis, angle ) {
  7189. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  7190. const c = Math.cos( angle );
  7191. const s = Math.sin( angle );
  7192. const t = 1 - c;
  7193. const x = axis.x, y = axis.y, z = axis.z;
  7194. const tx = t * x, ty = t * y;
  7195. this.set(
  7196. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  7197. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  7198. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  7199. 0, 0, 0, 1
  7200. );
  7201. return this;
  7202. }
  7203. /**
  7204. * Sets this matrix as a scale transformation.
  7205. *
  7206. * @param {number} x - The amount to scale in the X axis.
  7207. * @param {number} y - The amount to scale in the Y axis.
  7208. * @param {number} z - The amount to scale in the Z axis.
  7209. * @return {Matrix4} A reference to this matrix.
  7210. */
  7211. makeScale( x, y, z ) {
  7212. this.set(
  7213. x, 0, 0, 0,
  7214. 0, y, 0, 0,
  7215. 0, 0, z, 0,
  7216. 0, 0, 0, 1
  7217. );
  7218. return this;
  7219. }
  7220. /**
  7221. * Sets this matrix as a shear transformation.
  7222. *
  7223. * @param {number} xy - The amount to shear X by Y.
  7224. * @param {number} xz - The amount to shear X by Z.
  7225. * @param {number} yx - The amount to shear Y by X.
  7226. * @param {number} yz - The amount to shear Y by Z.
  7227. * @param {number} zx - The amount to shear Z by X.
  7228. * @param {number} zy - The amount to shear Z by Y.
  7229. * @return {Matrix4} A reference to this matrix.
  7230. */
  7231. makeShear( xy, xz, yx, yz, zx, zy ) {
  7232. this.set(
  7233. 1, yx, zx, 0,
  7234. xy, 1, zy, 0,
  7235. xz, yz, 1, 0,
  7236. 0, 0, 0, 1
  7237. );
  7238. return this;
  7239. }
  7240. /**
  7241. * Sets this matrix to the transformation composed of the given position,
  7242. * rotation (Quaternion) and scale.
  7243. *
  7244. * @param {Vector3} position - The position vector.
  7245. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7246. * @param {Vector3} scale - The scale vector.
  7247. * @return {Matrix4} A reference to this matrix.
  7248. */
  7249. compose( position, quaternion, scale ) {
  7250. const te = this.elements;
  7251. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  7252. const x2 = x + x, y2 = y + y, z2 = z + z;
  7253. const xx = x * x2, xy = x * y2, xz = x * z2;
  7254. const yy = y * y2, yz = y * z2, zz = z * z2;
  7255. const wx = w * x2, wy = w * y2, wz = w * z2;
  7256. const sx = scale.x, sy = scale.y, sz = scale.z;
  7257. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  7258. te[ 1 ] = ( xy + wz ) * sx;
  7259. te[ 2 ] = ( xz - wy ) * sx;
  7260. te[ 3 ] = 0;
  7261. te[ 4 ] = ( xy - wz ) * sy;
  7262. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  7263. te[ 6 ] = ( yz + wx ) * sy;
  7264. te[ 7 ] = 0;
  7265. te[ 8 ] = ( xz + wy ) * sz;
  7266. te[ 9 ] = ( yz - wx ) * sz;
  7267. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  7268. te[ 11 ] = 0;
  7269. te[ 12 ] = position.x;
  7270. te[ 13 ] = position.y;
  7271. te[ 14 ] = position.z;
  7272. te[ 15 ] = 1;
  7273. return this;
  7274. }
  7275. /**
  7276. * Decomposes this matrix into its position, rotation and scale components
  7277. * and provides the result in the given objects.
  7278. *
  7279. * Note: Not all matrices are decomposable in this way. For example, if an
  7280. * object has a non-uniformly scaled parent, then the object's world matrix
  7281. * may not be decomposable, and this method may not be appropriate.
  7282. *
  7283. * @param {Vector3} position - The position vector.
  7284. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  7285. * @param {Vector3} scale - The scale vector.
  7286. * @return {Matrix4} A reference to this matrix.
  7287. */
  7288. decompose( position, quaternion, scale ) {
  7289. const te = this.elements;
  7290. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  7291. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  7292. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  7293. // if determine is negative, we need to invert one scale
  7294. const det = this.determinant();
  7295. if ( det < 0 ) sx = - sx;
  7296. position.x = te[ 12 ];
  7297. position.y = te[ 13 ];
  7298. position.z = te[ 14 ];
  7299. // scale the rotation part
  7300. _m1$2.copy( this );
  7301. const invSX = 1 / sx;
  7302. const invSY = 1 / sy;
  7303. const invSZ = 1 / sz;
  7304. _m1$2.elements[ 0 ] *= invSX;
  7305. _m1$2.elements[ 1 ] *= invSX;
  7306. _m1$2.elements[ 2 ] *= invSX;
  7307. _m1$2.elements[ 4 ] *= invSY;
  7308. _m1$2.elements[ 5 ] *= invSY;
  7309. _m1$2.elements[ 6 ] *= invSY;
  7310. _m1$2.elements[ 8 ] *= invSZ;
  7311. _m1$2.elements[ 9 ] *= invSZ;
  7312. _m1$2.elements[ 10 ] *= invSZ;
  7313. quaternion.setFromRotationMatrix( _m1$2 );
  7314. scale.x = sx;
  7315. scale.y = sy;
  7316. scale.z = sz;
  7317. return this;
  7318. }
  7319. /**
  7320. * Creates a perspective projection matrix. This is used internally by
  7321. * {@link PerspectiveCamera#updateProjectionMatrix}.
  7322. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7323. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7324. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7325. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7326. * @param {number} near - The distance from the camera to the near plane.
  7327. * @param {number} far - The distance from the camera to the far plane.
  7328. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7329. * @return {Matrix4} A reference to this matrix.
  7330. */
  7331. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7332. const te = this.elements;
  7333. const x = 2 * near / ( right - left );
  7334. const y = 2 * near / ( top - bottom );
  7335. const a = ( right + left ) / ( right - left );
  7336. const b = ( top + bottom ) / ( top - bottom );
  7337. let c, d;
  7338. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7339. c = - ( far + near ) / ( far - near );
  7340. d = ( -2 * far * near ) / ( far - near );
  7341. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7342. c = - far / ( far - near );
  7343. d = ( - far * near ) / ( far - near );
  7344. } else {
  7345. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  7346. }
  7347. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  7348. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  7349. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  7350. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  7351. return this;
  7352. }
  7353. /**
  7354. * Creates a orthographic projection matrix. This is used internally by
  7355. * {@link OrthographicCamera#updateProjectionMatrix}.
  7356. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  7357. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  7358. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  7359. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  7360. * @param {number} near - The distance from the camera to the near plane.
  7361. * @param {number} far - The distance from the camera to the far plane.
  7362. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  7363. * @return {Matrix4} A reference to this matrix.
  7364. */
  7365. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  7366. const te = this.elements;
  7367. const w = 1.0 / ( right - left );
  7368. const h = 1.0 / ( top - bottom );
  7369. const p = 1.0 / ( far - near );
  7370. const x = ( right + left ) * w;
  7371. const y = ( top + bottom ) * h;
  7372. let z, zInv;
  7373. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7374. z = ( far + near ) * p;
  7375. zInv = -2 * p;
  7376. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7377. z = near * p;
  7378. zInv = -1 * p;
  7379. } else {
  7380. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  7381. }
  7382. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  7383. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  7384. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  7385. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  7386. return this;
  7387. }
  7388. /**
  7389. * Returns `true` if this matrix is equal with the given one.
  7390. *
  7391. * @param {Matrix4} matrix - The matrix to test for equality.
  7392. * @return {boolean} Whether this matrix is equal with the given one.
  7393. */
  7394. equals( matrix ) {
  7395. const te = this.elements;
  7396. const me = matrix.elements;
  7397. for ( let i = 0; i < 16; i ++ ) {
  7398. if ( te[ i ] !== me[ i ] ) return false;
  7399. }
  7400. return true;
  7401. }
  7402. /**
  7403. * Sets the elements of the matrix from the given array.
  7404. *
  7405. * @param {Array<number>} array - The matrix elements in column-major order.
  7406. * @param {number} [offset=0] - Index of the first element in the array.
  7407. * @return {Matrix4} A reference to this matrix.
  7408. */
  7409. fromArray( array, offset = 0 ) {
  7410. for ( let i = 0; i < 16; i ++ ) {
  7411. this.elements[ i ] = array[ i + offset ];
  7412. }
  7413. return this;
  7414. }
  7415. /**
  7416. * Writes the elements of this matrix to the given array. If no array is provided,
  7417. * the method returns a new instance.
  7418. *
  7419. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  7420. * @param {number} [offset=0] - Index of the first element in the array.
  7421. * @return {Array<number>} The matrix elements in column-major order.
  7422. */
  7423. toArray( array = [], offset = 0 ) {
  7424. const te = this.elements;
  7425. array[ offset ] = te[ 0 ];
  7426. array[ offset + 1 ] = te[ 1 ];
  7427. array[ offset + 2 ] = te[ 2 ];
  7428. array[ offset + 3 ] = te[ 3 ];
  7429. array[ offset + 4 ] = te[ 4 ];
  7430. array[ offset + 5 ] = te[ 5 ];
  7431. array[ offset + 6 ] = te[ 6 ];
  7432. array[ offset + 7 ] = te[ 7 ];
  7433. array[ offset + 8 ] = te[ 8 ];
  7434. array[ offset + 9 ] = te[ 9 ];
  7435. array[ offset + 10 ] = te[ 10 ];
  7436. array[ offset + 11 ] = te[ 11 ];
  7437. array[ offset + 12 ] = te[ 12 ];
  7438. array[ offset + 13 ] = te[ 13 ];
  7439. array[ offset + 14 ] = te[ 14 ];
  7440. array[ offset + 15 ] = te[ 15 ];
  7441. return array;
  7442. }
  7443. }
  7444. const _v1$5 = /*@__PURE__*/ new Vector3();
  7445. const _m1$2 = /*@__PURE__*/ new Matrix4();
  7446. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  7447. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  7448. const _x = /*@__PURE__*/ new Vector3();
  7449. const _y = /*@__PURE__*/ new Vector3();
  7450. const _z = /*@__PURE__*/ new Vector3();
  7451. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  7452. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  7453. /**
  7454. * A class representing Euler angles.
  7455. *
  7456. * Euler angles describe a rotational transformation by rotating an object on
  7457. * its various axes in specified amounts per axis, and a specified axis
  7458. * order.
  7459. *
  7460. * Iterating through an instance will yield its components (x, y, z,
  7461. * order) in the corresponding order.
  7462. *
  7463. * ```js
  7464. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  7465. * const b = new THREE.Vector3( 1, 0, 1 );
  7466. * b.applyEuler(a);
  7467. * ```
  7468. */
  7469. class Euler {
  7470. /**
  7471. * Constructs a new euler instance.
  7472. *
  7473. * @param {number} [x=0] - The angle of the x axis in radians.
  7474. * @param {number} [y=0] - The angle of the y axis in radians.
  7475. * @param {number} [z=0] - The angle of the z axis in radians.
  7476. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  7477. */
  7478. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  7479. /**
  7480. * This flag can be used for type testing.
  7481. *
  7482. * @type {boolean}
  7483. * @readonly
  7484. * @default true
  7485. */
  7486. this.isEuler = true;
  7487. this._x = x;
  7488. this._y = y;
  7489. this._z = z;
  7490. this._order = order;
  7491. }
  7492. /**
  7493. * The angle of the x axis in radians.
  7494. *
  7495. * @type {number}
  7496. * @default 0
  7497. */
  7498. get x() {
  7499. return this._x;
  7500. }
  7501. set x( value ) {
  7502. this._x = value;
  7503. this._onChangeCallback();
  7504. }
  7505. /**
  7506. * The angle of the y axis in radians.
  7507. *
  7508. * @type {number}
  7509. * @default 0
  7510. */
  7511. get y() {
  7512. return this._y;
  7513. }
  7514. set y( value ) {
  7515. this._y = value;
  7516. this._onChangeCallback();
  7517. }
  7518. /**
  7519. * The angle of the z axis in radians.
  7520. *
  7521. * @type {number}
  7522. * @default 0
  7523. */
  7524. get z() {
  7525. return this._z;
  7526. }
  7527. set z( value ) {
  7528. this._z = value;
  7529. this._onChangeCallback();
  7530. }
  7531. /**
  7532. * A string representing the order that the rotations are applied.
  7533. *
  7534. * @type {string}
  7535. * @default 'XYZ'
  7536. */
  7537. get order() {
  7538. return this._order;
  7539. }
  7540. set order( value ) {
  7541. this._order = value;
  7542. this._onChangeCallback();
  7543. }
  7544. /**
  7545. * Sets the Euler components.
  7546. *
  7547. * @param {number} x - The angle of the x axis in radians.
  7548. * @param {number} y - The angle of the y axis in radians.
  7549. * @param {number} z - The angle of the z axis in radians.
  7550. * @param {string} [order] - A string representing the order that the rotations are applied.
  7551. * @return {Euler} A reference to this Euler instance.
  7552. */
  7553. set( x, y, z, order = this._order ) {
  7554. this._x = x;
  7555. this._y = y;
  7556. this._z = z;
  7557. this._order = order;
  7558. this._onChangeCallback();
  7559. return this;
  7560. }
  7561. /**
  7562. * Returns a new Euler instance with copied values from this instance.
  7563. *
  7564. * @return {Euler} A clone of this instance.
  7565. */
  7566. clone() {
  7567. return new this.constructor( this._x, this._y, this._z, this._order );
  7568. }
  7569. /**
  7570. * Copies the values of the given Euler instance to this instance.
  7571. *
  7572. * @param {Euler} euler - The Euler instance to copy.
  7573. * @return {Euler} A reference to this Euler instance.
  7574. */
  7575. copy( euler ) {
  7576. this._x = euler._x;
  7577. this._y = euler._y;
  7578. this._z = euler._z;
  7579. this._order = euler._order;
  7580. this._onChangeCallback();
  7581. return this;
  7582. }
  7583. /**
  7584. * Sets the angles of this Euler instance from a pure rotation matrix.
  7585. *
  7586. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  7587. * @param {string} [order] - A string representing the order that the rotations are applied.
  7588. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7589. * @return {Euler} A reference to this Euler instance.
  7590. */
  7591. setFromRotationMatrix( m, order = this._order, update = true ) {
  7592. const te = m.elements;
  7593. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  7594. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  7595. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  7596. switch ( order ) {
  7597. case 'XYZ':
  7598. this._y = Math.asin( clamp( m13, -1, 1 ) );
  7599. if ( Math.abs( m13 ) < 0.9999999 ) {
  7600. this._x = Math.atan2( - m23, m33 );
  7601. this._z = Math.atan2( - m12, m11 );
  7602. } else {
  7603. this._x = Math.atan2( m32, m22 );
  7604. this._z = 0;
  7605. }
  7606. break;
  7607. case 'YXZ':
  7608. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  7609. if ( Math.abs( m23 ) < 0.9999999 ) {
  7610. this._y = Math.atan2( m13, m33 );
  7611. this._z = Math.atan2( m21, m22 );
  7612. } else {
  7613. this._y = Math.atan2( - m31, m11 );
  7614. this._z = 0;
  7615. }
  7616. break;
  7617. case 'ZXY':
  7618. this._x = Math.asin( clamp( m32, -1, 1 ) );
  7619. if ( Math.abs( m32 ) < 0.9999999 ) {
  7620. this._y = Math.atan2( - m31, m33 );
  7621. this._z = Math.atan2( - m12, m22 );
  7622. } else {
  7623. this._y = 0;
  7624. this._z = Math.atan2( m21, m11 );
  7625. }
  7626. break;
  7627. case 'ZYX':
  7628. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  7629. if ( Math.abs( m31 ) < 0.9999999 ) {
  7630. this._x = Math.atan2( m32, m33 );
  7631. this._z = Math.atan2( m21, m11 );
  7632. } else {
  7633. this._x = 0;
  7634. this._z = Math.atan2( - m12, m22 );
  7635. }
  7636. break;
  7637. case 'YZX':
  7638. this._z = Math.asin( clamp( m21, -1, 1 ) );
  7639. if ( Math.abs( m21 ) < 0.9999999 ) {
  7640. this._x = Math.atan2( - m23, m22 );
  7641. this._y = Math.atan2( - m31, m11 );
  7642. } else {
  7643. this._x = 0;
  7644. this._y = Math.atan2( m13, m33 );
  7645. }
  7646. break;
  7647. case 'XZY':
  7648. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  7649. if ( Math.abs( m12 ) < 0.9999999 ) {
  7650. this._x = Math.atan2( m32, m22 );
  7651. this._y = Math.atan2( m13, m11 );
  7652. } else {
  7653. this._x = Math.atan2( - m23, m33 );
  7654. this._y = 0;
  7655. }
  7656. break;
  7657. default:
  7658. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  7659. }
  7660. this._order = order;
  7661. if ( update === true ) this._onChangeCallback();
  7662. return this;
  7663. }
  7664. /**
  7665. * Sets the angles of this Euler instance from a normalized quaternion.
  7666. *
  7667. * @param {Quaternion} q - A normalized Quaternion.
  7668. * @param {string} [order] - A string representing the order that the rotations are applied.
  7669. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  7670. * @return {Euler} A reference to this Euler instance.
  7671. */
  7672. setFromQuaternion( q, order, update ) {
  7673. _matrix$2.makeRotationFromQuaternion( q );
  7674. return this.setFromRotationMatrix( _matrix$2, order, update );
  7675. }
  7676. /**
  7677. * Sets the angles of this Euler instance from the given vector.
  7678. *
  7679. * @param {Vector3} v - The vector.
  7680. * @param {string} [order] - A string representing the order that the rotations are applied.
  7681. * @return {Euler} A reference to this Euler instance.
  7682. */
  7683. setFromVector3( v, order = this._order ) {
  7684. return this.set( v.x, v.y, v.z, order );
  7685. }
  7686. /**
  7687. * Resets the euler angle with a new order by creating a quaternion from this
  7688. * euler angle and then setting this euler angle with the quaternion and the
  7689. * new order.
  7690. *
  7691. * Warning: This discards revolution information.
  7692. *
  7693. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  7694. * @return {Euler} A reference to this Euler instance.
  7695. */
  7696. reorder( newOrder ) {
  7697. _quaternion$3.setFromEuler( this );
  7698. return this.setFromQuaternion( _quaternion$3, newOrder );
  7699. }
  7700. /**
  7701. * Returns `true` if this Euler instance is equal with the given one.
  7702. *
  7703. * @param {Euler} euler - The Euler instance to test for equality.
  7704. * @return {boolean} Whether this Euler instance is equal with the given one.
  7705. */
  7706. equals( euler ) {
  7707. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  7708. }
  7709. /**
  7710. * Sets this Euler instance's components to values from the given array. The first three
  7711. * entries of the array are assign to the x,y and z components. An optional fourth entry
  7712. * defines the Euler order.
  7713. *
  7714. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  7715. * @return {Euler} A reference to this Euler instance.
  7716. */
  7717. fromArray( array ) {
  7718. this._x = array[ 0 ];
  7719. this._y = array[ 1 ];
  7720. this._z = array[ 2 ];
  7721. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  7722. this._onChangeCallback();
  7723. return this;
  7724. }
  7725. /**
  7726. * Writes the components of this Euler instance to the given array. If no array is provided,
  7727. * the method returns a new instance.
  7728. *
  7729. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  7730. * @param {number} [offset=0] - Index of the first element in the array.
  7731. * @return {Array<number,number,number,string>} The Euler components.
  7732. */
  7733. toArray( array = [], offset = 0 ) {
  7734. array[ offset ] = this._x;
  7735. array[ offset + 1 ] = this._y;
  7736. array[ offset + 2 ] = this._z;
  7737. array[ offset + 3 ] = this._order;
  7738. return array;
  7739. }
  7740. _onChange( callback ) {
  7741. this._onChangeCallback = callback;
  7742. return this;
  7743. }
  7744. _onChangeCallback() {}
  7745. *[ Symbol.iterator ]() {
  7746. yield this._x;
  7747. yield this._y;
  7748. yield this._z;
  7749. yield this._order;
  7750. }
  7751. }
  7752. /**
  7753. * The default Euler angle order.
  7754. *
  7755. * @static
  7756. * @type {string}
  7757. * @default 'XYZ'
  7758. */
  7759. Euler.DEFAULT_ORDER = 'XYZ';
  7760. class Layers {
  7761. constructor() {
  7762. this.mask = 1 | 0;
  7763. }
  7764. set( channel ) {
  7765. this.mask = ( 1 << channel | 0 ) >>> 0;
  7766. }
  7767. enable( channel ) {
  7768. this.mask |= 1 << channel | 0;
  7769. }
  7770. enableAll() {
  7771. this.mask = 0xffffffff | 0;
  7772. }
  7773. toggle( channel ) {
  7774. this.mask ^= 1 << channel | 0;
  7775. }
  7776. disable( channel ) {
  7777. this.mask &= ~ ( 1 << channel | 0 );
  7778. }
  7779. disableAll() {
  7780. this.mask = 0;
  7781. }
  7782. test( layers ) {
  7783. return ( this.mask & layers.mask ) !== 0;
  7784. }
  7785. isEnabled( channel ) {
  7786. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  7787. }
  7788. }
  7789. let _object3DId = 0;
  7790. const _v1$4 = /*@__PURE__*/ new Vector3();
  7791. const _q1 = /*@__PURE__*/ new Quaternion();
  7792. const _m1$1 = /*@__PURE__*/ new Matrix4();
  7793. const _target = /*@__PURE__*/ new Vector3();
  7794. const _position$3 = /*@__PURE__*/ new Vector3();
  7795. const _scale$2 = /*@__PURE__*/ new Vector3();
  7796. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  7797. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  7798. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  7799. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  7800. /**
  7801. * Fires when the object has been added to its parent object.
  7802. *
  7803. * @event Object3D#added
  7804. * @type {Object}
  7805. */
  7806. const _addedEvent = { type: 'added' };
  7807. /**
  7808. * Fires when the object has been removed from its parent object.
  7809. *
  7810. * @event Object3D#removed
  7811. * @type {Object}
  7812. */
  7813. const _removedEvent = { type: 'removed' };
  7814. /**
  7815. * Fires when a new child object has been added.
  7816. *
  7817. * @event Object3D#childadded
  7818. * @type {Object}
  7819. */
  7820. const _childaddedEvent = { type: 'childadded', child: null };
  7821. /**
  7822. * Fires when a new child object has been added.
  7823. *
  7824. * @event Object3D#childremoved
  7825. * @type {Object}
  7826. */
  7827. const _childremovedEvent = { type: 'childremoved', child: null };
  7828. /**
  7829. * This is the base class for most objects in three.js and provides a set of
  7830. * properties and methods for manipulating objects in 3D space.
  7831. *
  7832. * @augments EventDispatcher
  7833. */
  7834. class Object3D extends EventDispatcher {
  7835. /**
  7836. * Constructs a new 3D object.
  7837. */
  7838. constructor() {
  7839. super();
  7840. /**
  7841. * This flag can be used for type testing.
  7842. *
  7843. * @type {boolean}
  7844. * @readonly
  7845. * @default true
  7846. */
  7847. this.isObject3D = true;
  7848. /**
  7849. * The ID of the 3D object.
  7850. *
  7851. * @name Object3D#id
  7852. * @type {number}
  7853. * @readonly
  7854. */
  7855. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  7856. /**
  7857. * The UUID of the 3D object.
  7858. *
  7859. * @type {string}
  7860. * @readonly
  7861. */
  7862. this.uuid = generateUUID();
  7863. /**
  7864. * The name of the 3D object.
  7865. *
  7866. * @type {string}
  7867. */
  7868. this.name = '';
  7869. /**
  7870. * The type property is used for detecting the object type
  7871. * in context of serialization/deserialization.
  7872. *
  7873. * @type {string}
  7874. * @readonly
  7875. */
  7876. this.type = 'Object3D';
  7877. /**
  7878. * A reference to the parent object.
  7879. *
  7880. * @type {?Object3D}
  7881. * @default null
  7882. */
  7883. this.parent = null;
  7884. /**
  7885. * An array holding the child 3D objects of this instance.
  7886. *
  7887. * @type {Array<Object3D>}
  7888. */
  7889. this.children = [];
  7890. /**
  7891. * Defines the `up` direction of the 3D object which influences
  7892. * the orientation via methods like {@link Object3D#lookAt}.
  7893. *
  7894. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  7895. *
  7896. * @type {Vector3}
  7897. */
  7898. this.up = Object3D.DEFAULT_UP.clone();
  7899. const position = new Vector3();
  7900. const rotation = new Euler();
  7901. const quaternion = new Quaternion();
  7902. const scale = new Vector3( 1, 1, 1 );
  7903. function onRotationChange() {
  7904. quaternion.setFromEuler( rotation, false );
  7905. }
  7906. function onQuaternionChange() {
  7907. rotation.setFromQuaternion( quaternion, undefined, false );
  7908. }
  7909. rotation._onChange( onRotationChange );
  7910. quaternion._onChange( onQuaternionChange );
  7911. Object.defineProperties( this, {
  7912. /**
  7913. * Represents the object's local position.
  7914. *
  7915. * @name Object3D#position
  7916. * @type {Vector3}
  7917. * @default (0,0,0)
  7918. */
  7919. position: {
  7920. configurable: true,
  7921. enumerable: true,
  7922. value: position
  7923. },
  7924. /**
  7925. * Represents the object's local rotation as Euler angles, in radians.
  7926. *
  7927. * @name Object3D#rotation
  7928. * @type {Euler}
  7929. * @default (0,0,0)
  7930. */
  7931. rotation: {
  7932. configurable: true,
  7933. enumerable: true,
  7934. value: rotation
  7935. },
  7936. /**
  7937. * Represents the object's local rotation as Quaternions.
  7938. *
  7939. * @name Object3D#quaternion
  7940. * @type {Quaternion}
  7941. */
  7942. quaternion: {
  7943. configurable: true,
  7944. enumerable: true,
  7945. value: quaternion
  7946. },
  7947. /**
  7948. * Represents the object's local scale.
  7949. *
  7950. * @name Object3D#scale
  7951. * @type {Vector3}
  7952. * @default (1,1,1)
  7953. */
  7954. scale: {
  7955. configurable: true,
  7956. enumerable: true,
  7957. value: scale
  7958. },
  7959. /**
  7960. * Represents the object's model-view matrix.
  7961. *
  7962. * @name Object3D#modelViewMatrix
  7963. * @type {Matrix4}
  7964. */
  7965. modelViewMatrix: {
  7966. value: new Matrix4()
  7967. },
  7968. /**
  7969. * Represents the object's normal matrix.
  7970. *
  7971. * @name Object3D#normalMatrix
  7972. * @type {Matrix3}
  7973. */
  7974. normalMatrix: {
  7975. value: new Matrix3()
  7976. }
  7977. } );
  7978. /**
  7979. * Represents the object's transformation matrix in local space.
  7980. *
  7981. * @type {Matrix4}
  7982. */
  7983. this.matrix = new Matrix4();
  7984. /**
  7985. * Represents the object's transformation matrix in world space.
  7986. * If the 3D object has no parent, then it's identical to the local transformation matrix
  7987. *
  7988. * @type {Matrix4}
  7989. */
  7990. this.matrixWorld = new Matrix4();
  7991. /**
  7992. * When set to `true`, the engine automatically computes the local matrix from position,
  7993. * rotation and scale every frame.
  7994. *
  7995. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  7996. *
  7997. * @type {boolean}
  7998. * @default true
  7999. */
  8000. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  8001. /**
  8002. * When set to `true`, the engine automatically computes the world matrix from the current local
  8003. * matrix and the object's transformation hierarchy.
  8004. *
  8005. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  8006. *
  8007. * @type {boolean}
  8008. * @default true
  8009. */
  8010. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  8011. /**
  8012. * When set to `true`, it calculates the world matrix in that frame and resets this property
  8013. * to `false`.
  8014. *
  8015. * @type {boolean}
  8016. * @default false
  8017. */
  8018. this.matrixWorldNeedsUpdate = false;
  8019. /**
  8020. * The layer membership of the 3D object. The 3D object is only visible if it has
  8021. * at least one layer in common with the camera in use. This property can also be
  8022. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  8023. *
  8024. * @type {Layers}
  8025. */
  8026. this.layers = new Layers();
  8027. /**
  8028. * When set to `true`, the 3D object gets rendered.
  8029. *
  8030. * @type {boolean}
  8031. * @default true
  8032. */
  8033. this.visible = true;
  8034. /**
  8035. * When set to `true`, the 3D object gets rendered into shadow maps.
  8036. *
  8037. * @type {boolean}
  8038. * @default false
  8039. */
  8040. this.castShadow = false;
  8041. /**
  8042. * When set to `true`, the 3D object is affected by shadows in the scene.
  8043. *
  8044. * @type {boolean}
  8045. * @default false
  8046. */
  8047. this.receiveShadow = false;
  8048. /**
  8049. * When set to `true`, the 3D object is honored by view frustum culling.
  8050. *
  8051. * @type {boolean}
  8052. * @default true
  8053. */
  8054. this.frustumCulled = true;
  8055. /**
  8056. * This value allows the default rendering order of scene graph objects to be
  8057. * overridden although opaque and transparent objects remain sorted independently.
  8058. * When this property is set for an instance of {@link Group},all descendants
  8059. * objects will be sorted and rendered together. Sorting is from lowest to highest
  8060. * render order.
  8061. *
  8062. * @type {number}
  8063. * @default 0
  8064. */
  8065. this.renderOrder = 0;
  8066. /**
  8067. * An array holding the animation clips of the 3D object.
  8068. *
  8069. * @type {Array<AnimationClip>}
  8070. */
  8071. this.animations = [];
  8072. /**
  8073. * An object that can be used to store custom data about the 3D object. It
  8074. * should not hold references to functions as these will not be cloned.
  8075. *
  8076. * @type {Object}
  8077. */
  8078. this.userData = {};
  8079. }
  8080. /**
  8081. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  8082. *
  8083. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8084. * @param {Object3D} object - The 3D object.
  8085. * @param {Camera} camera - The camera that is used to render the scene.
  8086. * @param {Camera} shadowCamera - The shadow camera.
  8087. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8088. * @param {Material} depthMaterial - The depth material.
  8089. * @param {Object} group - The geometry group data.
  8090. */
  8091. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8092. /**
  8093. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  8094. *
  8095. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8096. * @param {Object3D} object - The 3D object.
  8097. * @param {Camera} camera - The camera that is used to render the scene.
  8098. * @param {Camera} shadowCamera - The shadow camera.
  8099. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8100. * @param {Material} depthMaterial - The depth material.
  8101. * @param {Object} group - The geometry group data.
  8102. */
  8103. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  8104. /**
  8105. * A callback that is executed immediately before a 3D object is rendered.
  8106. *
  8107. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8108. * @param {Object3D} object - The 3D object.
  8109. * @param {Camera} camera - The camera that is used to render the scene.
  8110. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8111. * @param {Material} material - The 3D object's material.
  8112. * @param {Object} group - The geometry group data.
  8113. */
  8114. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8115. /**
  8116. * A callback that is executed immediately after a 3D object is rendered.
  8117. *
  8118. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  8119. * @param {Object3D} object - The 3D object.
  8120. * @param {Camera} camera - The camera that is used to render the scene.
  8121. * @param {BufferGeometry} geometry - The 3D object's geometry.
  8122. * @param {Material} material - The 3D object's material.
  8123. * @param {Object} group - The geometry group data.
  8124. */
  8125. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  8126. /**
  8127. * Applies the given transformation matrix to the object and updates the object's position,
  8128. * rotation and scale.
  8129. *
  8130. * @param {Matrix4} matrix - The transformation matrix.
  8131. */
  8132. applyMatrix4( matrix ) {
  8133. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8134. this.matrix.premultiply( matrix );
  8135. this.matrix.decompose( this.position, this.quaternion, this.scale );
  8136. }
  8137. /**
  8138. * Applies a rotation represented by given the quaternion to the 3D object.
  8139. *
  8140. * @param {Quaternion} q - The quaternion.
  8141. * @return {Object3D} A reference to this instance.
  8142. */
  8143. applyQuaternion( q ) {
  8144. this.quaternion.premultiply( q );
  8145. return this;
  8146. }
  8147. /**
  8148. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  8149. *
  8150. * @param {Vector3} axis - The (normalized) axis vector.
  8151. * @param {number} angle - The angle in radians.
  8152. */
  8153. setRotationFromAxisAngle( axis, angle ) {
  8154. // assumes axis is normalized
  8155. this.quaternion.setFromAxisAngle( axis, angle );
  8156. }
  8157. /**
  8158. * Sets the given rotation represented as Euler angles to the 3D object.
  8159. *
  8160. * @param {Euler} euler - The Euler angles.
  8161. */
  8162. setRotationFromEuler( euler ) {
  8163. this.quaternion.setFromEuler( euler, true );
  8164. }
  8165. /**
  8166. * Sets the given rotation represented as rotation matrix to the 3D object.
  8167. *
  8168. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  8169. * a pure rotation matrix (i.e, unscaled).
  8170. */
  8171. setRotationFromMatrix( m ) {
  8172. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  8173. this.quaternion.setFromRotationMatrix( m );
  8174. }
  8175. /**
  8176. * Sets the given rotation represented as a Quaternion to the 3D object.
  8177. *
  8178. * @param {Quaternion} q - The Quaternion
  8179. */
  8180. setRotationFromQuaternion( q ) {
  8181. // assumes q is normalized
  8182. this.quaternion.copy( q );
  8183. }
  8184. /**
  8185. * Rotates the 3D object along an axis in local space.
  8186. *
  8187. * @param {Vector3} axis - The (normalized) axis vector.
  8188. * @param {number} angle - The angle in radians.
  8189. * @return {Object3D} A reference to this instance.
  8190. */
  8191. rotateOnAxis( axis, angle ) {
  8192. // rotate object on axis in object space
  8193. // axis is assumed to be normalized
  8194. _q1.setFromAxisAngle( axis, angle );
  8195. this.quaternion.multiply( _q1 );
  8196. return this;
  8197. }
  8198. /**
  8199. * Rotates the 3D object along an axis in world space.
  8200. *
  8201. * @param {Vector3} axis - The (normalized) axis vector.
  8202. * @param {number} angle - The angle in radians.
  8203. * @return {Object3D} A reference to this instance.
  8204. */
  8205. rotateOnWorldAxis( axis, angle ) {
  8206. // rotate object on axis in world space
  8207. // axis is assumed to be normalized
  8208. // method assumes no rotated parent
  8209. _q1.setFromAxisAngle( axis, angle );
  8210. this.quaternion.premultiply( _q1 );
  8211. return this;
  8212. }
  8213. /**
  8214. * Rotates the 3D object around its X axis in local space.
  8215. *
  8216. * @param {number} angle - The angle in radians.
  8217. * @return {Object3D} A reference to this instance.
  8218. */
  8219. rotateX( angle ) {
  8220. return this.rotateOnAxis( _xAxis, angle );
  8221. }
  8222. /**
  8223. * Rotates the 3D object around its Y axis in local space.
  8224. *
  8225. * @param {number} angle - The angle in radians.
  8226. * @return {Object3D} A reference to this instance.
  8227. */
  8228. rotateY( angle ) {
  8229. return this.rotateOnAxis( _yAxis, angle );
  8230. }
  8231. /**
  8232. * Rotates the 3D object around its Z axis in local space.
  8233. *
  8234. * @param {number} angle - The angle in radians.
  8235. * @return {Object3D} A reference to this instance.
  8236. */
  8237. rotateZ( angle ) {
  8238. return this.rotateOnAxis( _zAxis, angle );
  8239. }
  8240. /**
  8241. * Translate the 3D object by a distance along the given axis in local space.
  8242. *
  8243. * @param {Vector3} axis - The (normalized) axis vector.
  8244. * @param {number} distance - The distance in world units.
  8245. * @return {Object3D} A reference to this instance.
  8246. */
  8247. translateOnAxis( axis, distance ) {
  8248. // translate object by distance along axis in object space
  8249. // axis is assumed to be normalized
  8250. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  8251. this.position.add( _v1$4.multiplyScalar( distance ) );
  8252. return this;
  8253. }
  8254. /**
  8255. * Translate the 3D object by a distance along its X-axis in local space.
  8256. *
  8257. * @param {number} distance - The distance in world units.
  8258. * @return {Object3D} A reference to this instance.
  8259. */
  8260. translateX( distance ) {
  8261. return this.translateOnAxis( _xAxis, distance );
  8262. }
  8263. /**
  8264. * Translate the 3D object by a distance along its Y-axis in local space.
  8265. *
  8266. * @param {number} distance - The distance in world units.
  8267. * @return {Object3D} A reference to this instance.
  8268. */
  8269. translateY( distance ) {
  8270. return this.translateOnAxis( _yAxis, distance );
  8271. }
  8272. /**
  8273. * Translate the 3D object by a distance along its Z-axis in local space.
  8274. *
  8275. * @param {number} distance - The distance in world units.
  8276. * @return {Object3D} A reference to this instance.
  8277. */
  8278. translateZ( distance ) {
  8279. return this.translateOnAxis( _zAxis, distance );
  8280. }
  8281. /**
  8282. * Converts the given vector from this 3D object's local space to world space.
  8283. *
  8284. * @param {Vector3} vector - The vector to convert.
  8285. * @return {Vector3} The converted vector.
  8286. */
  8287. localToWorld( vector ) {
  8288. this.updateWorldMatrix( true, false );
  8289. return vector.applyMatrix4( this.matrixWorld );
  8290. }
  8291. /**
  8292. * Converts the given vector from this 3D object's word space to local space.
  8293. *
  8294. * @param {Vector3} vector - The vector to convert.
  8295. * @return {Vector3} The converted vector.
  8296. */
  8297. worldToLocal( vector ) {
  8298. this.updateWorldMatrix( true, false );
  8299. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  8300. }
  8301. /**
  8302. * Rotates the object to face a point in world space.
  8303. *
  8304. * This method does not support objects having non-uniformly-scaled parent(s).
  8305. *
  8306. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  8307. * @param {number} [y] - The y coordinate in world space.
  8308. * @param {number} [z] - The z coordinate in world space.
  8309. */
  8310. lookAt( x, y, z ) {
  8311. // This method does not support objects having non-uniformly-scaled parent(s)
  8312. if ( x.isVector3 ) {
  8313. _target.copy( x );
  8314. } else {
  8315. _target.set( x, y, z );
  8316. }
  8317. const parent = this.parent;
  8318. this.updateWorldMatrix( true, false );
  8319. _position$3.setFromMatrixPosition( this.matrixWorld );
  8320. if ( this.isCamera || this.isLight ) {
  8321. _m1$1.lookAt( _position$3, _target, this.up );
  8322. } else {
  8323. _m1$1.lookAt( _target, _position$3, this.up );
  8324. }
  8325. this.quaternion.setFromRotationMatrix( _m1$1 );
  8326. if ( parent ) {
  8327. _m1$1.extractRotation( parent.matrixWorld );
  8328. _q1.setFromRotationMatrix( _m1$1 );
  8329. this.quaternion.premultiply( _q1.invert() );
  8330. }
  8331. }
  8332. /**
  8333. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  8334. * objects may be added. Any current parent on an object passed in here will be
  8335. * removed, since an object can have at most one parent.
  8336. *
  8337. * @fires Object3D#added
  8338. * @fires Object3D#childadded
  8339. * @param {Object3D} object - The 3D object to add.
  8340. * @return {Object3D} A reference to this instance.
  8341. */
  8342. add( object ) {
  8343. if ( arguments.length > 1 ) {
  8344. for ( let i = 0; i < arguments.length; i ++ ) {
  8345. this.add( arguments[ i ] );
  8346. }
  8347. return this;
  8348. }
  8349. if ( object === this ) {
  8350. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  8351. return this;
  8352. }
  8353. if ( object && object.isObject3D ) {
  8354. object.removeFromParent();
  8355. object.parent = this;
  8356. this.children.push( object );
  8357. object.dispatchEvent( _addedEvent );
  8358. _childaddedEvent.child = object;
  8359. this.dispatchEvent( _childaddedEvent );
  8360. _childaddedEvent.child = null;
  8361. } else {
  8362. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  8363. }
  8364. return this;
  8365. }
  8366. /**
  8367. * Removes the given 3D object as child from this 3D object.
  8368. * An arbitrary number of objects may be removed.
  8369. *
  8370. * @fires Object3D#removed
  8371. * @fires Object3D#childremoved
  8372. * @param {Object3D} object - The 3D object to remove.
  8373. * @return {Object3D} A reference to this instance.
  8374. */
  8375. remove( object ) {
  8376. if ( arguments.length > 1 ) {
  8377. for ( let i = 0; i < arguments.length; i ++ ) {
  8378. this.remove( arguments[ i ] );
  8379. }
  8380. return this;
  8381. }
  8382. const index = this.children.indexOf( object );
  8383. if ( index !== -1 ) {
  8384. object.parent = null;
  8385. this.children.splice( index, 1 );
  8386. object.dispatchEvent( _removedEvent );
  8387. _childremovedEvent.child = object;
  8388. this.dispatchEvent( _childremovedEvent );
  8389. _childremovedEvent.child = null;
  8390. }
  8391. return this;
  8392. }
  8393. /**
  8394. * Removes this 3D object from its current parent.
  8395. *
  8396. * @fires Object3D#removed
  8397. * @fires Object3D#childremoved
  8398. * @return {Object3D} A reference to this instance.
  8399. */
  8400. removeFromParent() {
  8401. const parent = this.parent;
  8402. if ( parent !== null ) {
  8403. parent.remove( this );
  8404. }
  8405. return this;
  8406. }
  8407. /**
  8408. * Removes all child objects.
  8409. *
  8410. * @fires Object3D#removed
  8411. * @fires Object3D#childremoved
  8412. * @return {Object3D} A reference to this instance.
  8413. */
  8414. clear() {
  8415. return this.remove( ... this.children );
  8416. }
  8417. /**
  8418. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  8419. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  8420. *
  8421. * @fires Object3D#added
  8422. * @fires Object3D#childadded
  8423. * @param {Object3D} object - The 3D object to attach.
  8424. * @return {Object3D} A reference to this instance.
  8425. */
  8426. attach( object ) {
  8427. // adds object as a child of this, while maintaining the object's world transform
  8428. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  8429. this.updateWorldMatrix( true, false );
  8430. _m1$1.copy( this.matrixWorld ).invert();
  8431. if ( object.parent !== null ) {
  8432. object.parent.updateWorldMatrix( true, false );
  8433. _m1$1.multiply( object.parent.matrixWorld );
  8434. }
  8435. object.applyMatrix4( _m1$1 );
  8436. object.removeFromParent();
  8437. object.parent = this;
  8438. this.children.push( object );
  8439. object.updateWorldMatrix( false, true );
  8440. object.dispatchEvent( _addedEvent );
  8441. _childaddedEvent.child = object;
  8442. this.dispatchEvent( _childaddedEvent );
  8443. _childaddedEvent.child = null;
  8444. return this;
  8445. }
  8446. /**
  8447. * Searches through the 3D object and its children, starting with the 3D object
  8448. * itself, and returns the first with a matching ID.
  8449. *
  8450. * @param {number} id - The id.
  8451. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8452. */
  8453. getObjectById( id ) {
  8454. return this.getObjectByProperty( 'id', id );
  8455. }
  8456. /**
  8457. * Searches through the 3D object and its children, starting with the 3D object
  8458. * itself, and returns the first with a matching name.
  8459. *
  8460. * @param {string} name - The name.
  8461. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8462. */
  8463. getObjectByName( name ) {
  8464. return this.getObjectByProperty( 'name', name );
  8465. }
  8466. /**
  8467. * Searches through the 3D object and its children, starting with the 3D object
  8468. * itself, and returns the first with a matching property value.
  8469. *
  8470. * @param {string} name - The name of the property.
  8471. * @param {any} value - The value.
  8472. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  8473. */
  8474. getObjectByProperty( name, value ) {
  8475. if ( this[ name ] === value ) return this;
  8476. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  8477. const child = this.children[ i ];
  8478. const object = child.getObjectByProperty( name, value );
  8479. if ( object !== undefined ) {
  8480. return object;
  8481. }
  8482. }
  8483. return undefined;
  8484. }
  8485. /**
  8486. * Searches through the 3D object and its children, starting with the 3D object
  8487. * itself, and returns all 3D objects with a matching property value.
  8488. *
  8489. * @param {string} name - The name of the property.
  8490. * @param {any} value - The value.
  8491. * @param {Array<Object3D>} result - The method stores the result in this array.
  8492. * @return {Array<Object3D>} The found 3D objects.
  8493. */
  8494. getObjectsByProperty( name, value, result = [] ) {
  8495. if ( this[ name ] === value ) result.push( this );
  8496. const children = this.children;
  8497. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8498. children[ i ].getObjectsByProperty( name, value, result );
  8499. }
  8500. return result;
  8501. }
  8502. /**
  8503. * Returns a vector representing the position of the 3D object in world space.
  8504. *
  8505. * @param {Vector3} target - The target vector the result is stored to.
  8506. * @return {Vector3} The 3D object's position in world space.
  8507. */
  8508. getWorldPosition( target ) {
  8509. this.updateWorldMatrix( true, false );
  8510. return target.setFromMatrixPosition( this.matrixWorld );
  8511. }
  8512. /**
  8513. * Returns a Quaternion representing the position of the 3D object in world space.
  8514. *
  8515. * @param {Quaternion} target - The target Quaternion the result is stored to.
  8516. * @return {Quaternion} The 3D object's rotation in world space.
  8517. */
  8518. getWorldQuaternion( target ) {
  8519. this.updateWorldMatrix( true, false );
  8520. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  8521. return target;
  8522. }
  8523. /**
  8524. * Returns a vector representing the scale of the 3D object in world space.
  8525. *
  8526. * @param {Vector3} target - The target vector the result is stored to.
  8527. * @return {Vector3} The 3D object's scale in world space.
  8528. */
  8529. getWorldScale( target ) {
  8530. this.updateWorldMatrix( true, false );
  8531. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  8532. return target;
  8533. }
  8534. /**
  8535. * Returns a vector representing the ("look") direction of the 3D object in world space.
  8536. *
  8537. * @param {Vector3} target - The target vector the result is stored to.
  8538. * @return {Vector3} The 3D object's direction in world space.
  8539. */
  8540. getWorldDirection( target ) {
  8541. this.updateWorldMatrix( true, false );
  8542. const e = this.matrixWorld.elements;
  8543. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  8544. }
  8545. /**
  8546. * Abstract method to get intersections between a casted ray and this
  8547. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  8548. * implement this method in order to use raycasting.
  8549. *
  8550. * @abstract
  8551. * @param {Raycaster} raycaster - The raycaster.
  8552. * @param {Array<Object>} intersects - An array holding the result of the method.
  8553. */
  8554. raycast( /* raycaster, intersects */ ) {}
  8555. /**
  8556. * Executes the callback on this 3D object and all descendants.
  8557. *
  8558. * Note: Modifying the scene graph inside the callback is discouraged.
  8559. *
  8560. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8561. */
  8562. traverse( callback ) {
  8563. callback( this );
  8564. const children = this.children;
  8565. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8566. children[ i ].traverse( callback );
  8567. }
  8568. }
  8569. /**
  8570. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  8571. * Descendants of invisible 3D objects are not traversed.
  8572. *
  8573. * Note: Modifying the scene graph inside the callback is discouraged.
  8574. *
  8575. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8576. */
  8577. traverseVisible( callback ) {
  8578. if ( this.visible === false ) return;
  8579. callback( this );
  8580. const children = this.children;
  8581. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8582. children[ i ].traverseVisible( callback );
  8583. }
  8584. }
  8585. /**
  8586. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  8587. *
  8588. * Note: Modifying the scene graph inside the callback is discouraged.
  8589. *
  8590. * @param {Function} callback - A callback function that allows to process the current 3D object.
  8591. */
  8592. traverseAncestors( callback ) {
  8593. const parent = this.parent;
  8594. if ( parent !== null ) {
  8595. callback( parent );
  8596. parent.traverseAncestors( callback );
  8597. }
  8598. }
  8599. /**
  8600. * Updates the transformation matrix in local space by computing it from the current
  8601. * position, rotation and scale values.
  8602. */
  8603. updateMatrix() {
  8604. this.matrix.compose( this.position, this.quaternion, this.scale );
  8605. this.matrixWorldNeedsUpdate = true;
  8606. }
  8607. /**
  8608. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  8609. *
  8610. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  8611. * local space. The computation of the local and world matrix can be controlled with the
  8612. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  8613. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  8614. *
  8615. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  8616. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  8617. */
  8618. updateMatrixWorld( force ) {
  8619. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8620. if ( this.matrixWorldNeedsUpdate || force ) {
  8621. if ( this.matrixWorldAutoUpdate === true ) {
  8622. if ( this.parent === null ) {
  8623. this.matrixWorld.copy( this.matrix );
  8624. } else {
  8625. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8626. }
  8627. }
  8628. this.matrixWorldNeedsUpdate = false;
  8629. force = true;
  8630. }
  8631. // make sure descendants are updated if required
  8632. const children = this.children;
  8633. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8634. const child = children[ i ];
  8635. child.updateMatrixWorld( force );
  8636. }
  8637. }
  8638. /**
  8639. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  8640. * update of ancestor and descendant nodes.
  8641. *
  8642. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  8643. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  8644. */
  8645. updateWorldMatrix( updateParents, updateChildren ) {
  8646. const parent = this.parent;
  8647. if ( updateParents === true && parent !== null ) {
  8648. parent.updateWorldMatrix( true, false );
  8649. }
  8650. if ( this.matrixAutoUpdate ) this.updateMatrix();
  8651. if ( this.matrixWorldAutoUpdate === true ) {
  8652. if ( this.parent === null ) {
  8653. this.matrixWorld.copy( this.matrix );
  8654. } else {
  8655. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8656. }
  8657. }
  8658. // make sure descendants are updated
  8659. if ( updateChildren === true ) {
  8660. const children = this.children;
  8661. for ( let i = 0, l = children.length; i < l; i ++ ) {
  8662. const child = children[ i ];
  8663. child.updateWorldMatrix( false, true );
  8664. }
  8665. }
  8666. }
  8667. /**
  8668. * Serializes the 3D object into JSON.
  8669. *
  8670. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  8671. * @return {Object} A JSON object representing the serialized 3D object.
  8672. * @see {@link ObjectLoader#parse}
  8673. */
  8674. toJSON( meta ) {
  8675. // meta is a string when called from JSON.stringify
  8676. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  8677. const output = {};
  8678. // meta is a hash used to collect geometries, materials.
  8679. // not providing it implies that this is the root object
  8680. // being serialized.
  8681. if ( isRootObject ) {
  8682. // initialize meta obj
  8683. meta = {
  8684. geometries: {},
  8685. materials: {},
  8686. textures: {},
  8687. images: {},
  8688. shapes: {},
  8689. skeletons: {},
  8690. animations: {},
  8691. nodes: {}
  8692. };
  8693. output.metadata = {
  8694. version: 4.6,
  8695. type: 'Object',
  8696. generator: 'Object3D.toJSON'
  8697. };
  8698. }
  8699. // standard Object3D serialization
  8700. const object = {};
  8701. object.uuid = this.uuid;
  8702. object.type = this.type;
  8703. if ( this.name !== '' ) object.name = this.name;
  8704. if ( this.castShadow === true ) object.castShadow = true;
  8705. if ( this.receiveShadow === true ) object.receiveShadow = true;
  8706. if ( this.visible === false ) object.visible = false;
  8707. if ( this.frustumCulled === false ) object.frustumCulled = false;
  8708. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  8709. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  8710. object.layers = this.layers.mask;
  8711. object.matrix = this.matrix.toArray();
  8712. object.up = this.up.toArray();
  8713. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  8714. // object specific properties
  8715. if ( this.isInstancedMesh ) {
  8716. object.type = 'InstancedMesh';
  8717. object.count = this.count;
  8718. object.instanceMatrix = this.instanceMatrix.toJSON();
  8719. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  8720. }
  8721. if ( this.isBatchedMesh ) {
  8722. object.type = 'BatchedMesh';
  8723. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  8724. object.sortObjects = this.sortObjects;
  8725. object.drawRanges = this._drawRanges;
  8726. object.reservedRanges = this._reservedRanges;
  8727. object.visibility = this._visibility;
  8728. object.active = this._active;
  8729. object.bounds = this._bounds.map( bound => ( {
  8730. boxInitialized: bound.boxInitialized,
  8731. boxMin: bound.box.min.toArray(),
  8732. boxMax: bound.box.max.toArray(),
  8733. sphereInitialized: bound.sphereInitialized,
  8734. sphereRadius: bound.sphere.radius,
  8735. sphereCenter: bound.sphere.center.toArray()
  8736. } ) );
  8737. object.maxInstanceCount = this._maxInstanceCount;
  8738. object.maxVertexCount = this._maxVertexCount;
  8739. object.maxIndexCount = this._maxIndexCount;
  8740. object.geometryInitialized = this._geometryInitialized;
  8741. object.geometryCount = this._geometryCount;
  8742. object.matricesTexture = this._matricesTexture.toJSON( meta );
  8743. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  8744. if ( this.boundingSphere !== null ) {
  8745. object.boundingSphere = {
  8746. center: object.boundingSphere.center.toArray(),
  8747. radius: object.boundingSphere.radius
  8748. };
  8749. }
  8750. if ( this.boundingBox !== null ) {
  8751. object.boundingBox = {
  8752. min: object.boundingBox.min.toArray(),
  8753. max: object.boundingBox.max.toArray()
  8754. };
  8755. }
  8756. }
  8757. //
  8758. function serialize( library, element ) {
  8759. if ( library[ element.uuid ] === undefined ) {
  8760. library[ element.uuid ] = element.toJSON( meta );
  8761. }
  8762. return element.uuid;
  8763. }
  8764. if ( this.isScene ) {
  8765. if ( this.background ) {
  8766. if ( this.background.isColor ) {
  8767. object.background = this.background.toJSON();
  8768. } else if ( this.background.isTexture ) {
  8769. object.background = this.background.toJSON( meta ).uuid;
  8770. }
  8771. }
  8772. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  8773. object.environment = this.environment.toJSON( meta ).uuid;
  8774. }
  8775. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  8776. object.geometry = serialize( meta.geometries, this.geometry );
  8777. const parameters = this.geometry.parameters;
  8778. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  8779. const shapes = parameters.shapes;
  8780. if ( Array.isArray( shapes ) ) {
  8781. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  8782. const shape = shapes[ i ];
  8783. serialize( meta.shapes, shape );
  8784. }
  8785. } else {
  8786. serialize( meta.shapes, shapes );
  8787. }
  8788. }
  8789. }
  8790. if ( this.isSkinnedMesh ) {
  8791. object.bindMode = this.bindMode;
  8792. object.bindMatrix = this.bindMatrix.toArray();
  8793. if ( this.skeleton !== undefined ) {
  8794. serialize( meta.skeletons, this.skeleton );
  8795. object.skeleton = this.skeleton.uuid;
  8796. }
  8797. }
  8798. if ( this.material !== undefined ) {
  8799. if ( Array.isArray( this.material ) ) {
  8800. const uuids = [];
  8801. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  8802. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  8803. }
  8804. object.material = uuids;
  8805. } else {
  8806. object.material = serialize( meta.materials, this.material );
  8807. }
  8808. }
  8809. //
  8810. if ( this.children.length > 0 ) {
  8811. object.children = [];
  8812. for ( let i = 0; i < this.children.length; i ++ ) {
  8813. object.children.push( this.children[ i ].toJSON( meta ).object );
  8814. }
  8815. }
  8816. //
  8817. if ( this.animations.length > 0 ) {
  8818. object.animations = [];
  8819. for ( let i = 0; i < this.animations.length; i ++ ) {
  8820. const animation = this.animations[ i ];
  8821. object.animations.push( serialize( meta.animations, animation ) );
  8822. }
  8823. }
  8824. if ( isRootObject ) {
  8825. const geometries = extractFromCache( meta.geometries );
  8826. const materials = extractFromCache( meta.materials );
  8827. const textures = extractFromCache( meta.textures );
  8828. const images = extractFromCache( meta.images );
  8829. const shapes = extractFromCache( meta.shapes );
  8830. const skeletons = extractFromCache( meta.skeletons );
  8831. const animations = extractFromCache( meta.animations );
  8832. const nodes = extractFromCache( meta.nodes );
  8833. if ( geometries.length > 0 ) output.geometries = geometries;
  8834. if ( materials.length > 0 ) output.materials = materials;
  8835. if ( textures.length > 0 ) output.textures = textures;
  8836. if ( images.length > 0 ) output.images = images;
  8837. if ( shapes.length > 0 ) output.shapes = shapes;
  8838. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  8839. if ( animations.length > 0 ) output.animations = animations;
  8840. if ( nodes.length > 0 ) output.nodes = nodes;
  8841. }
  8842. output.object = object;
  8843. return output;
  8844. // extract data from the cache hash
  8845. // remove metadata on each item
  8846. // and return as array
  8847. function extractFromCache( cache ) {
  8848. const values = [];
  8849. for ( const key in cache ) {
  8850. const data = cache[ key ];
  8851. delete data.metadata;
  8852. values.push( data );
  8853. }
  8854. return values;
  8855. }
  8856. }
  8857. /**
  8858. * Returns a new 3D object with copied values from this instance.
  8859. *
  8860. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  8861. * @return {Object3D} A clone of this instance.
  8862. */
  8863. clone( recursive ) {
  8864. return new this.constructor().copy( this, recursive );
  8865. }
  8866. /**
  8867. * Copies the values of the given 3D object to this instance.
  8868. *
  8869. * @param {Object3D} source - The 3D object to copy.
  8870. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  8871. * @return {Object3D} A reference to this instance.
  8872. */
  8873. copy( source, recursive = true ) {
  8874. this.name = source.name;
  8875. this.up.copy( source.up );
  8876. this.position.copy( source.position );
  8877. this.rotation.order = source.rotation.order;
  8878. this.quaternion.copy( source.quaternion );
  8879. this.scale.copy( source.scale );
  8880. this.matrix.copy( source.matrix );
  8881. this.matrixWorld.copy( source.matrixWorld );
  8882. this.matrixAutoUpdate = source.matrixAutoUpdate;
  8883. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  8884. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  8885. this.layers.mask = source.layers.mask;
  8886. this.visible = source.visible;
  8887. this.castShadow = source.castShadow;
  8888. this.receiveShadow = source.receiveShadow;
  8889. this.frustumCulled = source.frustumCulled;
  8890. this.renderOrder = source.renderOrder;
  8891. this.animations = source.animations.slice();
  8892. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  8893. if ( recursive === true ) {
  8894. for ( let i = 0; i < source.children.length; i ++ ) {
  8895. const child = source.children[ i ];
  8896. this.add( child.clone() );
  8897. }
  8898. }
  8899. return this;
  8900. }
  8901. }
  8902. /**
  8903. * The default up direction for objects, also used as the default
  8904. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  8905. *
  8906. * @static
  8907. * @type {Vector3}
  8908. * @default (0,1,0)
  8909. */
  8910. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  8911. /**
  8912. * The default setting for {@link Object3D#matrixAutoUpdate} for
  8913. * newly created 3D objects.
  8914. *
  8915. * @static
  8916. * @type {boolean}
  8917. * @default true
  8918. */
  8919. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  8920. /**
  8921. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  8922. * newly created 3D objects.
  8923. *
  8924. * @static
  8925. * @type {boolean}
  8926. * @default true
  8927. */
  8928. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  8929. const _v0$1 = /*@__PURE__*/ new Vector3();
  8930. const _v1$3 = /*@__PURE__*/ new Vector3();
  8931. const _v2$2 = /*@__PURE__*/ new Vector3();
  8932. const _v3$2 = /*@__PURE__*/ new Vector3();
  8933. const _vab = /*@__PURE__*/ new Vector3();
  8934. const _vac = /*@__PURE__*/ new Vector3();
  8935. const _vbc = /*@__PURE__*/ new Vector3();
  8936. const _vap = /*@__PURE__*/ new Vector3();
  8937. const _vbp = /*@__PURE__*/ new Vector3();
  8938. const _vcp = /*@__PURE__*/ new Vector3();
  8939. const _v40 = /*@__PURE__*/ new Vector4();
  8940. const _v41 = /*@__PURE__*/ new Vector4();
  8941. const _v42 = /*@__PURE__*/ new Vector4();
  8942. /**
  8943. * A geometric triangle as defined by three vectors representing its three corners.
  8944. */
  8945. class Triangle {
  8946. /**
  8947. * Constructs a new triangle.
  8948. *
  8949. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  8950. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  8951. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  8952. */
  8953. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  8954. /**
  8955. * The first corner of the triangle.
  8956. *
  8957. * @type {Vector3}
  8958. */
  8959. this.a = a;
  8960. /**
  8961. * The second corner of the triangle.
  8962. *
  8963. * @type {Vector3}
  8964. */
  8965. this.b = b;
  8966. /**
  8967. * The third corner of the triangle.
  8968. *
  8969. * @type {Vector3}
  8970. */
  8971. this.c = c;
  8972. }
  8973. /**
  8974. * Computes the normal vector of a triangle.
  8975. *
  8976. * @param {Vector3} a - The first corner of the triangle.
  8977. * @param {Vector3} b - The second corner of the triangle.
  8978. * @param {Vector3} c - The third corner of the triangle.
  8979. * @param {Vector3} target - The target vector that is used to store the method's result.
  8980. * @return {Vector3} The triangle's normal.
  8981. */
  8982. static getNormal( a, b, c, target ) {
  8983. target.subVectors( c, b );
  8984. _v0$1.subVectors( a, b );
  8985. target.cross( _v0$1 );
  8986. const targetLengthSq = target.lengthSq();
  8987. if ( targetLengthSq > 0 ) {
  8988. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  8989. }
  8990. return target.set( 0, 0, 0 );
  8991. }
  8992. /**
  8993. * Computes a barycentric coordinates from the given vector.
  8994. * Returns `null` if the triangle is degenerate.
  8995. *
  8996. * @param {Vector3} point - A point in 3D space.
  8997. * @param {Vector3} a - The first corner of the triangle.
  8998. * @param {Vector3} b - The second corner of the triangle.
  8999. * @param {Vector3} c - The third corner of the triangle.
  9000. * @param {Vector3} target - The target vector that is used to store the method's result.
  9001. * @return {?Vector3} The barycentric coordinates for the given point
  9002. */
  9003. static getBarycoord( point, a, b, c, target ) {
  9004. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  9005. _v0$1.subVectors( c, a );
  9006. _v1$3.subVectors( b, a );
  9007. _v2$2.subVectors( point, a );
  9008. const dot00 = _v0$1.dot( _v0$1 );
  9009. const dot01 = _v0$1.dot( _v1$3 );
  9010. const dot02 = _v0$1.dot( _v2$2 );
  9011. const dot11 = _v1$3.dot( _v1$3 );
  9012. const dot12 = _v1$3.dot( _v2$2 );
  9013. const denom = ( dot00 * dot11 - dot01 * dot01 );
  9014. // collinear or singular triangle
  9015. if ( denom === 0 ) {
  9016. target.set( 0, 0, 0 );
  9017. return null;
  9018. }
  9019. const invDenom = 1 / denom;
  9020. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  9021. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  9022. // barycentric coordinates must always sum to 1
  9023. return target.set( 1 - u - v, v, u );
  9024. }
  9025. /**
  9026. * Returns `true` if the given point, when projected onto the plane of the
  9027. * triangle, lies within the triangle.
  9028. *
  9029. * @param {Vector3} point - The point in 3D space to test.
  9030. * @param {Vector3} a - The first corner of the triangle.
  9031. * @param {Vector3} b - The second corner of the triangle.
  9032. * @param {Vector3} c - The third corner of the triangle.
  9033. * @return {boolean} Whether the given point, when projected onto the plane of the
  9034. * triangle, lies within the triangle or not.
  9035. */
  9036. static containsPoint( point, a, b, c ) {
  9037. // if the triangle is degenerate then we can't contain a point
  9038. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  9039. return false;
  9040. }
  9041. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  9042. }
  9043. /**
  9044. * Computes the value barycentrically interpolated for the given point on the
  9045. * triangle. Returns `null` if the triangle is degenerate.
  9046. *
  9047. * @param {Vector3} point - Position of interpolated point.
  9048. * @param {Vector3} p1 - The first corner of the triangle.
  9049. * @param {Vector3} p2 - The second corner of the triangle.
  9050. * @param {Vector3} p3 - The third corner of the triangle.
  9051. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9052. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9053. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9054. * @param {Vector3} target - The target vector that is used to store the method's result.
  9055. * @return {?Vector3} The interpolated value.
  9056. */
  9057. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  9058. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  9059. target.x = 0;
  9060. target.y = 0;
  9061. if ( 'z' in target ) target.z = 0;
  9062. if ( 'w' in target ) target.w = 0;
  9063. return null;
  9064. }
  9065. target.setScalar( 0 );
  9066. target.addScaledVector( v1, _v3$2.x );
  9067. target.addScaledVector( v2, _v3$2.y );
  9068. target.addScaledVector( v3, _v3$2.z );
  9069. return target;
  9070. }
  9071. /**
  9072. * Computes the value barycentrically interpolated for the given attribute and indices.
  9073. *
  9074. * @param {BufferAttribute} attr - The attribute to interpolate.
  9075. * @param {number} i1 - Index of first vertex.
  9076. * @param {number} i2 - Index of second vertex.
  9077. * @param {number} i3 - Index of third vertex.
  9078. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  9079. * @param {Vector3} target - The target vector that is used to store the method's result.
  9080. * @return {Vector3} The interpolated attribute value.
  9081. */
  9082. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  9083. _v40.setScalar( 0 );
  9084. _v41.setScalar( 0 );
  9085. _v42.setScalar( 0 );
  9086. _v40.fromBufferAttribute( attr, i1 );
  9087. _v41.fromBufferAttribute( attr, i2 );
  9088. _v42.fromBufferAttribute( attr, i3 );
  9089. target.setScalar( 0 );
  9090. target.addScaledVector( _v40, barycoord.x );
  9091. target.addScaledVector( _v41, barycoord.y );
  9092. target.addScaledVector( _v42, barycoord.z );
  9093. return target;
  9094. }
  9095. /**
  9096. * Returns `true` if the triangle is oriented towards the given direction.
  9097. *
  9098. * @param {Vector3} a - The first corner of the triangle.
  9099. * @param {Vector3} b - The second corner of the triangle.
  9100. * @param {Vector3} c - The third corner of the triangle.
  9101. * @param {Vector3} direction - The (normalized) direction vector.
  9102. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9103. */
  9104. static isFrontFacing( a, b, c, direction ) {
  9105. _v0$1.subVectors( c, b );
  9106. _v1$3.subVectors( a, b );
  9107. // strictly front facing
  9108. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  9109. }
  9110. /**
  9111. * Sets the triangle's vertices by copying the given values.
  9112. *
  9113. * @param {Vector3} a - The first corner of the triangle.
  9114. * @param {Vector3} b - The second corner of the triangle.
  9115. * @param {Vector3} c - The third corner of the triangle.
  9116. * @return {Triangle} A reference to this triangle.
  9117. */
  9118. set( a, b, c ) {
  9119. this.a.copy( a );
  9120. this.b.copy( b );
  9121. this.c.copy( c );
  9122. return this;
  9123. }
  9124. /**
  9125. * Sets the triangle's vertices by copying the given array values.
  9126. *
  9127. * @param {Array<Vector3>} points - An array with 3D points.
  9128. * @param {number} i0 - The array index representing the first corner of the triangle.
  9129. * @param {number} i1 - The array index representing the second corner of the triangle.
  9130. * @param {number} i2 - The array index representing the third corner of the triangle.
  9131. * @return {Triangle} A reference to this triangle.
  9132. */
  9133. setFromPointsAndIndices( points, i0, i1, i2 ) {
  9134. this.a.copy( points[ i0 ] );
  9135. this.b.copy( points[ i1 ] );
  9136. this.c.copy( points[ i2 ] );
  9137. return this;
  9138. }
  9139. /**
  9140. * Sets the triangle's vertices by copying the given attribute values.
  9141. *
  9142. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  9143. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  9144. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  9145. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  9146. * @return {Triangle} A reference to this triangle.
  9147. */
  9148. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  9149. this.a.fromBufferAttribute( attribute, i0 );
  9150. this.b.fromBufferAttribute( attribute, i1 );
  9151. this.c.fromBufferAttribute( attribute, i2 );
  9152. return this;
  9153. }
  9154. /**
  9155. * Returns a new triangle with copied values from this instance.
  9156. *
  9157. * @return {Triangle} A clone of this instance.
  9158. */
  9159. clone() {
  9160. return new this.constructor().copy( this );
  9161. }
  9162. /**
  9163. * Copies the values of the given triangle to this instance.
  9164. *
  9165. * @param {Triangle} triangle - The triangle to copy.
  9166. * @return {Triangle} A reference to this triangle.
  9167. */
  9168. copy( triangle ) {
  9169. this.a.copy( triangle.a );
  9170. this.b.copy( triangle.b );
  9171. this.c.copy( triangle.c );
  9172. return this;
  9173. }
  9174. /**
  9175. * Computes the area of the triangle.
  9176. *
  9177. * @return {number} The triangle's area.
  9178. */
  9179. getArea() {
  9180. _v0$1.subVectors( this.c, this.b );
  9181. _v1$3.subVectors( this.a, this.b );
  9182. return _v0$1.cross( _v1$3 ).length() * 0.5;
  9183. }
  9184. /**
  9185. * Computes the midpoint of the triangle.
  9186. *
  9187. * @param {Vector3} target - The target vector that is used to store the method's result.
  9188. * @return {Vector3} The triangle's midpoint.
  9189. */
  9190. getMidpoint( target ) {
  9191. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  9192. }
  9193. /**
  9194. * Computes the normal of the triangle.
  9195. *
  9196. * @param {Vector3} target - The target vector that is used to store the method's result.
  9197. * @return {Vector3} The triangle's normal.
  9198. */
  9199. getNormal( target ) {
  9200. return Triangle.getNormal( this.a, this.b, this.c, target );
  9201. }
  9202. /**
  9203. * Computes a plane the triangle lies within.
  9204. *
  9205. * @param {Plane} target - The target vector that is used to store the method's result.
  9206. * @return {Plane} The plane the triangle lies within.
  9207. */
  9208. getPlane( target ) {
  9209. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  9210. }
  9211. /**
  9212. * Computes a barycentric coordinates from the given vector.
  9213. * Returns `null` if the triangle is degenerate.
  9214. *
  9215. * @param {Vector3} point - A point in 3D space.
  9216. * @param {Vector3} target - The target vector that is used to store the method's result.
  9217. * @return {?Vector3} The barycentric coordinates for the given point
  9218. */
  9219. getBarycoord( point, target ) {
  9220. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  9221. }
  9222. /**
  9223. * Computes the value barycentrically interpolated for the given point on the
  9224. * triangle. Returns `null` if the triangle is degenerate.
  9225. *
  9226. * @param {Vector3} point - Position of interpolated point.
  9227. * @param {Vector3} v1 - Value to interpolate of first vertex.
  9228. * @param {Vector3} v2 - Value to interpolate of second vertex.
  9229. * @param {Vector3} v3 - Value to interpolate of third vertex.
  9230. * @param {Vector3} target - The target vector that is used to store the method's result.
  9231. * @return {?Vector3} The interpolated value.
  9232. */
  9233. getInterpolation( point, v1, v2, v3, target ) {
  9234. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  9235. }
  9236. /**
  9237. * Returns `true` if the given point, when projected onto the plane of the
  9238. * triangle, lies within the triangle.
  9239. *
  9240. * @param {Vector3} point - The point in 3D space to test.
  9241. * @return {boolean} Whether the given point, when projected onto the plane of the
  9242. * triangle, lies within the triangle or not.
  9243. */
  9244. containsPoint( point ) {
  9245. return Triangle.containsPoint( point, this.a, this.b, this.c );
  9246. }
  9247. /**
  9248. * Returns `true` if the triangle is oriented towards the given direction.
  9249. *
  9250. * @param {Vector3} direction - The (normalized) direction vector.
  9251. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  9252. */
  9253. isFrontFacing( direction ) {
  9254. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  9255. }
  9256. /**
  9257. * Returns `true` if this triangle intersects with the given box.
  9258. *
  9259. * @param {Box3} box - The box to intersect.
  9260. * @return {boolean} Whether this triangle intersects with the given box or not.
  9261. */
  9262. intersectsBox( box ) {
  9263. return box.intersectsTriangle( this );
  9264. }
  9265. /**
  9266. * Returns the closest point on the triangle to the given point.
  9267. *
  9268. * @param {Vector3} p - The point to compute the closest point for.
  9269. * @param {Vector3} target - The target vector that is used to store the method's result.
  9270. * @return {Vector3} The closest point on the triangle.
  9271. */
  9272. closestPointToPoint( p, target ) {
  9273. const a = this.a, b = this.b, c = this.c;
  9274. let v, w;
  9275. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  9276. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  9277. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  9278. // basically, we're distinguishing which of the voronoi regions of the triangle
  9279. // the point lies in with the minimum amount of redundant computation.
  9280. _vab.subVectors( b, a );
  9281. _vac.subVectors( c, a );
  9282. _vap.subVectors( p, a );
  9283. const d1 = _vab.dot( _vap );
  9284. const d2 = _vac.dot( _vap );
  9285. if ( d1 <= 0 && d2 <= 0 ) {
  9286. // vertex region of A; barycentric coords (1, 0, 0)
  9287. return target.copy( a );
  9288. }
  9289. _vbp.subVectors( p, b );
  9290. const d3 = _vab.dot( _vbp );
  9291. const d4 = _vac.dot( _vbp );
  9292. if ( d3 >= 0 && d4 <= d3 ) {
  9293. // vertex region of B; barycentric coords (0, 1, 0)
  9294. return target.copy( b );
  9295. }
  9296. const vc = d1 * d4 - d3 * d2;
  9297. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  9298. v = d1 / ( d1 - d3 );
  9299. // edge region of AB; barycentric coords (1-v, v, 0)
  9300. return target.copy( a ).addScaledVector( _vab, v );
  9301. }
  9302. _vcp.subVectors( p, c );
  9303. const d5 = _vab.dot( _vcp );
  9304. const d6 = _vac.dot( _vcp );
  9305. if ( d6 >= 0 && d5 <= d6 ) {
  9306. // vertex region of C; barycentric coords (0, 0, 1)
  9307. return target.copy( c );
  9308. }
  9309. const vb = d5 * d2 - d1 * d6;
  9310. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  9311. w = d2 / ( d2 - d6 );
  9312. // edge region of AC; barycentric coords (1-w, 0, w)
  9313. return target.copy( a ).addScaledVector( _vac, w );
  9314. }
  9315. const va = d3 * d6 - d5 * d4;
  9316. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  9317. _vbc.subVectors( c, b );
  9318. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  9319. // edge region of BC; barycentric coords (0, 1-w, w)
  9320. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  9321. }
  9322. // face region
  9323. const denom = 1 / ( va + vb + vc );
  9324. // u = va * denom
  9325. v = vb * denom;
  9326. w = vc * denom;
  9327. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  9328. }
  9329. /**
  9330. * Returns `true` if this triangle is equal with the given one.
  9331. *
  9332. * @param {Triangle} triangle - The triangle to test for equality.
  9333. * @return {boolean} Whether this triangle is equal with the given one.
  9334. */
  9335. equals( triangle ) {
  9336. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  9337. }
  9338. }
  9339. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  9340. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  9341. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  9342. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  9343. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  9344. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  9345. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  9346. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  9347. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  9348. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  9349. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  9350. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  9351. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  9352. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  9353. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  9354. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  9355. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  9356. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  9357. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  9358. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  9359. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  9360. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  9361. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  9362. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  9363. const _hslA = { h: 0, s: 0, l: 0 };
  9364. const _hslB = { h: 0, s: 0, l: 0 };
  9365. function hue2rgb( p, q, t ) {
  9366. if ( t < 0 ) t += 1;
  9367. if ( t > 1 ) t -= 1;
  9368. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  9369. if ( t < 1 / 2 ) return q;
  9370. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  9371. return p;
  9372. }
  9373. /**
  9374. * A Color instance is represented by RGB components in the linear <i>working
  9375. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  9376. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  9377. * strings) are converted to the working color space automatically.
  9378. *
  9379. * ```js
  9380. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  9381. * const color = new THREE.Color().setHex( 0x112233 );
  9382. * ```
  9383. * Source color spaces may be specified explicitly, to ensure correct conversions.
  9384. * ```js
  9385. * // assumed already LinearSRGBColorSpace; no conversion
  9386. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  9387. *
  9388. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  9389. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  9390. * ```
  9391. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  9392. * see <i>Color management</i>. Iterating through a Color instance will yield
  9393. * its components (r, g, b) in the corresponding order. A Color can be initialised
  9394. * in any of the following ways:
  9395. * ```js
  9396. * //empty constructor - will default white
  9397. * const color1 = new THREE.Color();
  9398. *
  9399. * //Hexadecimal color (recommended)
  9400. * const color2 = new THREE.Color( 0xff0000 );
  9401. *
  9402. * //RGB string
  9403. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  9404. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  9405. *
  9406. * //X11 color name - all 140 color names are supported.
  9407. * //Note the lack of CamelCase in the name
  9408. * const color5 = new THREE.Color( 'skyblue' );
  9409. * //HSL string
  9410. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  9411. *
  9412. * //Separate RGB values between 0 and 1
  9413. * const color7 = new THREE.Color( 1, 0, 0 );
  9414. * ```
  9415. */
  9416. class Color {
  9417. /**
  9418. * Constructs a new color.
  9419. *
  9420. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  9421. * and that method is used throughout the rest of the documentation.
  9422. *
  9423. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9424. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9425. * @param {number} [g] - The green component.
  9426. * @param {number} [b] - The blue component.
  9427. */
  9428. constructor( r, g, b ) {
  9429. /**
  9430. * This flag can be used for type testing.
  9431. *
  9432. * @type {boolean}
  9433. * @readonly
  9434. * @default true
  9435. */
  9436. this.isColor = true;
  9437. /**
  9438. * The red component.
  9439. *
  9440. * @type {number}
  9441. * @default 1
  9442. */
  9443. this.r = 1;
  9444. /**
  9445. * The green component.
  9446. *
  9447. * @type {number}
  9448. * @default 1
  9449. */
  9450. this.g = 1;
  9451. /**
  9452. * The blue component.
  9453. *
  9454. * @type {number}
  9455. * @default 1
  9456. */
  9457. this.b = 1;
  9458. return this.set( r, g, b );
  9459. }
  9460. /**
  9461. * Sets the colors's components from the given values.
  9462. *
  9463. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  9464. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  9465. * @param {number} [g] - The green component.
  9466. * @param {number} [b] - The blue component.
  9467. * @return {Color} A reference to this color.
  9468. */
  9469. set( r, g, b ) {
  9470. if ( g === undefined && b === undefined ) {
  9471. // r is THREE.Color, hex or string
  9472. const value = r;
  9473. if ( value && value.isColor ) {
  9474. this.copy( value );
  9475. } else if ( typeof value === 'number' ) {
  9476. this.setHex( value );
  9477. } else if ( typeof value === 'string' ) {
  9478. this.setStyle( value );
  9479. }
  9480. } else {
  9481. this.setRGB( r, g, b );
  9482. }
  9483. return this;
  9484. }
  9485. /**
  9486. * Sets the colors's components to the given scalar value.
  9487. *
  9488. * @param {number} scalar - The scalar value.
  9489. * @return {Color} A reference to this color.
  9490. */
  9491. setScalar( scalar ) {
  9492. this.r = scalar;
  9493. this.g = scalar;
  9494. this.b = scalar;
  9495. return this;
  9496. }
  9497. /**
  9498. * Sets this color from a hexadecimal value.
  9499. *
  9500. * @param {number} hex - The hexadecimal value.
  9501. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9502. * @return {Color} A reference to this color.
  9503. */
  9504. setHex( hex, colorSpace = SRGBColorSpace ) {
  9505. hex = Math.floor( hex );
  9506. this.r = ( hex >> 16 & 255 ) / 255;
  9507. this.g = ( hex >> 8 & 255 ) / 255;
  9508. this.b = ( hex & 255 ) / 255;
  9509. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9510. return this;
  9511. }
  9512. /**
  9513. * Sets this color from RGB values.
  9514. *
  9515. * @param {number} r - Red channel value between `0.0` and `1.0`.
  9516. * @param {number} g - Green channel value between `0.0` and `1.0`.
  9517. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  9518. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9519. * @return {Color} A reference to this color.
  9520. */
  9521. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  9522. this.r = r;
  9523. this.g = g;
  9524. this.b = b;
  9525. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9526. return this;
  9527. }
  9528. /**
  9529. * Sets this color from RGB values.
  9530. *
  9531. * @param {number} h - Hue value between `0.0` and `1.0`.
  9532. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9533. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9534. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9535. * @return {Color} A reference to this color.
  9536. */
  9537. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  9538. // h,s,l ranges are in 0.0 - 1.0
  9539. h = euclideanModulo( h, 1 );
  9540. s = clamp( s, 0, 1 );
  9541. l = clamp( l, 0, 1 );
  9542. if ( s === 0 ) {
  9543. this.r = this.g = this.b = l;
  9544. } else {
  9545. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  9546. const q = ( 2 * l ) - p;
  9547. this.r = hue2rgb( q, p, h + 1 / 3 );
  9548. this.g = hue2rgb( q, p, h );
  9549. this.b = hue2rgb( q, p, h - 1 / 3 );
  9550. }
  9551. ColorManagement.toWorkingColorSpace( this, colorSpace );
  9552. return this;
  9553. }
  9554. /**
  9555. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  9556. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  9557. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  9558. * all 140 color names are supported).
  9559. *
  9560. * @param {string} style - Color as a CSS-style string.
  9561. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9562. * @return {Color} A reference to this color.
  9563. */
  9564. setStyle( style, colorSpace = SRGBColorSpace ) {
  9565. function handleAlpha( string ) {
  9566. if ( string === undefined ) return;
  9567. if ( parseFloat( string ) < 1 ) {
  9568. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  9569. }
  9570. }
  9571. let m;
  9572. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  9573. // rgb / hsl
  9574. let color;
  9575. const name = m[ 1 ];
  9576. const components = m[ 2 ];
  9577. switch ( name ) {
  9578. case 'rgb':
  9579. case 'rgba':
  9580. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9581. // rgb(255,0,0) rgba(255,0,0,0.5)
  9582. handleAlpha( color[ 4 ] );
  9583. return this.setRGB(
  9584. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  9585. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  9586. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  9587. colorSpace
  9588. );
  9589. }
  9590. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9591. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  9592. handleAlpha( color[ 4 ] );
  9593. return this.setRGB(
  9594. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  9595. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  9596. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  9597. colorSpace
  9598. );
  9599. }
  9600. break;
  9601. case 'hsl':
  9602. case 'hsla':
  9603. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  9604. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  9605. handleAlpha( color[ 4 ] );
  9606. return this.setHSL(
  9607. parseFloat( color[ 1 ] ) / 360,
  9608. parseFloat( color[ 2 ] ) / 100,
  9609. parseFloat( color[ 3 ] ) / 100,
  9610. colorSpace
  9611. );
  9612. }
  9613. break;
  9614. default:
  9615. console.warn( 'THREE.Color: Unknown color model ' + style );
  9616. }
  9617. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  9618. // hex color
  9619. const hex = m[ 1 ];
  9620. const size = hex.length;
  9621. if ( size === 3 ) {
  9622. // #ff0
  9623. return this.setRGB(
  9624. parseInt( hex.charAt( 0 ), 16 ) / 15,
  9625. parseInt( hex.charAt( 1 ), 16 ) / 15,
  9626. parseInt( hex.charAt( 2 ), 16 ) / 15,
  9627. colorSpace
  9628. );
  9629. } else if ( size === 6 ) {
  9630. // #ff0000
  9631. return this.setHex( parseInt( hex, 16 ), colorSpace );
  9632. } else {
  9633. console.warn( 'THREE.Color: Invalid hex color ' + style );
  9634. }
  9635. } else if ( style && style.length > 0 ) {
  9636. return this.setColorName( style, colorSpace );
  9637. }
  9638. return this;
  9639. }
  9640. /**
  9641. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  9642. * you don't need the other CSS-style formats.
  9643. *
  9644. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  9645. * ```js
  9646. * Color.NAMES.aliceblue // returns 0xF0F8FF
  9647. * ```
  9648. *
  9649. * @param {string} style - The color name.
  9650. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9651. * @return {Color} A reference to this color.
  9652. */
  9653. setColorName( style, colorSpace = SRGBColorSpace ) {
  9654. // color keywords
  9655. const hex = _colorKeywords[ style.toLowerCase() ];
  9656. if ( hex !== undefined ) {
  9657. // red
  9658. this.setHex( hex, colorSpace );
  9659. } else {
  9660. // unknown color
  9661. console.warn( 'THREE.Color: Unknown color ' + style );
  9662. }
  9663. return this;
  9664. }
  9665. /**
  9666. * Returns a new color with copied values from this instance.
  9667. *
  9668. * @return {Color} A clone of this instance.
  9669. */
  9670. clone() {
  9671. return new this.constructor( this.r, this.g, this.b );
  9672. }
  9673. /**
  9674. * Copies the values of the given color to this instance.
  9675. *
  9676. * @param {Color} color - The color to copy.
  9677. * @return {Color} A reference to this color.
  9678. */
  9679. copy( color ) {
  9680. this.r = color.r;
  9681. this.g = color.g;
  9682. this.b = color.b;
  9683. return this;
  9684. }
  9685. /**
  9686. * Copies the given color into this color, and then converts this color from
  9687. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9688. *
  9689. * @param {Color} color - The color to copy/convert.
  9690. * @return {Color} A reference to this color.
  9691. */
  9692. copySRGBToLinear( color ) {
  9693. this.r = SRGBToLinear( color.r );
  9694. this.g = SRGBToLinear( color.g );
  9695. this.b = SRGBToLinear( color.b );
  9696. return this;
  9697. }
  9698. /**
  9699. * Copies the given color into this color, and then converts this color from
  9700. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9701. *
  9702. * @param {Color} color - The color to copy/convert.
  9703. * @return {Color} A reference to this color.
  9704. */
  9705. copyLinearToSRGB( color ) {
  9706. this.r = LinearToSRGB( color.r );
  9707. this.g = LinearToSRGB( color.g );
  9708. this.b = LinearToSRGB( color.b );
  9709. return this;
  9710. }
  9711. /**
  9712. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  9713. *
  9714. * @return {Color} A reference to this color.
  9715. */
  9716. convertSRGBToLinear() {
  9717. this.copySRGBToLinear( this );
  9718. return this;
  9719. }
  9720. /**
  9721. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  9722. *
  9723. * @return {Color} A reference to this color.
  9724. */
  9725. convertLinearToSRGB() {
  9726. this.copyLinearToSRGB( this );
  9727. return this;
  9728. }
  9729. /**
  9730. * Returns the hexadecimal value of this color.
  9731. *
  9732. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9733. * @return {number} The hexadecimal value.
  9734. */
  9735. getHex( colorSpace = SRGBColorSpace ) {
  9736. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9737. 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 ) );
  9738. }
  9739. /**
  9740. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  9741. *
  9742. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9743. * @return {string} The hexadecimal value as a string.
  9744. */
  9745. getHexString( colorSpace = SRGBColorSpace ) {
  9746. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  9747. }
  9748. /**
  9749. * Converts the colors RGB values into the HSL format and stores them into the
  9750. * given target object.
  9751. *
  9752. * @param {{h:0,s:0,l:0}} target - The target object that is used to store the method's result.
  9753. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9754. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  9755. */
  9756. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  9757. // h,s,l ranges are in 0.0 - 1.0
  9758. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9759. const r = _color.r, g = _color.g, b = _color.b;
  9760. const max = Math.max( r, g, b );
  9761. const min = Math.min( r, g, b );
  9762. let hue, saturation;
  9763. const lightness = ( min + max ) / 2.0;
  9764. if ( min === max ) {
  9765. hue = 0;
  9766. saturation = 0;
  9767. } else {
  9768. const delta = max - min;
  9769. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  9770. switch ( max ) {
  9771. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  9772. case g: hue = ( b - r ) / delta + 2; break;
  9773. case b: hue = ( r - g ) / delta + 4; break;
  9774. }
  9775. hue /= 6;
  9776. }
  9777. target.h = hue;
  9778. target.s = saturation;
  9779. target.l = lightness;
  9780. return target;
  9781. }
  9782. /**
  9783. * Returns the RGB values of this color and stores them into the given target object.
  9784. *
  9785. * @param {Color} target - The target color that is used to store the method's result.
  9786. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  9787. * @return {Color} The RGB representation of this color.
  9788. */
  9789. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  9790. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9791. target.r = _color.r;
  9792. target.g = _color.g;
  9793. target.b = _color.b;
  9794. return target;
  9795. }
  9796. /**
  9797. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  9798. *
  9799. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  9800. * @return {string} The CSS representation of this color.
  9801. */
  9802. getStyle( colorSpace = SRGBColorSpace ) {
  9803. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  9804. const r = _color.r, g = _color.g, b = _color.b;
  9805. if ( colorSpace !== SRGBColorSpace ) {
  9806. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  9807. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  9808. }
  9809. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  9810. }
  9811. /**
  9812. * Adds the given HSL values to this color's values.
  9813. * Internally, this converts the color's RGB values to HSL, adds HSL
  9814. * and then converts the color back to RGB.
  9815. *
  9816. * @param {number} h - Hue value between `0.0` and `1.0`.
  9817. * @param {number} s - Saturation value between `0.0` and `1.0`.
  9818. * @param {number} l - Lightness value between `0.0` and `1.0`.
  9819. * @return {Color} A reference to this color.
  9820. */
  9821. offsetHSL( h, s, l ) {
  9822. this.getHSL( _hslA );
  9823. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  9824. }
  9825. /**
  9826. * Adds the RGB values of the given color to the RGB values of this color.
  9827. *
  9828. * @param {Color} color - The color to add.
  9829. * @return {Color} A reference to this color.
  9830. */
  9831. add( color ) {
  9832. this.r += color.r;
  9833. this.g += color.g;
  9834. this.b += color.b;
  9835. return this;
  9836. }
  9837. /**
  9838. * Adds the RGB values of the given colors and stores the result in this instance.
  9839. *
  9840. * @param {Color} color1 - The first color.
  9841. * @param {Color} color2 - The second color.
  9842. * @return {Color} A reference to this color.
  9843. */
  9844. addColors( color1, color2 ) {
  9845. this.r = color1.r + color2.r;
  9846. this.g = color1.g + color2.g;
  9847. this.b = color1.b + color2.b;
  9848. return this;
  9849. }
  9850. /**
  9851. * Adds the given scalar value to the RGB values of this color.
  9852. *
  9853. * @param {number} s - The scalar to add.
  9854. * @return {Color} A reference to this color.
  9855. */
  9856. addScalar( s ) {
  9857. this.r += s;
  9858. this.g += s;
  9859. this.b += s;
  9860. return this;
  9861. }
  9862. /**
  9863. * Subtracts the RGB values of the given color from the RGB values of this color.
  9864. *
  9865. * @param {Color} color - The color to subtract.
  9866. * @return {Color} A reference to this color.
  9867. */
  9868. sub( color ) {
  9869. this.r = Math.max( 0, this.r - color.r );
  9870. this.g = Math.max( 0, this.g - color.g );
  9871. this.b = Math.max( 0, this.b - color.b );
  9872. return this;
  9873. }
  9874. /**
  9875. * Multiplies the RGB values of the given color with the RGB values of this color.
  9876. *
  9877. * @param {Color} color - The color to multiply.
  9878. * @return {Color} A reference to this color.
  9879. */
  9880. multiply( color ) {
  9881. this.r *= color.r;
  9882. this.g *= color.g;
  9883. this.b *= color.b;
  9884. return this;
  9885. }
  9886. /**
  9887. * Multiplies the given scalar value with the RGB values of this color.
  9888. *
  9889. * @param {number} s - The scalar to multiply.
  9890. * @return {Color} A reference to this color.
  9891. */
  9892. multiplyScalar( s ) {
  9893. this.r *= s;
  9894. this.g *= s;
  9895. this.b *= s;
  9896. return this;
  9897. }
  9898. /**
  9899. * Linearly interpolates this color's RGB values toward the RGB values of the
  9900. * given color. The alpha argument can be thought of as the ratio between
  9901. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  9902. *
  9903. * @param {Color} color - The color to converge on.
  9904. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9905. * @return {Color} A reference to this color.
  9906. */
  9907. lerp( color, alpha ) {
  9908. this.r += ( color.r - this.r ) * alpha;
  9909. this.g += ( color.g - this.g ) * alpha;
  9910. this.b += ( color.b - this.b ) * alpha;
  9911. return this;
  9912. }
  9913. /**
  9914. * Linearly interpolates between the given colors and stores the result in this instance.
  9915. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  9916. * is the first and `1.0` is the second color.
  9917. *
  9918. * @param {Color} color1 - The first color.
  9919. * @param {Color} color2 - The second color.
  9920. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9921. * @return {Color} A reference to this color.
  9922. */
  9923. lerpColors( color1, color2, alpha ) {
  9924. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  9925. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  9926. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  9927. return this;
  9928. }
  9929. /**
  9930. * Linearly interpolates this color's HSL values toward the HSL values of the
  9931. * given color. It differs from {@link Color#lerp} by not interpolating straight
  9932. * from one color to the other, but instead going through all the hues in between
  9933. * those two colors. The alpha argument can be thought of as the ratio between
  9934. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  9935. *
  9936. * @param {Color} color - The color to converge on.
  9937. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  9938. * @return {Color} A reference to this color.
  9939. */
  9940. lerpHSL( color, alpha ) {
  9941. this.getHSL( _hslA );
  9942. color.getHSL( _hslB );
  9943. const h = lerp( _hslA.h, _hslB.h, alpha );
  9944. const s = lerp( _hslA.s, _hslB.s, alpha );
  9945. const l = lerp( _hslA.l, _hslB.l, alpha );
  9946. this.setHSL( h, s, l );
  9947. return this;
  9948. }
  9949. /**
  9950. * Sets the color's RGB components from the given 3D vector.
  9951. *
  9952. * @param {Vector3} v - The vector to set.
  9953. * @return {Color} A reference to this color.
  9954. */
  9955. setFromVector3( v ) {
  9956. this.r = v.x;
  9957. this.g = v.y;
  9958. this.b = v.z;
  9959. return this;
  9960. }
  9961. /**
  9962. * Transforms this color with the given 3x3 matrix.
  9963. *
  9964. * @param {Matrix3} m - The matrix.
  9965. * @return {Color} A reference to this color.
  9966. */
  9967. applyMatrix3( m ) {
  9968. const r = this.r, g = this.g, b = this.b;
  9969. const e = m.elements;
  9970. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  9971. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  9972. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  9973. return this;
  9974. }
  9975. /**
  9976. * Returns `true` if this color is equal with the given one.
  9977. *
  9978. * @param {Color} c - The color to test for equality.
  9979. * @return {boolean} Whether this bounding color is equal with the given one.
  9980. */
  9981. equals( c ) {
  9982. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  9983. }
  9984. /**
  9985. * Sets this color's RGB components from the given array.
  9986. *
  9987. * @param {Array<number>} array - An array holding the RGB values.
  9988. * @param {number} [offset=0] - The offset into the array.
  9989. * @return {Color} A reference to this color.
  9990. */
  9991. fromArray( array, offset = 0 ) {
  9992. this.r = array[ offset ];
  9993. this.g = array[ offset + 1 ];
  9994. this.b = array[ offset + 2 ];
  9995. return this;
  9996. }
  9997. /**
  9998. * Writes the RGB components of this color to the given array. If no array is provided,
  9999. * the method returns a new instance.
  10000. *
  10001. * @param {Array<number>} [array=[]] - The target array holding the color components.
  10002. * @param {number} [offset=0] - Index of the first element in the array.
  10003. * @return {Array<number>} The color components.
  10004. */
  10005. toArray( array = [], offset = 0 ) {
  10006. array[ offset ] = this.r;
  10007. array[ offset + 1 ] = this.g;
  10008. array[ offset + 2 ] = this.b;
  10009. return array;
  10010. }
  10011. /**
  10012. * Sets the components of this color from the given buffer attribute.
  10013. *
  10014. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  10015. * @param {number} index - The index into the attribute.
  10016. * @return {Color} A reference to this color.
  10017. */
  10018. fromBufferAttribute( attribute, index ) {
  10019. this.r = attribute.getX( index );
  10020. this.g = attribute.getY( index );
  10021. this.b = attribute.getZ( index );
  10022. return this;
  10023. }
  10024. /**
  10025. * This methods defines the serialization result of this class. Returns the color
  10026. * as a hexadecimal value.
  10027. *
  10028. * @return {number} The hexadecimal value.
  10029. */
  10030. toJSON() {
  10031. return this.getHex();
  10032. }
  10033. *[ Symbol.iterator ]() {
  10034. yield this.r;
  10035. yield this.g;
  10036. yield this.b;
  10037. }
  10038. }
  10039. const _color = /*@__PURE__*/ new Color();
  10040. /**
  10041. * A dictionary with X11 color names.
  10042. *
  10043. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  10044. *
  10045. * @static
  10046. * @type {Object}
  10047. */
  10048. Color.NAMES = _colorKeywords;
  10049. let _materialId = 0;
  10050. /**
  10051. * Abstract base class for materials.
  10052. *
  10053. * Materials define the appearance of renderable 3D objects.
  10054. *
  10055. * @abstract
  10056. * @augments EventDispatcher
  10057. */
  10058. class Material extends EventDispatcher {
  10059. /**
  10060. * Constructs a new material.
  10061. */
  10062. constructor() {
  10063. super();
  10064. /**
  10065. * This flag can be used for type testing.
  10066. *
  10067. * @type {boolean}
  10068. * @readonly
  10069. * @default true
  10070. */
  10071. this.isMaterial = true;
  10072. /**
  10073. * The ID of the material.
  10074. *
  10075. * @name Material#id
  10076. * @type {number}
  10077. * @readonly
  10078. */
  10079. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  10080. /**
  10081. * The UUID of the material.
  10082. *
  10083. * @type {string}
  10084. * @readonly
  10085. */
  10086. this.uuid = generateUUID();
  10087. /**
  10088. * The name of the material.
  10089. *
  10090. * @type {string}
  10091. */
  10092. this.name = '';
  10093. /**
  10094. * The type property is used for detecting the object type
  10095. * in context of serialization/deserialization.
  10096. *
  10097. * @type {string}
  10098. * @readonly
  10099. */
  10100. this.type = 'Material';
  10101. /**
  10102. * Defines the blending type of the material.
  10103. *
  10104. * It must be set to `CustomBlending` if custom blending properties like
  10105. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  10106. * should have any effect.
  10107. *
  10108. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  10109. * @default NormalBlending
  10110. */
  10111. this.blending = NormalBlending;
  10112. /**
  10113. * Defines which side of faces will be rendered - front, back or both.
  10114. *
  10115. * @type {(FrontSide|BackSide|DoubleSide)}
  10116. * @default FrontSide
  10117. */
  10118. this.side = FrontSide;
  10119. /**
  10120. * If set to `true`, vertex colors should be used.
  10121. *
  10122. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  10123. * four (RGBA) component color buffer attribute is used.
  10124. *
  10125. * @type {boolean}
  10126. * @default false
  10127. */
  10128. this.vertexColors = false;
  10129. /**
  10130. * Defines how transparent the material is.
  10131. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  10132. *
  10133. * If the {@link Material#transparent} is not set to `true`,
  10134. * the material will remain fully opaque and this value will only affect its color.
  10135. *
  10136. * @type {number}
  10137. * @default 1
  10138. */
  10139. this.opacity = 1;
  10140. /**
  10141. * Defines whether this material is transparent. This has an effect on
  10142. * rendering as transparent objects need special treatment and are rendered
  10143. * after non-transparent objects.
  10144. *
  10145. * When set to true, the extent to which the material is transparent is
  10146. * controlled by {@link Material#opacity}.
  10147. *
  10148. * @type {boolean}
  10149. * @default false
  10150. */
  10151. this.transparent = false;
  10152. /**
  10153. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  10154. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  10155. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  10156. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  10157. *
  10158. * @type {boolean}
  10159. * @default false
  10160. */
  10161. this.alphaHash = false;
  10162. /**
  10163. * Defines the blending source factor.
  10164. *
  10165. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10166. * @default SrcAlphaFactor
  10167. */
  10168. this.blendSrc = SrcAlphaFactor;
  10169. /**
  10170. * Defines the blending destination factor.
  10171. *
  10172. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10173. * @default OneMinusSrcAlphaFactor
  10174. */
  10175. this.blendDst = OneMinusSrcAlphaFactor;
  10176. /**
  10177. * Defines the blending equation.
  10178. *
  10179. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10180. * @default OneMinusSrcAlphaFactor
  10181. */
  10182. this.blendEquation = AddEquation;
  10183. /**
  10184. * Defines the blending source alpha factor.
  10185. *
  10186. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10187. * @default null
  10188. */
  10189. this.blendSrcAlpha = null;
  10190. /**
  10191. * Defines the blending destination alpha factor.
  10192. *
  10193. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  10194. * @default null
  10195. */
  10196. this.blendDstAlpha = null;
  10197. /**
  10198. * Defines the blending equation of the alpha channel.
  10199. *
  10200. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  10201. * @default OneMinusSrcAlphaFactor
  10202. */
  10203. this.blendEquationAlpha = null;
  10204. /**
  10205. * Represents the RGB values of the constant blend color.
  10206. *
  10207. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  10208. *
  10209. * @type {Color}
  10210. * @default (0,0,0)
  10211. */
  10212. this.blendColor = new Color( 0, 0, 0 );
  10213. /**
  10214. * Represents the alpha value of the constant blend color.
  10215. *
  10216. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  10217. *
  10218. * @type {number}
  10219. * @default 0
  10220. */
  10221. this.blendAlpha = 0;
  10222. /**
  10223. * Defines the depth function.
  10224. *
  10225. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  10226. * @default LessEqualDepth
  10227. */
  10228. this.depthFunc = LessEqualDepth;
  10229. /**
  10230. * Whether to have depth test enabled when rendering this material.
  10231. * When the depth test is disabled, the depth write will also be implicitly disabled.
  10232. *
  10233. * @type {boolean}
  10234. * @default true
  10235. */
  10236. this.depthTest = true;
  10237. /**
  10238. * Whether rendering this material has any effect on the depth buffer.
  10239. *
  10240. * When drawing 2D overlays it can be useful to disable the depth writing in
  10241. * order to layer several things together without creating z-index artifacts.
  10242. *
  10243. * @type {boolean}
  10244. * @default true
  10245. */
  10246. this.depthWrite = true;
  10247. /**
  10248. * The bit mask to use when writing to the stencil buffer.
  10249. *
  10250. * @type {number}
  10251. * @default 0xff
  10252. */
  10253. this.stencilWriteMask = 0xff;
  10254. /**
  10255. * The stencil comparison function to use.
  10256. *
  10257. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  10258. * @default AlwaysStencilFunc
  10259. */
  10260. this.stencilFunc = AlwaysStencilFunc;
  10261. /**
  10262. * The value to use when performing stencil comparisons or stencil operations.
  10263. *
  10264. * @type {number}
  10265. * @default 0
  10266. */
  10267. this.stencilRef = 0;
  10268. /**
  10269. * The bit mask to use when comparing against the stencil buffer.
  10270. *
  10271. * @type {number}
  10272. * @default 0xff
  10273. */
  10274. this.stencilFuncMask = 0xff;
  10275. /**
  10276. * Which stencil operation to perform when the comparison function returns `false`.
  10277. *
  10278. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10279. * @default KeepStencilOp
  10280. */
  10281. this.stencilFail = KeepStencilOp;
  10282. /**
  10283. * Which stencil operation to perform when the comparison function returns
  10284. * `true` but the depth test fails.
  10285. *
  10286. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10287. * @default KeepStencilOp
  10288. */
  10289. this.stencilZFail = KeepStencilOp;
  10290. /**
  10291. * Which stencil operation to perform when the comparison function returns
  10292. * `true` and the depth test passes.
  10293. *
  10294. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  10295. * @default KeepStencilOp
  10296. */
  10297. this.stencilZPass = KeepStencilOp;
  10298. /**
  10299. * Whether stencil operations are performed against the stencil buffer. In
  10300. * order to perform writes or comparisons against the stencil buffer this
  10301. * value must be `true`.
  10302. *
  10303. * @type {boolean}
  10304. * @default false
  10305. */
  10306. this.stencilWrite = false;
  10307. /**
  10308. * User-defined clipping planes specified as THREE.Plane objects in world
  10309. * space. These planes apply to the objects this material is attached to.
  10310. * Points in space whose signed distance to the plane is negative are clipped
  10311. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  10312. * be `true`.
  10313. *
  10314. * @type {?Array<Plane>}
  10315. * @default null
  10316. */
  10317. this.clippingPlanes = null;
  10318. /**
  10319. * Changes the behavior of clipping planes so that only their intersection is
  10320. * clipped, rather than their union.
  10321. *
  10322. * @type {boolean}
  10323. * @default false
  10324. */
  10325. this.clipIntersection = false;
  10326. /**
  10327. * Defines whether to clip shadows according to the clipping planes specified
  10328. * on this material.
  10329. *
  10330. * @type {boolean}
  10331. * @default false
  10332. */
  10333. this.clipShadows = false;
  10334. /**
  10335. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  10336. * is determined as follows:
  10337. *
  10338. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  10339. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  10340. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  10341. *
  10342. * @type {?(FrontSide|BackSide|DoubleSide)}
  10343. * @default null
  10344. */
  10345. this.shadowSide = null;
  10346. /**
  10347. * Whether to render the material's color.
  10348. *
  10349. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  10350. * objects that occlude other objects.
  10351. *
  10352. * @type {boolean}
  10353. * @default true
  10354. */
  10355. this.colorWrite = true;
  10356. /**
  10357. * Override the renderer's default precision for this material.
  10358. *
  10359. * @type {?('highp'|'mediump'|'lowp')}
  10360. * @default null
  10361. */
  10362. this.precision = null;
  10363. /**
  10364. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  10365. * be offset after it is interpolated from the depth values of the appropriate vertices.
  10366. * The offset is added before the depth test is performed and before the value is written
  10367. * into the depth buffer.
  10368. *
  10369. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  10370. * rendering solids with highlighted edges.
  10371. *
  10372. * @type {boolean}
  10373. * @default false
  10374. */
  10375. this.polygonOffset = false;
  10376. /**
  10377. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  10378. *
  10379. * @type {number}
  10380. * @default 0
  10381. */
  10382. this.polygonOffsetFactor = 0;
  10383. /**
  10384. * Is multiplied by an implementation-specific value to create a constant depth offset.
  10385. *
  10386. * @type {number}
  10387. * @default 0
  10388. */
  10389. this.polygonOffsetUnits = 0;
  10390. /**
  10391. * Whether to apply dithering to the color to remove the appearance of banding.
  10392. *
  10393. * @type {boolean}
  10394. * @default false
  10395. */
  10396. this.dithering = false;
  10397. /**
  10398. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  10399. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  10400. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  10401. *
  10402. * @type {boolean}
  10403. * @default false
  10404. */
  10405. this.alphaToCoverage = false;
  10406. /**
  10407. * Whether to premultiply the alpha (transparency) value.
  10408. *
  10409. * @type {boolean}
  10410. * @default false
  10411. */
  10412. this.premultipliedAlpha = false;
  10413. /**
  10414. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  10415. *
  10416. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  10417. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  10418. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  10419. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  10420. * disable the two pass rendering to avoid performance issues.
  10421. *
  10422. * @type {boolean}
  10423. * @default false
  10424. */
  10425. this.forceSinglePass = false;
  10426. /**
  10427. * Defines whether 3D objects using this material are visible.
  10428. *
  10429. * @type {boolean}
  10430. * @default true
  10431. */
  10432. this.visible = true;
  10433. /**
  10434. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  10435. *
  10436. * It is ignored when rendering to a render target or using post processing or when using
  10437. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  10438. *
  10439. * @type {boolean}
  10440. * @default true
  10441. */
  10442. this.toneMapped = true;
  10443. /**
  10444. * An object that can be used to store custom data about the Material. It
  10445. * should not hold references to functions as these will not be cloned.
  10446. *
  10447. * @type {Object}
  10448. */
  10449. this.userData = {};
  10450. /**
  10451. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  10452. *
  10453. * @type {number}
  10454. * @readonly
  10455. * @default 0
  10456. */
  10457. this.version = 0;
  10458. this._alphaTest = 0;
  10459. }
  10460. /**
  10461. * Sets the alpha value to be used when running an alpha test. The material
  10462. * will not be rendered if the opacity is lower than this value.
  10463. *
  10464. * @type {number}
  10465. * @readonly
  10466. * @default 0
  10467. */
  10468. get alphaTest() {
  10469. return this._alphaTest;
  10470. }
  10471. set alphaTest( value ) {
  10472. if ( this._alphaTest > 0 !== value > 0 ) {
  10473. this.version ++;
  10474. }
  10475. this._alphaTest = value;
  10476. }
  10477. /**
  10478. * An optional callback that is executed immediately before the material is used to render a 3D object.
  10479. *
  10480. * This method can only be used when rendering with {@link WebGLRenderer}.
  10481. *
  10482. * @param {WebGLRenderer} renderer - The renderer.
  10483. * @param {Scene} scene - The scene.
  10484. * @param {Camera} camera - The camera that is used to render the scene.
  10485. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10486. * @param {Object3D} object - The 3D object.
  10487. * @param {Object} group - The geometry group data.
  10488. */
  10489. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  10490. /**
  10491. * An optional callback that is executed immediately before the shader
  10492. * program is compiled. This function is called with the shader source code
  10493. * as a parameter. Useful for the modification of built-in materials.
  10494. *
  10495. * This method can only be used when rendering with {@link WebGLRenderer}. The
  10496. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  10497. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  10498. *
  10499. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  10500. * @param {WebGLRenderer} renderer - A reference to the renderer.
  10501. */
  10502. onBeforeCompile( /* shaderobject, renderer */ ) {}
  10503. /**
  10504. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  10505. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  10506. * shader or recompile the shader for this material as needed.
  10507. *
  10508. * This method can only be used when rendering with {@link WebGLRenderer}.
  10509. *
  10510. * @return {string} The custom program cache key.
  10511. */
  10512. customProgramCacheKey() {
  10513. return this.onBeforeCompile.toString();
  10514. }
  10515. setValues( values ) {
  10516. if ( values === undefined ) return;
  10517. for ( const key in values ) {
  10518. const newValue = values[ key ];
  10519. if ( newValue === undefined ) {
  10520. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  10521. continue;
  10522. }
  10523. const currentValue = this[ key ];
  10524. if ( currentValue === undefined ) {
  10525. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  10526. continue;
  10527. }
  10528. if ( currentValue && currentValue.isColor ) {
  10529. currentValue.set( newValue );
  10530. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  10531. currentValue.copy( newValue );
  10532. } else {
  10533. this[ key ] = newValue;
  10534. }
  10535. }
  10536. }
  10537. /**
  10538. * Serializes the material into JSON.
  10539. *
  10540. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10541. * @return {Object} A JSON object representing the serialized material.
  10542. * @see {@link ObjectLoader#parse}
  10543. */
  10544. toJSON( meta ) {
  10545. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10546. if ( isRootObject ) {
  10547. meta = {
  10548. textures: {},
  10549. images: {}
  10550. };
  10551. }
  10552. const data = {
  10553. metadata: {
  10554. version: 4.6,
  10555. type: 'Material',
  10556. generator: 'Material.toJSON'
  10557. }
  10558. };
  10559. // standard Material serialization
  10560. data.uuid = this.uuid;
  10561. data.type = this.type;
  10562. if ( this.name !== '' ) data.name = this.name;
  10563. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  10564. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  10565. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  10566. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  10567. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  10568. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  10569. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  10570. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  10571. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  10572. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  10573. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  10574. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  10575. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  10576. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  10577. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  10578. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  10579. }
  10580. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  10581. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  10582. }
  10583. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  10584. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  10585. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  10586. }
  10587. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  10588. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  10589. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  10590. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  10591. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  10592. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  10593. }
  10594. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  10595. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  10596. }
  10597. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  10598. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  10599. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  10600. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  10601. }
  10602. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  10603. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  10604. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  10605. if ( this.lightMap && this.lightMap.isTexture ) {
  10606. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  10607. data.lightMapIntensity = this.lightMapIntensity;
  10608. }
  10609. if ( this.aoMap && this.aoMap.isTexture ) {
  10610. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  10611. data.aoMapIntensity = this.aoMapIntensity;
  10612. }
  10613. if ( this.bumpMap && this.bumpMap.isTexture ) {
  10614. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  10615. data.bumpScale = this.bumpScale;
  10616. }
  10617. if ( this.normalMap && this.normalMap.isTexture ) {
  10618. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  10619. data.normalMapType = this.normalMapType;
  10620. data.normalScale = this.normalScale.toArray();
  10621. }
  10622. if ( this.displacementMap && this.displacementMap.isTexture ) {
  10623. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  10624. data.displacementScale = this.displacementScale;
  10625. data.displacementBias = this.displacementBias;
  10626. }
  10627. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  10628. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  10629. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  10630. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  10631. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  10632. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  10633. if ( this.envMap && this.envMap.isTexture ) {
  10634. data.envMap = this.envMap.toJSON( meta ).uuid;
  10635. if ( this.combine !== undefined ) data.combine = this.combine;
  10636. }
  10637. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  10638. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  10639. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  10640. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  10641. if ( this.gradientMap && this.gradientMap.isTexture ) {
  10642. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  10643. }
  10644. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  10645. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  10646. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  10647. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  10648. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  10649. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  10650. if ( this.size !== undefined ) data.size = this.size;
  10651. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  10652. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  10653. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  10654. if ( this.side !== FrontSide ) data.side = this.side;
  10655. if ( this.vertexColors === true ) data.vertexColors = true;
  10656. if ( this.opacity < 1 ) data.opacity = this.opacity;
  10657. if ( this.transparent === true ) data.transparent = true;
  10658. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  10659. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  10660. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  10661. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  10662. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  10663. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  10664. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  10665. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  10666. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  10667. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  10668. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  10669. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  10670. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  10671. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  10672. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  10673. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  10674. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  10675. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  10676. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  10677. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  10678. // rotation (SpriteMaterial)
  10679. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  10680. if ( this.polygonOffset === true ) data.polygonOffset = true;
  10681. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  10682. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  10683. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  10684. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  10685. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  10686. if ( this.scale !== undefined ) data.scale = this.scale;
  10687. if ( this.dithering === true ) data.dithering = true;
  10688. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  10689. if ( this.alphaHash === true ) data.alphaHash = true;
  10690. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  10691. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  10692. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  10693. if ( this.wireframe === true ) data.wireframe = true;
  10694. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  10695. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  10696. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  10697. if ( this.flatShading === true ) data.flatShading = true;
  10698. if ( this.visible === false ) data.visible = false;
  10699. if ( this.toneMapped === false ) data.toneMapped = false;
  10700. if ( this.fog === false ) data.fog = false;
  10701. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  10702. // TODO: Copied from Object3D.toJSON
  10703. function extractFromCache( cache ) {
  10704. const values = [];
  10705. for ( const key in cache ) {
  10706. const data = cache[ key ];
  10707. delete data.metadata;
  10708. values.push( data );
  10709. }
  10710. return values;
  10711. }
  10712. if ( isRootObject ) {
  10713. const textures = extractFromCache( meta.textures );
  10714. const images = extractFromCache( meta.images );
  10715. if ( textures.length > 0 ) data.textures = textures;
  10716. if ( images.length > 0 ) data.images = images;
  10717. }
  10718. return data;
  10719. }
  10720. /**
  10721. * Returns a new material with copied values from this instance.
  10722. *
  10723. * @return {Material} A clone of this instance.
  10724. */
  10725. clone() {
  10726. return new this.constructor().copy( this );
  10727. }
  10728. /**
  10729. * Copies the values of the given material to this instance.
  10730. *
  10731. * @param {Material} source - The material to copy.
  10732. * @return {Material} A reference to this instance.
  10733. */
  10734. copy( source ) {
  10735. this.name = source.name;
  10736. this.blending = source.blending;
  10737. this.side = source.side;
  10738. this.vertexColors = source.vertexColors;
  10739. this.opacity = source.opacity;
  10740. this.transparent = source.transparent;
  10741. this.blendSrc = source.blendSrc;
  10742. this.blendDst = source.blendDst;
  10743. this.blendEquation = source.blendEquation;
  10744. this.blendSrcAlpha = source.blendSrcAlpha;
  10745. this.blendDstAlpha = source.blendDstAlpha;
  10746. this.blendEquationAlpha = source.blendEquationAlpha;
  10747. this.blendColor.copy( source.blendColor );
  10748. this.blendAlpha = source.blendAlpha;
  10749. this.depthFunc = source.depthFunc;
  10750. this.depthTest = source.depthTest;
  10751. this.depthWrite = source.depthWrite;
  10752. this.stencilWriteMask = source.stencilWriteMask;
  10753. this.stencilFunc = source.stencilFunc;
  10754. this.stencilRef = source.stencilRef;
  10755. this.stencilFuncMask = source.stencilFuncMask;
  10756. this.stencilFail = source.stencilFail;
  10757. this.stencilZFail = source.stencilZFail;
  10758. this.stencilZPass = source.stencilZPass;
  10759. this.stencilWrite = source.stencilWrite;
  10760. const srcPlanes = source.clippingPlanes;
  10761. let dstPlanes = null;
  10762. if ( srcPlanes !== null ) {
  10763. const n = srcPlanes.length;
  10764. dstPlanes = new Array( n );
  10765. for ( let i = 0; i !== n; ++ i ) {
  10766. dstPlanes[ i ] = srcPlanes[ i ].clone();
  10767. }
  10768. }
  10769. this.clippingPlanes = dstPlanes;
  10770. this.clipIntersection = source.clipIntersection;
  10771. this.clipShadows = source.clipShadows;
  10772. this.shadowSide = source.shadowSide;
  10773. this.colorWrite = source.colorWrite;
  10774. this.precision = source.precision;
  10775. this.polygonOffset = source.polygonOffset;
  10776. this.polygonOffsetFactor = source.polygonOffsetFactor;
  10777. this.polygonOffsetUnits = source.polygonOffsetUnits;
  10778. this.dithering = source.dithering;
  10779. this.alphaTest = source.alphaTest;
  10780. this.alphaHash = source.alphaHash;
  10781. this.alphaToCoverage = source.alphaToCoverage;
  10782. this.premultipliedAlpha = source.premultipliedAlpha;
  10783. this.forceSinglePass = source.forceSinglePass;
  10784. this.visible = source.visible;
  10785. this.toneMapped = source.toneMapped;
  10786. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  10787. return this;
  10788. }
  10789. /**
  10790. * Frees the GPU-related resources allocated by this instance. Call this
  10791. * method whenever this instance is no longer used in your app.
  10792. *
  10793. * @fires Material#dispose
  10794. */
  10795. dispose() {
  10796. /**
  10797. * Fires when the material has been disposed of.
  10798. *
  10799. * @event Material#dispose
  10800. * @type {Object}
  10801. */
  10802. this.dispatchEvent( { type: 'dispose' } );
  10803. }
  10804. /**
  10805. * Setting this property to `true` indicates the engine the material
  10806. * needs to be recompiled.
  10807. *
  10808. * @type {boolean}
  10809. * @default false
  10810. * @param {boolean} value
  10811. */
  10812. set needsUpdate( value ) {
  10813. if ( value === true ) this.version ++;
  10814. }
  10815. onBuild( /* shaderobject, renderer */ ) {
  10816. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  10817. }
  10818. }
  10819. class MeshBasicMaterial extends Material {
  10820. constructor( parameters ) {
  10821. super();
  10822. this.isMeshBasicMaterial = true;
  10823. this.type = 'MeshBasicMaterial';
  10824. this.color = new Color( 0xffffff ); // emissive
  10825. this.map = null;
  10826. this.lightMap = null;
  10827. this.lightMapIntensity = 1.0;
  10828. this.aoMap = null;
  10829. this.aoMapIntensity = 1.0;
  10830. this.specularMap = null;
  10831. this.alphaMap = null;
  10832. this.envMap = null;
  10833. this.envMapRotation = new Euler();
  10834. this.combine = MultiplyOperation;
  10835. this.reflectivity = 1;
  10836. this.refractionRatio = 0.98;
  10837. this.wireframe = false;
  10838. this.wireframeLinewidth = 1;
  10839. this.wireframeLinecap = 'round';
  10840. this.wireframeLinejoin = 'round';
  10841. this.fog = true;
  10842. this.setValues( parameters );
  10843. }
  10844. copy( source ) {
  10845. super.copy( source );
  10846. this.color.copy( source.color );
  10847. this.map = source.map;
  10848. this.lightMap = source.lightMap;
  10849. this.lightMapIntensity = source.lightMapIntensity;
  10850. this.aoMap = source.aoMap;
  10851. this.aoMapIntensity = source.aoMapIntensity;
  10852. this.specularMap = source.specularMap;
  10853. this.alphaMap = source.alphaMap;
  10854. this.envMap = source.envMap;
  10855. this.envMapRotation.copy( source.envMapRotation );
  10856. this.combine = source.combine;
  10857. this.reflectivity = source.reflectivity;
  10858. this.refractionRatio = source.refractionRatio;
  10859. this.wireframe = source.wireframe;
  10860. this.wireframeLinewidth = source.wireframeLinewidth;
  10861. this.wireframeLinecap = source.wireframeLinecap;
  10862. this.wireframeLinejoin = source.wireframeLinejoin;
  10863. this.fog = source.fog;
  10864. return this;
  10865. }
  10866. }
  10867. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  10868. const _tables = /*@__PURE__*/ _generateTables();
  10869. function _generateTables() {
  10870. // float32 to float16 helpers
  10871. const buffer = new ArrayBuffer( 4 );
  10872. const floatView = new Float32Array( buffer );
  10873. const uint32View = new Uint32Array( buffer );
  10874. const baseTable = new Uint32Array( 512 );
  10875. const shiftTable = new Uint32Array( 512 );
  10876. for ( let i = 0; i < 256; ++ i ) {
  10877. const e = i - 127;
  10878. // very small number (0, -0)
  10879. if ( e < -27 ) {
  10880. baseTable[ i ] = 0x0000;
  10881. baseTable[ i | 0x100 ] = 0x8000;
  10882. shiftTable[ i ] = 24;
  10883. shiftTable[ i | 0x100 ] = 24;
  10884. // small number (denorm)
  10885. } else if ( e < -14 ) {
  10886. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  10887. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  10888. shiftTable[ i ] = - e - 1;
  10889. shiftTable[ i | 0x100 ] = - e - 1;
  10890. // normal number
  10891. } else if ( e <= 15 ) {
  10892. baseTable[ i ] = ( e + 15 ) << 10;
  10893. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  10894. shiftTable[ i ] = 13;
  10895. shiftTable[ i | 0x100 ] = 13;
  10896. // large number (Infinity, -Infinity)
  10897. } else if ( e < 128 ) {
  10898. baseTable[ i ] = 0x7c00;
  10899. baseTable[ i | 0x100 ] = 0xfc00;
  10900. shiftTable[ i ] = 24;
  10901. shiftTable[ i | 0x100 ] = 24;
  10902. // stay (NaN, Infinity, -Infinity)
  10903. } else {
  10904. baseTable[ i ] = 0x7c00;
  10905. baseTable[ i | 0x100 ] = 0xfc00;
  10906. shiftTable[ i ] = 13;
  10907. shiftTable[ i | 0x100 ] = 13;
  10908. }
  10909. }
  10910. // float16 to float32 helpers
  10911. const mantissaTable = new Uint32Array( 2048 );
  10912. const exponentTable = new Uint32Array( 64 );
  10913. const offsetTable = new Uint32Array( 64 );
  10914. for ( let i = 1; i < 1024; ++ i ) {
  10915. let m = i << 13; // zero pad mantissa bits
  10916. let e = 0; // zero exponent
  10917. // normalized
  10918. while ( ( m & 0x00800000 ) === 0 ) {
  10919. m <<= 1;
  10920. e -= 0x00800000; // decrement exponent
  10921. }
  10922. m &= -8388609; // clear leading 1 bit
  10923. e += 0x38800000; // adjust bias
  10924. mantissaTable[ i ] = m | e;
  10925. }
  10926. for ( let i = 1024; i < 2048; ++ i ) {
  10927. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  10928. }
  10929. for ( let i = 1; i < 31; ++ i ) {
  10930. exponentTable[ i ] = i << 23;
  10931. }
  10932. exponentTable[ 31 ] = 0x47800000;
  10933. exponentTable[ 32 ] = 0x80000000;
  10934. for ( let i = 33; i < 63; ++ i ) {
  10935. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  10936. }
  10937. exponentTable[ 63 ] = 0xc7800000;
  10938. for ( let i = 1; i < 64; ++ i ) {
  10939. if ( i !== 32 ) {
  10940. offsetTable[ i ] = 1024;
  10941. }
  10942. }
  10943. return {
  10944. floatView: floatView,
  10945. uint32View: uint32View,
  10946. baseTable: baseTable,
  10947. shiftTable: shiftTable,
  10948. mantissaTable: mantissaTable,
  10949. exponentTable: exponentTable,
  10950. offsetTable: offsetTable
  10951. };
  10952. }
  10953. /**
  10954. * Returns a half precision floating point value (FP16) from the given single
  10955. * precision floating point value (FP32).
  10956. *
  10957. * @param {number} val - A single precision floating point value.
  10958. * @return {number} The FP16 value.
  10959. */
  10960. function toHalfFloat( val ) {
  10961. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  10962. val = clamp( val, -65504, 65504 );
  10963. _tables.floatView[ 0 ] = val;
  10964. const f = _tables.uint32View[ 0 ];
  10965. const e = ( f >> 23 ) & 0x1ff;
  10966. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  10967. }
  10968. /**
  10969. * Returns a single precision floating point value (FP32) from the given half
  10970. * precision floating point value (FP16).
  10971. *
  10972. * @param {number} val - A half precision floating point value.
  10973. * @return {number} The FP32 value.
  10974. */
  10975. function fromHalfFloat( val ) {
  10976. const m = val >> 10;
  10977. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  10978. return _tables.floatView[ 0 ];
  10979. }
  10980. /**
  10981. * A class containing utility functions for data.
  10982. *
  10983. * @hideconstructor
  10984. */
  10985. class DataUtils {
  10986. /**
  10987. * Returns a half precision floating point value (FP16) from the given single
  10988. * precision floating point value (FP32).
  10989. *
  10990. * @param {number} val - A single precision floating point value.
  10991. * @return {number} The FP16 value.
  10992. */
  10993. static toHalfFloat( val ) {
  10994. return toHalfFloat( val );
  10995. }
  10996. /**
  10997. * Returns a single precision floating point value (FP32) from the given half
  10998. * precision floating point value (FP16).
  10999. *
  11000. * @param {number} val - A half precision floating point value.
  11001. * @return {number} The FP32 value.
  11002. */
  11003. static fromHalfFloat( val ) {
  11004. return fromHalfFloat( val );
  11005. }
  11006. }
  11007. const _vector$9 = /*@__PURE__*/ new Vector3();
  11008. const _vector2$1 = /*@__PURE__*/ new Vector2();
  11009. let _id$2 = 0;
  11010. class BufferAttribute {
  11011. constructor( array, itemSize, normalized = false ) {
  11012. if ( Array.isArray( array ) ) {
  11013. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11014. }
  11015. this.isBufferAttribute = true;
  11016. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  11017. this.name = '';
  11018. this.array = array;
  11019. this.itemSize = itemSize;
  11020. this.count = array !== undefined ? array.length / itemSize : 0;
  11021. this.normalized = normalized;
  11022. this.usage = StaticDrawUsage;
  11023. this.updateRanges = [];
  11024. this.gpuType = FloatType;
  11025. this.version = 0;
  11026. }
  11027. onUploadCallback() {}
  11028. set needsUpdate( value ) {
  11029. if ( value === true ) this.version ++;
  11030. }
  11031. setUsage( value ) {
  11032. this.usage = value;
  11033. return this;
  11034. }
  11035. addUpdateRange( start, count ) {
  11036. this.updateRanges.push( { start, count } );
  11037. }
  11038. clearUpdateRanges() {
  11039. this.updateRanges.length = 0;
  11040. }
  11041. copy( source ) {
  11042. this.name = source.name;
  11043. this.array = new source.array.constructor( source.array );
  11044. this.itemSize = source.itemSize;
  11045. this.count = source.count;
  11046. this.normalized = source.normalized;
  11047. this.usage = source.usage;
  11048. this.gpuType = source.gpuType;
  11049. return this;
  11050. }
  11051. copyAt( index1, attribute, index2 ) {
  11052. index1 *= this.itemSize;
  11053. index2 *= attribute.itemSize;
  11054. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  11055. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11056. }
  11057. return this;
  11058. }
  11059. copyArray( array ) {
  11060. this.array.set( array );
  11061. return this;
  11062. }
  11063. applyMatrix3( m ) {
  11064. if ( this.itemSize === 2 ) {
  11065. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11066. _vector2$1.fromBufferAttribute( this, i );
  11067. _vector2$1.applyMatrix3( m );
  11068. this.setXY( i, _vector2$1.x, _vector2$1.y );
  11069. }
  11070. } else if ( this.itemSize === 3 ) {
  11071. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11072. _vector$9.fromBufferAttribute( this, i );
  11073. _vector$9.applyMatrix3( m );
  11074. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11075. }
  11076. }
  11077. return this;
  11078. }
  11079. applyMatrix4( m ) {
  11080. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11081. _vector$9.fromBufferAttribute( this, i );
  11082. _vector$9.applyMatrix4( m );
  11083. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11084. }
  11085. return this;
  11086. }
  11087. applyNormalMatrix( m ) {
  11088. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11089. _vector$9.fromBufferAttribute( this, i );
  11090. _vector$9.applyNormalMatrix( m );
  11091. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11092. }
  11093. return this;
  11094. }
  11095. transformDirection( m ) {
  11096. for ( let i = 0, l = this.count; i < l; i ++ ) {
  11097. _vector$9.fromBufferAttribute( this, i );
  11098. _vector$9.transformDirection( m );
  11099. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  11100. }
  11101. return this;
  11102. }
  11103. set( value, offset = 0 ) {
  11104. // Matching BufferAttribute constructor, do not normalize the array.
  11105. this.array.set( value, offset );
  11106. return this;
  11107. }
  11108. getComponent( index, component ) {
  11109. let value = this.array[ index * this.itemSize + component ];
  11110. if ( this.normalized ) value = denormalize( value, this.array );
  11111. return value;
  11112. }
  11113. setComponent( index, component, value ) {
  11114. if ( this.normalized ) value = normalize( value, this.array );
  11115. this.array[ index * this.itemSize + component ] = value;
  11116. return this;
  11117. }
  11118. getX( index ) {
  11119. let x = this.array[ index * this.itemSize ];
  11120. if ( this.normalized ) x = denormalize( x, this.array );
  11121. return x;
  11122. }
  11123. setX( index, x ) {
  11124. if ( this.normalized ) x = normalize( x, this.array );
  11125. this.array[ index * this.itemSize ] = x;
  11126. return this;
  11127. }
  11128. getY( index ) {
  11129. let y = this.array[ index * this.itemSize + 1 ];
  11130. if ( this.normalized ) y = denormalize( y, this.array );
  11131. return y;
  11132. }
  11133. setY( index, y ) {
  11134. if ( this.normalized ) y = normalize( y, this.array );
  11135. this.array[ index * this.itemSize + 1 ] = y;
  11136. return this;
  11137. }
  11138. getZ( index ) {
  11139. let z = this.array[ index * this.itemSize + 2 ];
  11140. if ( this.normalized ) z = denormalize( z, this.array );
  11141. return z;
  11142. }
  11143. setZ( index, z ) {
  11144. if ( this.normalized ) z = normalize( z, this.array );
  11145. this.array[ index * this.itemSize + 2 ] = z;
  11146. return this;
  11147. }
  11148. getW( index ) {
  11149. let w = this.array[ index * this.itemSize + 3 ];
  11150. if ( this.normalized ) w = denormalize( w, this.array );
  11151. return w;
  11152. }
  11153. setW( index, w ) {
  11154. if ( this.normalized ) w = normalize( w, this.array );
  11155. this.array[ index * this.itemSize + 3 ] = w;
  11156. return this;
  11157. }
  11158. setXY( index, x, y ) {
  11159. index *= this.itemSize;
  11160. if ( this.normalized ) {
  11161. x = normalize( x, this.array );
  11162. y = normalize( y, this.array );
  11163. }
  11164. this.array[ index + 0 ] = x;
  11165. this.array[ index + 1 ] = y;
  11166. return this;
  11167. }
  11168. setXYZ( index, x, y, z ) {
  11169. index *= this.itemSize;
  11170. if ( this.normalized ) {
  11171. x = normalize( x, this.array );
  11172. y = normalize( y, this.array );
  11173. z = normalize( z, this.array );
  11174. }
  11175. this.array[ index + 0 ] = x;
  11176. this.array[ index + 1 ] = y;
  11177. this.array[ index + 2 ] = z;
  11178. return this;
  11179. }
  11180. setXYZW( index, x, y, z, w ) {
  11181. index *= this.itemSize;
  11182. if ( this.normalized ) {
  11183. x = normalize( x, this.array );
  11184. y = normalize( y, this.array );
  11185. z = normalize( z, this.array );
  11186. w = normalize( w, this.array );
  11187. }
  11188. this.array[ index + 0 ] = x;
  11189. this.array[ index + 1 ] = y;
  11190. this.array[ index + 2 ] = z;
  11191. this.array[ index + 3 ] = w;
  11192. return this;
  11193. }
  11194. onUpload( callback ) {
  11195. this.onUploadCallback = callback;
  11196. return this;
  11197. }
  11198. clone() {
  11199. return new this.constructor( this.array, this.itemSize ).copy( this );
  11200. }
  11201. toJSON() {
  11202. const data = {
  11203. itemSize: this.itemSize,
  11204. type: this.array.constructor.name,
  11205. array: Array.from( this.array ),
  11206. normalized: this.normalized
  11207. };
  11208. if ( this.name !== '' ) data.name = this.name;
  11209. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  11210. return data;
  11211. }
  11212. }
  11213. //
  11214. class Int8BufferAttribute extends BufferAttribute {
  11215. constructor( array, itemSize, normalized ) {
  11216. super( new Int8Array( array ), itemSize, normalized );
  11217. }
  11218. }
  11219. class Uint8BufferAttribute extends BufferAttribute {
  11220. constructor( array, itemSize, normalized ) {
  11221. super( new Uint8Array( array ), itemSize, normalized );
  11222. }
  11223. }
  11224. class Uint8ClampedBufferAttribute extends BufferAttribute {
  11225. constructor( array, itemSize, normalized ) {
  11226. super( new Uint8ClampedArray( array ), itemSize, normalized );
  11227. }
  11228. }
  11229. class Int16BufferAttribute extends BufferAttribute {
  11230. constructor( array, itemSize, normalized ) {
  11231. super( new Int16Array( array ), itemSize, normalized );
  11232. }
  11233. }
  11234. class Uint16BufferAttribute extends BufferAttribute {
  11235. constructor( array, itemSize, normalized ) {
  11236. super( new Uint16Array( array ), itemSize, normalized );
  11237. }
  11238. }
  11239. class Int32BufferAttribute extends BufferAttribute {
  11240. constructor( array, itemSize, normalized ) {
  11241. super( new Int32Array( array ), itemSize, normalized );
  11242. }
  11243. }
  11244. class Uint32BufferAttribute extends BufferAttribute {
  11245. constructor( array, itemSize, normalized ) {
  11246. super( new Uint32Array( array ), itemSize, normalized );
  11247. }
  11248. }
  11249. class Float16BufferAttribute extends BufferAttribute {
  11250. constructor( array, itemSize, normalized ) {
  11251. super( new Uint16Array( array ), itemSize, normalized );
  11252. this.isFloat16BufferAttribute = true;
  11253. }
  11254. getX( index ) {
  11255. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  11256. if ( this.normalized ) x = denormalize( x, this.array );
  11257. return x;
  11258. }
  11259. setX( index, x ) {
  11260. if ( this.normalized ) x = normalize( x, this.array );
  11261. this.array[ index * this.itemSize ] = toHalfFloat( x );
  11262. return this;
  11263. }
  11264. getY( index ) {
  11265. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  11266. if ( this.normalized ) y = denormalize( y, this.array );
  11267. return y;
  11268. }
  11269. setY( index, y ) {
  11270. if ( this.normalized ) y = normalize( y, this.array );
  11271. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  11272. return this;
  11273. }
  11274. getZ( index ) {
  11275. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  11276. if ( this.normalized ) z = denormalize( z, this.array );
  11277. return z;
  11278. }
  11279. setZ( index, z ) {
  11280. if ( this.normalized ) z = normalize( z, this.array );
  11281. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  11282. return this;
  11283. }
  11284. getW( index ) {
  11285. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  11286. if ( this.normalized ) w = denormalize( w, this.array );
  11287. return w;
  11288. }
  11289. setW( index, w ) {
  11290. if ( this.normalized ) w = normalize( w, this.array );
  11291. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  11292. return this;
  11293. }
  11294. setXY( index, x, y ) {
  11295. index *= this.itemSize;
  11296. if ( this.normalized ) {
  11297. x = normalize( x, this.array );
  11298. y = normalize( y, this.array );
  11299. }
  11300. this.array[ index + 0 ] = toHalfFloat( x );
  11301. this.array[ index + 1 ] = toHalfFloat( y );
  11302. return this;
  11303. }
  11304. setXYZ( index, x, y, z ) {
  11305. index *= this.itemSize;
  11306. if ( this.normalized ) {
  11307. x = normalize( x, this.array );
  11308. y = normalize( y, this.array );
  11309. z = normalize( z, this.array );
  11310. }
  11311. this.array[ index + 0 ] = toHalfFloat( x );
  11312. this.array[ index + 1 ] = toHalfFloat( y );
  11313. this.array[ index + 2 ] = toHalfFloat( z );
  11314. return this;
  11315. }
  11316. setXYZW( index, x, y, z, w ) {
  11317. index *= this.itemSize;
  11318. if ( this.normalized ) {
  11319. x = normalize( x, this.array );
  11320. y = normalize( y, this.array );
  11321. z = normalize( z, this.array );
  11322. w = normalize( w, this.array );
  11323. }
  11324. this.array[ index + 0 ] = toHalfFloat( x );
  11325. this.array[ index + 1 ] = toHalfFloat( y );
  11326. this.array[ index + 2 ] = toHalfFloat( z );
  11327. this.array[ index + 3 ] = toHalfFloat( w );
  11328. return this;
  11329. }
  11330. }
  11331. class Float32BufferAttribute extends BufferAttribute {
  11332. constructor( array, itemSize, normalized ) {
  11333. super( new Float32Array( array ), itemSize, normalized );
  11334. }
  11335. }
  11336. let _id$1 = 0;
  11337. const _m1 = /*@__PURE__*/ new Matrix4();
  11338. const _obj = /*@__PURE__*/ new Object3D();
  11339. const _offset = /*@__PURE__*/ new Vector3();
  11340. const _box$2 = /*@__PURE__*/ new Box3();
  11341. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  11342. const _vector$8 = /*@__PURE__*/ new Vector3();
  11343. class BufferGeometry extends EventDispatcher {
  11344. constructor() {
  11345. super();
  11346. this.isBufferGeometry = true;
  11347. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  11348. this.uuid = generateUUID();
  11349. this.name = '';
  11350. this.type = 'BufferGeometry';
  11351. this.index = null;
  11352. this.indirect = null;
  11353. this.attributes = {};
  11354. this.morphAttributes = {};
  11355. this.morphTargetsRelative = false;
  11356. this.groups = [];
  11357. this.boundingBox = null;
  11358. this.boundingSphere = null;
  11359. this.drawRange = { start: 0, count: Infinity };
  11360. this.userData = {};
  11361. }
  11362. getIndex() {
  11363. return this.index;
  11364. }
  11365. setIndex( index ) {
  11366. if ( Array.isArray( index ) ) {
  11367. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  11368. } else {
  11369. this.index = index;
  11370. }
  11371. return this;
  11372. }
  11373. setIndirect( indirect ) {
  11374. this.indirect = indirect;
  11375. return this;
  11376. }
  11377. getIndirect() {
  11378. return this.indirect;
  11379. }
  11380. getAttribute( name ) {
  11381. return this.attributes[ name ];
  11382. }
  11383. setAttribute( name, attribute ) {
  11384. this.attributes[ name ] = attribute;
  11385. return this;
  11386. }
  11387. deleteAttribute( name ) {
  11388. delete this.attributes[ name ];
  11389. return this;
  11390. }
  11391. hasAttribute( name ) {
  11392. return this.attributes[ name ] !== undefined;
  11393. }
  11394. addGroup( start, count, materialIndex = 0 ) {
  11395. this.groups.push( {
  11396. start: start,
  11397. count: count,
  11398. materialIndex: materialIndex
  11399. } );
  11400. }
  11401. clearGroups() {
  11402. this.groups = [];
  11403. }
  11404. setDrawRange( start, count ) {
  11405. this.drawRange.start = start;
  11406. this.drawRange.count = count;
  11407. }
  11408. applyMatrix4( matrix ) {
  11409. const position = this.attributes.position;
  11410. if ( position !== undefined ) {
  11411. position.applyMatrix4( matrix );
  11412. position.needsUpdate = true;
  11413. }
  11414. const normal = this.attributes.normal;
  11415. if ( normal !== undefined ) {
  11416. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11417. normal.applyNormalMatrix( normalMatrix );
  11418. normal.needsUpdate = true;
  11419. }
  11420. const tangent = this.attributes.tangent;
  11421. if ( tangent !== undefined ) {
  11422. tangent.transformDirection( matrix );
  11423. tangent.needsUpdate = true;
  11424. }
  11425. if ( this.boundingBox !== null ) {
  11426. this.computeBoundingBox();
  11427. }
  11428. if ( this.boundingSphere !== null ) {
  11429. this.computeBoundingSphere();
  11430. }
  11431. return this;
  11432. }
  11433. applyQuaternion( q ) {
  11434. _m1.makeRotationFromQuaternion( q );
  11435. this.applyMatrix4( _m1 );
  11436. return this;
  11437. }
  11438. rotateX( angle ) {
  11439. // rotate geometry around world x-axis
  11440. _m1.makeRotationX( angle );
  11441. this.applyMatrix4( _m1 );
  11442. return this;
  11443. }
  11444. rotateY( angle ) {
  11445. // rotate geometry around world y-axis
  11446. _m1.makeRotationY( angle );
  11447. this.applyMatrix4( _m1 );
  11448. return this;
  11449. }
  11450. rotateZ( angle ) {
  11451. // rotate geometry around world z-axis
  11452. _m1.makeRotationZ( angle );
  11453. this.applyMatrix4( _m1 );
  11454. return this;
  11455. }
  11456. translate( x, y, z ) {
  11457. // translate geometry
  11458. _m1.makeTranslation( x, y, z );
  11459. this.applyMatrix4( _m1 );
  11460. return this;
  11461. }
  11462. scale( x, y, z ) {
  11463. // scale geometry
  11464. _m1.makeScale( x, y, z );
  11465. this.applyMatrix4( _m1 );
  11466. return this;
  11467. }
  11468. lookAt( vector ) {
  11469. _obj.lookAt( vector );
  11470. _obj.updateMatrix();
  11471. this.applyMatrix4( _obj.matrix );
  11472. return this;
  11473. }
  11474. center() {
  11475. this.computeBoundingBox();
  11476. this.boundingBox.getCenter( _offset ).negate();
  11477. this.translate( _offset.x, _offset.y, _offset.z );
  11478. return this;
  11479. }
  11480. setFromPoints( points ) {
  11481. const positionAttribute = this.getAttribute( 'position' );
  11482. if ( positionAttribute === undefined ) {
  11483. const position = [];
  11484. for ( let i = 0, l = points.length; i < l; i ++ ) {
  11485. const point = points[ i ];
  11486. position.push( point.x, point.y, point.z || 0 );
  11487. }
  11488. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  11489. } else {
  11490. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  11491. for ( let i = 0; i < l; i ++ ) {
  11492. const point = points[ i ];
  11493. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  11494. }
  11495. if ( points.length > positionAttribute.count ) {
  11496. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  11497. }
  11498. positionAttribute.needsUpdate = true;
  11499. }
  11500. return this;
  11501. }
  11502. computeBoundingBox() {
  11503. if ( this.boundingBox === null ) {
  11504. this.boundingBox = new Box3();
  11505. }
  11506. const position = this.attributes.position;
  11507. const morphAttributesPosition = this.morphAttributes.position;
  11508. if ( position && position.isGLBufferAttribute ) {
  11509. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  11510. this.boundingBox.set(
  11511. new Vector3( - Infinity, - Infinity, - Infinity ),
  11512. new Vector3( + Infinity, + Infinity, + Infinity )
  11513. );
  11514. return;
  11515. }
  11516. if ( position !== undefined ) {
  11517. this.boundingBox.setFromBufferAttribute( position );
  11518. // process morph attributes if present
  11519. if ( morphAttributesPosition ) {
  11520. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11521. const morphAttribute = morphAttributesPosition[ i ];
  11522. _box$2.setFromBufferAttribute( morphAttribute );
  11523. if ( this.morphTargetsRelative ) {
  11524. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  11525. this.boundingBox.expandByPoint( _vector$8 );
  11526. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  11527. this.boundingBox.expandByPoint( _vector$8 );
  11528. } else {
  11529. this.boundingBox.expandByPoint( _box$2.min );
  11530. this.boundingBox.expandByPoint( _box$2.max );
  11531. }
  11532. }
  11533. }
  11534. } else {
  11535. this.boundingBox.makeEmpty();
  11536. }
  11537. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  11538. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  11539. }
  11540. }
  11541. computeBoundingSphere() {
  11542. if ( this.boundingSphere === null ) {
  11543. this.boundingSphere = new Sphere();
  11544. }
  11545. const position = this.attributes.position;
  11546. const morphAttributesPosition = this.morphAttributes.position;
  11547. if ( position && position.isGLBufferAttribute ) {
  11548. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  11549. this.boundingSphere.set( new Vector3(), Infinity );
  11550. return;
  11551. }
  11552. if ( position ) {
  11553. // first, find the center of the bounding sphere
  11554. const center = this.boundingSphere.center;
  11555. _box$2.setFromBufferAttribute( position );
  11556. // process morph attributes if present
  11557. if ( morphAttributesPosition ) {
  11558. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11559. const morphAttribute = morphAttributesPosition[ i ];
  11560. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  11561. if ( this.morphTargetsRelative ) {
  11562. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  11563. _box$2.expandByPoint( _vector$8 );
  11564. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  11565. _box$2.expandByPoint( _vector$8 );
  11566. } else {
  11567. _box$2.expandByPoint( _boxMorphTargets.min );
  11568. _box$2.expandByPoint( _boxMorphTargets.max );
  11569. }
  11570. }
  11571. }
  11572. _box$2.getCenter( center );
  11573. // second, try to find a boundingSphere with a radius smaller than the
  11574. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  11575. let maxRadiusSq = 0;
  11576. for ( let i = 0, il = position.count; i < il; i ++ ) {
  11577. _vector$8.fromBufferAttribute( position, i );
  11578. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11579. }
  11580. // process morph attributes if present
  11581. if ( morphAttributesPosition ) {
  11582. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  11583. const morphAttribute = morphAttributesPosition[ i ];
  11584. const morphTargetsRelative = this.morphTargetsRelative;
  11585. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  11586. _vector$8.fromBufferAttribute( morphAttribute, j );
  11587. if ( morphTargetsRelative ) {
  11588. _offset.fromBufferAttribute( position, j );
  11589. _vector$8.add( _offset );
  11590. }
  11591. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  11592. }
  11593. }
  11594. }
  11595. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  11596. if ( isNaN( this.boundingSphere.radius ) ) {
  11597. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  11598. }
  11599. }
  11600. }
  11601. computeTangents() {
  11602. const index = this.index;
  11603. const attributes = this.attributes;
  11604. // based on http://www.terathon.com/code/tangent.html
  11605. // (per vertex tangents)
  11606. if ( index === null ||
  11607. attributes.position === undefined ||
  11608. attributes.normal === undefined ||
  11609. attributes.uv === undefined ) {
  11610. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  11611. return;
  11612. }
  11613. const positionAttribute = attributes.position;
  11614. const normalAttribute = attributes.normal;
  11615. const uvAttribute = attributes.uv;
  11616. if ( this.hasAttribute( 'tangent' ) === false ) {
  11617. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  11618. }
  11619. const tangentAttribute = this.getAttribute( 'tangent' );
  11620. const tan1 = [], tan2 = [];
  11621. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  11622. tan1[ i ] = new Vector3();
  11623. tan2[ i ] = new Vector3();
  11624. }
  11625. const vA = new Vector3(),
  11626. vB = new Vector3(),
  11627. vC = new Vector3(),
  11628. uvA = new Vector2(),
  11629. uvB = new Vector2(),
  11630. uvC = new Vector2(),
  11631. sdir = new Vector3(),
  11632. tdir = new Vector3();
  11633. function handleTriangle( a, b, c ) {
  11634. vA.fromBufferAttribute( positionAttribute, a );
  11635. vB.fromBufferAttribute( positionAttribute, b );
  11636. vC.fromBufferAttribute( positionAttribute, c );
  11637. uvA.fromBufferAttribute( uvAttribute, a );
  11638. uvB.fromBufferAttribute( uvAttribute, b );
  11639. uvC.fromBufferAttribute( uvAttribute, c );
  11640. vB.sub( vA );
  11641. vC.sub( vA );
  11642. uvB.sub( uvA );
  11643. uvC.sub( uvA );
  11644. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  11645. // silently ignore degenerate uv triangles having coincident or colinear vertices
  11646. if ( ! isFinite( r ) ) return;
  11647. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  11648. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  11649. tan1[ a ].add( sdir );
  11650. tan1[ b ].add( sdir );
  11651. tan1[ c ].add( sdir );
  11652. tan2[ a ].add( tdir );
  11653. tan2[ b ].add( tdir );
  11654. tan2[ c ].add( tdir );
  11655. }
  11656. let groups = this.groups;
  11657. if ( groups.length === 0 ) {
  11658. groups = [ {
  11659. start: 0,
  11660. count: index.count
  11661. } ];
  11662. }
  11663. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11664. const group = groups[ i ];
  11665. const start = group.start;
  11666. const count = group.count;
  11667. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11668. handleTriangle(
  11669. index.getX( j + 0 ),
  11670. index.getX( j + 1 ),
  11671. index.getX( j + 2 )
  11672. );
  11673. }
  11674. }
  11675. const tmp = new Vector3(), tmp2 = new Vector3();
  11676. const n = new Vector3(), n2 = new Vector3();
  11677. function handleVertex( v ) {
  11678. n.fromBufferAttribute( normalAttribute, v );
  11679. n2.copy( n );
  11680. const t = tan1[ v ];
  11681. // Gram-Schmidt orthogonalize
  11682. tmp.copy( t );
  11683. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  11684. // Calculate handedness
  11685. tmp2.crossVectors( n2, t );
  11686. const test = tmp2.dot( tan2[ v ] );
  11687. const w = ( test < 0.0 ) ? -1 : 1.0;
  11688. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  11689. }
  11690. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  11691. const group = groups[ i ];
  11692. const start = group.start;
  11693. const count = group.count;
  11694. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  11695. handleVertex( index.getX( j + 0 ) );
  11696. handleVertex( index.getX( j + 1 ) );
  11697. handleVertex( index.getX( j + 2 ) );
  11698. }
  11699. }
  11700. }
  11701. computeVertexNormals() {
  11702. const index = this.index;
  11703. const positionAttribute = this.getAttribute( 'position' );
  11704. if ( positionAttribute !== undefined ) {
  11705. let normalAttribute = this.getAttribute( 'normal' );
  11706. if ( normalAttribute === undefined ) {
  11707. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  11708. this.setAttribute( 'normal', normalAttribute );
  11709. } else {
  11710. // reset existing normals to zero
  11711. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  11712. normalAttribute.setXYZ( i, 0, 0, 0 );
  11713. }
  11714. }
  11715. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  11716. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  11717. const cb = new Vector3(), ab = new Vector3();
  11718. // indexed elements
  11719. if ( index ) {
  11720. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  11721. const vA = index.getX( i + 0 );
  11722. const vB = index.getX( i + 1 );
  11723. const vC = index.getX( i + 2 );
  11724. pA.fromBufferAttribute( positionAttribute, vA );
  11725. pB.fromBufferAttribute( positionAttribute, vB );
  11726. pC.fromBufferAttribute( positionAttribute, vC );
  11727. cb.subVectors( pC, pB );
  11728. ab.subVectors( pA, pB );
  11729. cb.cross( ab );
  11730. nA.fromBufferAttribute( normalAttribute, vA );
  11731. nB.fromBufferAttribute( normalAttribute, vB );
  11732. nC.fromBufferAttribute( normalAttribute, vC );
  11733. nA.add( cb );
  11734. nB.add( cb );
  11735. nC.add( cb );
  11736. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  11737. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  11738. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  11739. }
  11740. } else {
  11741. // non-indexed elements (unconnected triangle soup)
  11742. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  11743. pA.fromBufferAttribute( positionAttribute, i + 0 );
  11744. pB.fromBufferAttribute( positionAttribute, i + 1 );
  11745. pC.fromBufferAttribute( positionAttribute, i + 2 );
  11746. cb.subVectors( pC, pB );
  11747. ab.subVectors( pA, pB );
  11748. cb.cross( ab );
  11749. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  11750. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  11751. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  11752. }
  11753. }
  11754. this.normalizeNormals();
  11755. normalAttribute.needsUpdate = true;
  11756. }
  11757. }
  11758. normalizeNormals() {
  11759. const normals = this.attributes.normal;
  11760. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  11761. _vector$8.fromBufferAttribute( normals, i );
  11762. _vector$8.normalize();
  11763. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  11764. }
  11765. }
  11766. toNonIndexed() {
  11767. function convertBufferAttribute( attribute, indices ) {
  11768. const array = attribute.array;
  11769. const itemSize = attribute.itemSize;
  11770. const normalized = attribute.normalized;
  11771. const array2 = new array.constructor( indices.length * itemSize );
  11772. let index = 0, index2 = 0;
  11773. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  11774. if ( attribute.isInterleavedBufferAttribute ) {
  11775. index = indices[ i ] * attribute.data.stride + attribute.offset;
  11776. } else {
  11777. index = indices[ i ] * itemSize;
  11778. }
  11779. for ( let j = 0; j < itemSize; j ++ ) {
  11780. array2[ index2 ++ ] = array[ index ++ ];
  11781. }
  11782. }
  11783. return new BufferAttribute( array2, itemSize, normalized );
  11784. }
  11785. //
  11786. if ( this.index === null ) {
  11787. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  11788. return this;
  11789. }
  11790. const geometry2 = new BufferGeometry();
  11791. const indices = this.index.array;
  11792. const attributes = this.attributes;
  11793. // attributes
  11794. for ( const name in attributes ) {
  11795. const attribute = attributes[ name ];
  11796. const newAttribute = convertBufferAttribute( attribute, indices );
  11797. geometry2.setAttribute( name, newAttribute );
  11798. }
  11799. // morph attributes
  11800. const morphAttributes = this.morphAttributes;
  11801. for ( const name in morphAttributes ) {
  11802. const morphArray = [];
  11803. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11804. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  11805. const attribute = morphAttribute[ i ];
  11806. const newAttribute = convertBufferAttribute( attribute, indices );
  11807. morphArray.push( newAttribute );
  11808. }
  11809. geometry2.morphAttributes[ name ] = morphArray;
  11810. }
  11811. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  11812. // groups
  11813. const groups = this.groups;
  11814. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11815. const group = groups[ i ];
  11816. geometry2.addGroup( group.start, group.count, group.materialIndex );
  11817. }
  11818. return geometry2;
  11819. }
  11820. toJSON() {
  11821. const data = {
  11822. metadata: {
  11823. version: 4.6,
  11824. type: 'BufferGeometry',
  11825. generator: 'BufferGeometry.toJSON'
  11826. }
  11827. };
  11828. // standard BufferGeometry serialization
  11829. data.uuid = this.uuid;
  11830. data.type = this.type;
  11831. if ( this.name !== '' ) data.name = this.name;
  11832. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  11833. if ( this.parameters !== undefined ) {
  11834. const parameters = this.parameters;
  11835. for ( const key in parameters ) {
  11836. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11837. }
  11838. return data;
  11839. }
  11840. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  11841. data.data = { attributes: {} };
  11842. const index = this.index;
  11843. if ( index !== null ) {
  11844. data.data.index = {
  11845. type: index.array.constructor.name,
  11846. array: Array.prototype.slice.call( index.array )
  11847. };
  11848. }
  11849. const attributes = this.attributes;
  11850. for ( const key in attributes ) {
  11851. const attribute = attributes[ key ];
  11852. data.data.attributes[ key ] = attribute.toJSON( data.data );
  11853. }
  11854. const morphAttributes = {};
  11855. let hasMorphAttributes = false;
  11856. for ( const key in this.morphAttributes ) {
  11857. const attributeArray = this.morphAttributes[ key ];
  11858. const array = [];
  11859. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  11860. const attribute = attributeArray[ i ];
  11861. array.push( attribute.toJSON( data.data ) );
  11862. }
  11863. if ( array.length > 0 ) {
  11864. morphAttributes[ key ] = array;
  11865. hasMorphAttributes = true;
  11866. }
  11867. }
  11868. if ( hasMorphAttributes ) {
  11869. data.data.morphAttributes = morphAttributes;
  11870. data.data.morphTargetsRelative = this.morphTargetsRelative;
  11871. }
  11872. const groups = this.groups;
  11873. if ( groups.length > 0 ) {
  11874. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  11875. }
  11876. const boundingSphere = this.boundingSphere;
  11877. if ( boundingSphere !== null ) {
  11878. data.data.boundingSphere = {
  11879. center: boundingSphere.center.toArray(),
  11880. radius: boundingSphere.radius
  11881. };
  11882. }
  11883. return data;
  11884. }
  11885. clone() {
  11886. return new this.constructor().copy( this );
  11887. }
  11888. copy( source ) {
  11889. // reset
  11890. this.index = null;
  11891. this.attributes = {};
  11892. this.morphAttributes = {};
  11893. this.groups = [];
  11894. this.boundingBox = null;
  11895. this.boundingSphere = null;
  11896. // used for storing cloned, shared data
  11897. const data = {};
  11898. // name
  11899. this.name = source.name;
  11900. // index
  11901. const index = source.index;
  11902. if ( index !== null ) {
  11903. this.setIndex( index.clone( data ) );
  11904. }
  11905. // attributes
  11906. const attributes = source.attributes;
  11907. for ( const name in attributes ) {
  11908. const attribute = attributes[ name ];
  11909. this.setAttribute( name, attribute.clone( data ) );
  11910. }
  11911. // morph attributes
  11912. const morphAttributes = source.morphAttributes;
  11913. for ( const name in morphAttributes ) {
  11914. const array = [];
  11915. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  11916. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  11917. array.push( morphAttribute[ i ].clone( data ) );
  11918. }
  11919. this.morphAttributes[ name ] = array;
  11920. }
  11921. this.morphTargetsRelative = source.morphTargetsRelative;
  11922. // groups
  11923. const groups = source.groups;
  11924. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  11925. const group = groups[ i ];
  11926. this.addGroup( group.start, group.count, group.materialIndex );
  11927. }
  11928. // bounding box
  11929. const boundingBox = source.boundingBox;
  11930. if ( boundingBox !== null ) {
  11931. this.boundingBox = boundingBox.clone();
  11932. }
  11933. // bounding sphere
  11934. const boundingSphere = source.boundingSphere;
  11935. if ( boundingSphere !== null ) {
  11936. this.boundingSphere = boundingSphere.clone();
  11937. }
  11938. // draw range
  11939. this.drawRange.start = source.drawRange.start;
  11940. this.drawRange.count = source.drawRange.count;
  11941. // user data
  11942. this.userData = source.userData;
  11943. return this;
  11944. }
  11945. dispose() {
  11946. this.dispatchEvent( { type: 'dispose' } );
  11947. }
  11948. }
  11949. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  11950. const _ray$3 = /*@__PURE__*/ new Ray();
  11951. const _sphere$6 = /*@__PURE__*/ new Sphere();
  11952. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  11953. const _vA$1 = /*@__PURE__*/ new Vector3();
  11954. const _vB$1 = /*@__PURE__*/ new Vector3();
  11955. const _vC$1 = /*@__PURE__*/ new Vector3();
  11956. const _tempA = /*@__PURE__*/ new Vector3();
  11957. const _morphA = /*@__PURE__*/ new Vector3();
  11958. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  11959. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  11960. /**
  11961. * Class representing triangular polygon mesh based objects.
  11962. *
  11963. * ```js
  11964. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  11965. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  11966. * const mesh = new THREE.Mesh( geometry, material );
  11967. * scene.add( mesh );
  11968. * ```
  11969. *
  11970. * @augments Object3D
  11971. */
  11972. class Mesh extends Object3D {
  11973. /**
  11974. * Constructs a new mesh.
  11975. *
  11976. * @param {BufferGeometry} [geometry] - The mesh geometry.
  11977. * @param {Material|Array<Material>} [material] - The mesh material.
  11978. */
  11979. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  11980. super();
  11981. /**
  11982. * This flag can be used for type testing.
  11983. *
  11984. * @type {boolean}
  11985. * @readonly
  11986. * @default true
  11987. */
  11988. this.isMesh = true;
  11989. this.type = 'Mesh';
  11990. /**
  11991. * The mesh geometry.
  11992. *
  11993. * @type {BufferGeometry}
  11994. */
  11995. this.geometry = geometry;
  11996. /**
  11997. * The mesh material.
  11998. *
  11999. * @type {Material|Array<Material>}
  12000. * @default MeshBasicMaterial
  12001. */
  12002. this.material = material;
  12003. /**
  12004. * A dictionary representing the morph targets in the geometry. The key is the
  12005. * morph targets name, the value its attribute index. This member is `undefined`
  12006. * by default and only set when morph targets are detected in the geometry.
  12007. *
  12008. * @type {Object<String,number>|undefined}
  12009. * @default undefined
  12010. */
  12011. this.morphTargetDictionary = undefined;
  12012. /**
  12013. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  12014. * is applied. This member is `undefined` by default and only set when morph targets are
  12015. * detected in the geometry.
  12016. *
  12017. * @type {Array<number>|undefined}
  12018. * @default undefined
  12019. */
  12020. this.morphTargetInfluences = undefined;
  12021. this.updateMorphTargets();
  12022. }
  12023. copy( source, recursive ) {
  12024. super.copy( source, recursive );
  12025. if ( source.morphTargetInfluences !== undefined ) {
  12026. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  12027. }
  12028. if ( source.morphTargetDictionary !== undefined ) {
  12029. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  12030. }
  12031. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  12032. this.geometry = source.geometry;
  12033. return this;
  12034. }
  12035. /**
  12036. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  12037. * to make sure existing morph targets can influence this 3D object.
  12038. */
  12039. updateMorphTargets() {
  12040. const geometry = this.geometry;
  12041. const morphAttributes = geometry.morphAttributes;
  12042. const keys = Object.keys( morphAttributes );
  12043. if ( keys.length > 0 ) {
  12044. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  12045. if ( morphAttribute !== undefined ) {
  12046. this.morphTargetInfluences = [];
  12047. this.morphTargetDictionary = {};
  12048. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  12049. const name = morphAttribute[ m ].name || String( m );
  12050. this.morphTargetInfluences.push( 0 );
  12051. this.morphTargetDictionary[ name ] = m;
  12052. }
  12053. }
  12054. }
  12055. }
  12056. /**
  12057. * Returns the local-space position of the vertex at the given index, taking into
  12058. * account the current animation state of both morph targets and skinning.
  12059. *
  12060. * @param {number} index - The vertex index.
  12061. * @param {Vector3} target - The target object that is used to store the method's result.
  12062. * @return {Vector3} The vertex position in local space.
  12063. */
  12064. getVertexPosition( index, target ) {
  12065. const geometry = this.geometry;
  12066. const position = geometry.attributes.position;
  12067. const morphPosition = geometry.morphAttributes.position;
  12068. const morphTargetsRelative = geometry.morphTargetsRelative;
  12069. target.fromBufferAttribute( position, index );
  12070. const morphInfluences = this.morphTargetInfluences;
  12071. if ( morphPosition && morphInfluences ) {
  12072. _morphA.set( 0, 0, 0 );
  12073. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  12074. const influence = morphInfluences[ i ];
  12075. const morphAttribute = morphPosition[ i ];
  12076. if ( influence === 0 ) continue;
  12077. _tempA.fromBufferAttribute( morphAttribute, index );
  12078. if ( morphTargetsRelative ) {
  12079. _morphA.addScaledVector( _tempA, influence );
  12080. } else {
  12081. _morphA.addScaledVector( _tempA.sub( target ), influence );
  12082. }
  12083. }
  12084. target.add( _morphA );
  12085. }
  12086. return target;
  12087. }
  12088. /**
  12089. * Computes intersection points between a casted ray and this line.
  12090. *
  12091. * @param {Raycaster} raycaster - The raycaster.
  12092. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  12093. */
  12094. raycast( raycaster, intersects ) {
  12095. const geometry = this.geometry;
  12096. const material = this.material;
  12097. const matrixWorld = this.matrixWorld;
  12098. if ( material === undefined ) return;
  12099. // test with bounding sphere in world space
  12100. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  12101. _sphere$6.copy( geometry.boundingSphere );
  12102. _sphere$6.applyMatrix4( matrixWorld );
  12103. // check distance from ray origin to bounding sphere
  12104. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  12105. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  12106. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  12107. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  12108. }
  12109. // convert ray to local space of mesh
  12110. _inverseMatrix$3.copy( matrixWorld ).invert();
  12111. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  12112. // test with bounding box in local space
  12113. if ( geometry.boundingBox !== null ) {
  12114. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  12115. }
  12116. // test for intersections with geometry
  12117. this._computeIntersections( raycaster, intersects, _ray$3 );
  12118. }
  12119. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  12120. let intersection;
  12121. const geometry = this.geometry;
  12122. const material = this.material;
  12123. const index = geometry.index;
  12124. const position = geometry.attributes.position;
  12125. const uv = geometry.attributes.uv;
  12126. const uv1 = geometry.attributes.uv1;
  12127. const normal = geometry.attributes.normal;
  12128. const groups = geometry.groups;
  12129. const drawRange = geometry.drawRange;
  12130. if ( index !== null ) {
  12131. // indexed buffer geometry
  12132. if ( Array.isArray( material ) ) {
  12133. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12134. const group = groups[ i ];
  12135. const groupMaterial = material[ group.materialIndex ];
  12136. const start = Math.max( group.start, drawRange.start );
  12137. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12138. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12139. const a = index.getX( j );
  12140. const b = index.getX( j + 1 );
  12141. const c = index.getX( j + 2 );
  12142. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12143. if ( intersection ) {
  12144. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  12145. intersection.face.materialIndex = group.materialIndex;
  12146. intersects.push( intersection );
  12147. }
  12148. }
  12149. }
  12150. } else {
  12151. const start = Math.max( 0, drawRange.start );
  12152. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  12153. for ( let i = start, il = end; i < il; i += 3 ) {
  12154. const a = index.getX( i );
  12155. const b = index.getX( i + 1 );
  12156. const c = index.getX( i + 2 );
  12157. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12158. if ( intersection ) {
  12159. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  12160. intersects.push( intersection );
  12161. }
  12162. }
  12163. }
  12164. } else if ( position !== undefined ) {
  12165. // non-indexed buffer geometry
  12166. if ( Array.isArray( material ) ) {
  12167. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  12168. const group = groups[ i ];
  12169. const groupMaterial = material[ group.materialIndex ];
  12170. const start = Math.max( group.start, drawRange.start );
  12171. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  12172. for ( let j = start, jl = end; j < jl; j += 3 ) {
  12173. const a = j;
  12174. const b = j + 1;
  12175. const c = j + 2;
  12176. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12177. if ( intersection ) {
  12178. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  12179. intersection.face.materialIndex = group.materialIndex;
  12180. intersects.push( intersection );
  12181. }
  12182. }
  12183. }
  12184. } else {
  12185. const start = Math.max( 0, drawRange.start );
  12186. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  12187. for ( let i = start, il = end; i < il; i += 3 ) {
  12188. const a = i;
  12189. const b = i + 1;
  12190. const c = i + 2;
  12191. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  12192. if ( intersection ) {
  12193. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  12194. intersects.push( intersection );
  12195. }
  12196. }
  12197. }
  12198. }
  12199. }
  12200. }
  12201. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  12202. let intersect;
  12203. if ( material.side === BackSide ) {
  12204. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  12205. } else {
  12206. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  12207. }
  12208. if ( intersect === null ) return null;
  12209. _intersectionPointWorld.copy( point );
  12210. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  12211. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  12212. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  12213. return {
  12214. distance: distance,
  12215. point: _intersectionPointWorld.clone(),
  12216. object: object
  12217. };
  12218. }
  12219. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  12220. object.getVertexPosition( a, _vA$1 );
  12221. object.getVertexPosition( b, _vB$1 );
  12222. object.getVertexPosition( c, _vC$1 );
  12223. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  12224. if ( intersection ) {
  12225. const barycoord = new Vector3();
  12226. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  12227. if ( uv ) {
  12228. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  12229. }
  12230. if ( uv1 ) {
  12231. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  12232. }
  12233. if ( normal ) {
  12234. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  12235. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  12236. intersection.normal.multiplyScalar( -1 );
  12237. }
  12238. }
  12239. const face = {
  12240. a: a,
  12241. b: b,
  12242. c: c,
  12243. normal: new Vector3(),
  12244. materialIndex: 0
  12245. };
  12246. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  12247. intersection.face = face;
  12248. intersection.barycoord = barycoord;
  12249. }
  12250. return intersection;
  12251. }
  12252. /**
  12253. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  12254. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  12255. * of the axes.
  12256. *
  12257. * ```js
  12258. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  12259. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  12260. * const cube = new THREE.Mesh( geometry, material );
  12261. * scene.add( cube );
  12262. * ```
  12263. *
  12264. * @augments BufferGeometry
  12265. */
  12266. class BoxGeometry extends BufferGeometry {
  12267. /**
  12268. * Constructs a new box geometry.
  12269. *
  12270. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  12271. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  12272. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  12273. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  12274. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  12275. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  12276. */
  12277. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  12278. super();
  12279. this.type = 'BoxGeometry';
  12280. /**
  12281. * Holds the constructor parameters that have been
  12282. * used to generate the geometry. Any modification
  12283. * after instantiation does not change the geometry.
  12284. *
  12285. * @type {Object}
  12286. */
  12287. this.parameters = {
  12288. width: width,
  12289. height: height,
  12290. depth: depth,
  12291. widthSegments: widthSegments,
  12292. heightSegments: heightSegments,
  12293. depthSegments: depthSegments
  12294. };
  12295. const scope = this;
  12296. // segments
  12297. widthSegments = Math.floor( widthSegments );
  12298. heightSegments = Math.floor( heightSegments );
  12299. depthSegments = Math.floor( depthSegments );
  12300. // buffers
  12301. const indices = [];
  12302. const vertices = [];
  12303. const normals = [];
  12304. const uvs = [];
  12305. // helper variables
  12306. let numberOfVertices = 0;
  12307. let groupStart = 0;
  12308. // build each side of the box geometry
  12309. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  12310. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  12311. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  12312. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  12313. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  12314. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  12315. // build geometry
  12316. this.setIndex( indices );
  12317. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12318. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  12319. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  12320. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  12321. const segmentWidth = width / gridX;
  12322. const segmentHeight = height / gridY;
  12323. const widthHalf = width / 2;
  12324. const heightHalf = height / 2;
  12325. const depthHalf = depth / 2;
  12326. const gridX1 = gridX + 1;
  12327. const gridY1 = gridY + 1;
  12328. let vertexCounter = 0;
  12329. let groupCount = 0;
  12330. const vector = new Vector3();
  12331. // generate vertices, normals and uvs
  12332. for ( let iy = 0; iy < gridY1; iy ++ ) {
  12333. const y = iy * segmentHeight - heightHalf;
  12334. for ( let ix = 0; ix < gridX1; ix ++ ) {
  12335. const x = ix * segmentWidth - widthHalf;
  12336. // set values to correct vector component
  12337. vector[ u ] = x * udir;
  12338. vector[ v ] = y * vdir;
  12339. vector[ w ] = depthHalf;
  12340. // now apply vector to vertex buffer
  12341. vertices.push( vector.x, vector.y, vector.z );
  12342. // set values to correct vector component
  12343. vector[ u ] = 0;
  12344. vector[ v ] = 0;
  12345. vector[ w ] = depth > 0 ? 1 : -1;
  12346. // now apply vector to normal buffer
  12347. normals.push( vector.x, vector.y, vector.z );
  12348. // uvs
  12349. uvs.push( ix / gridX );
  12350. uvs.push( 1 - ( iy / gridY ) );
  12351. // counters
  12352. vertexCounter += 1;
  12353. }
  12354. }
  12355. // indices
  12356. // 1. you need three indices to draw a single face
  12357. // 2. a single segment consists of two faces
  12358. // 3. so we need to generate six (2*3) indices per segment
  12359. for ( let iy = 0; iy < gridY; iy ++ ) {
  12360. for ( let ix = 0; ix < gridX; ix ++ ) {
  12361. const a = numberOfVertices + ix + gridX1 * iy;
  12362. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  12363. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  12364. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  12365. // faces
  12366. indices.push( a, b, d );
  12367. indices.push( b, c, d );
  12368. // increase counter
  12369. groupCount += 6;
  12370. }
  12371. }
  12372. // add a group to the geometry. this will ensure multi material support
  12373. scope.addGroup( groupStart, groupCount, materialIndex );
  12374. // calculate new start value for groups
  12375. groupStart += groupCount;
  12376. // update total number of vertices
  12377. numberOfVertices += vertexCounter;
  12378. }
  12379. }
  12380. copy( source ) {
  12381. super.copy( source );
  12382. this.parameters = Object.assign( {}, source.parameters );
  12383. return this;
  12384. }
  12385. /**
  12386. * Factory method for creating an instance of this class from the given
  12387. * JSON object.
  12388. *
  12389. * @param {Object} data - A JSON object representing the serialized geometry.
  12390. * @return {BoxGeometry} A new instance.
  12391. */
  12392. static fromJSON( data ) {
  12393. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  12394. }
  12395. }
  12396. /**
  12397. * Uniform Utilities
  12398. */
  12399. function cloneUniforms( src ) {
  12400. const dst = {};
  12401. for ( const u in src ) {
  12402. dst[ u ] = {};
  12403. for ( const p in src[ u ] ) {
  12404. const property = src[ u ][ p ];
  12405. if ( property && ( property.isColor ||
  12406. property.isMatrix3 || property.isMatrix4 ||
  12407. property.isVector2 || property.isVector3 || property.isVector4 ||
  12408. property.isTexture || property.isQuaternion ) ) {
  12409. if ( property.isRenderTargetTexture ) {
  12410. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  12411. dst[ u ][ p ] = null;
  12412. } else {
  12413. dst[ u ][ p ] = property.clone();
  12414. }
  12415. } else if ( Array.isArray( property ) ) {
  12416. dst[ u ][ p ] = property.slice();
  12417. } else {
  12418. dst[ u ][ p ] = property;
  12419. }
  12420. }
  12421. }
  12422. return dst;
  12423. }
  12424. function mergeUniforms( uniforms ) {
  12425. const merged = {};
  12426. for ( let u = 0; u < uniforms.length; u ++ ) {
  12427. const tmp = cloneUniforms( uniforms[ u ] );
  12428. for ( const p in tmp ) {
  12429. merged[ p ] = tmp[ p ];
  12430. }
  12431. }
  12432. return merged;
  12433. }
  12434. function cloneUniformsGroups( src ) {
  12435. const dst = [];
  12436. for ( let u = 0; u < src.length; u ++ ) {
  12437. dst.push( src[ u ].clone() );
  12438. }
  12439. return dst;
  12440. }
  12441. function getUnlitUniformColorSpace( renderer ) {
  12442. const currentRenderTarget = renderer.getRenderTarget();
  12443. if ( currentRenderTarget === null ) {
  12444. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  12445. return renderer.outputColorSpace;
  12446. }
  12447. // https://github.com/mrdoob/three.js/issues/27868
  12448. if ( currentRenderTarget.isXRRenderTarget === true ) {
  12449. return currentRenderTarget.texture.colorSpace;
  12450. }
  12451. return ColorManagement.workingColorSpace;
  12452. }
  12453. // Legacy
  12454. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  12455. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  12456. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  12457. class ShaderMaterial extends Material {
  12458. constructor( parameters ) {
  12459. super();
  12460. this.isShaderMaterial = true;
  12461. this.type = 'ShaderMaterial';
  12462. this.defines = {};
  12463. this.uniforms = {};
  12464. this.uniformsGroups = [];
  12465. this.vertexShader = default_vertex;
  12466. this.fragmentShader = default_fragment;
  12467. this.linewidth = 1;
  12468. this.wireframe = false;
  12469. this.wireframeLinewidth = 1;
  12470. this.fog = false; // set to use scene fog
  12471. this.lights = false; // set to use scene lights
  12472. this.clipping = false; // set to use user-defined clipping planes
  12473. this.forceSinglePass = true;
  12474. this.extensions = {
  12475. clipCullDistance: false, // set to use vertex shader clipping
  12476. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  12477. };
  12478. // When rendered geometry doesn't include these attributes but the material does,
  12479. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12480. this.defaultAttributeValues = {
  12481. 'color': [ 1, 1, 1 ],
  12482. 'uv': [ 0, 0 ],
  12483. 'uv1': [ 0, 0 ]
  12484. };
  12485. this.index0AttributeName = undefined;
  12486. this.uniformsNeedUpdate = false;
  12487. this.glslVersion = null;
  12488. if ( parameters !== undefined ) {
  12489. this.setValues( parameters );
  12490. }
  12491. }
  12492. copy( source ) {
  12493. super.copy( source );
  12494. this.fragmentShader = source.fragmentShader;
  12495. this.vertexShader = source.vertexShader;
  12496. this.uniforms = cloneUniforms( source.uniforms );
  12497. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  12498. this.defines = Object.assign( {}, source.defines );
  12499. this.wireframe = source.wireframe;
  12500. this.wireframeLinewidth = source.wireframeLinewidth;
  12501. this.fog = source.fog;
  12502. this.lights = source.lights;
  12503. this.clipping = source.clipping;
  12504. this.extensions = Object.assign( {}, source.extensions );
  12505. this.glslVersion = source.glslVersion;
  12506. return this;
  12507. }
  12508. toJSON( meta ) {
  12509. const data = super.toJSON( meta );
  12510. data.glslVersion = this.glslVersion;
  12511. data.uniforms = {};
  12512. for ( const name in this.uniforms ) {
  12513. const uniform = this.uniforms[ name ];
  12514. const value = uniform.value;
  12515. if ( value && value.isTexture ) {
  12516. data.uniforms[ name ] = {
  12517. type: 't',
  12518. value: value.toJSON( meta ).uuid
  12519. };
  12520. } else if ( value && value.isColor ) {
  12521. data.uniforms[ name ] = {
  12522. type: 'c',
  12523. value: value.getHex()
  12524. };
  12525. } else if ( value && value.isVector2 ) {
  12526. data.uniforms[ name ] = {
  12527. type: 'v2',
  12528. value: value.toArray()
  12529. };
  12530. } else if ( value && value.isVector3 ) {
  12531. data.uniforms[ name ] = {
  12532. type: 'v3',
  12533. value: value.toArray()
  12534. };
  12535. } else if ( value && value.isVector4 ) {
  12536. data.uniforms[ name ] = {
  12537. type: 'v4',
  12538. value: value.toArray()
  12539. };
  12540. } else if ( value && value.isMatrix3 ) {
  12541. data.uniforms[ name ] = {
  12542. type: 'm3',
  12543. value: value.toArray()
  12544. };
  12545. } else if ( value && value.isMatrix4 ) {
  12546. data.uniforms[ name ] = {
  12547. type: 'm4',
  12548. value: value.toArray()
  12549. };
  12550. } else {
  12551. data.uniforms[ name ] = {
  12552. value: value
  12553. };
  12554. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  12555. }
  12556. }
  12557. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  12558. data.vertexShader = this.vertexShader;
  12559. data.fragmentShader = this.fragmentShader;
  12560. data.lights = this.lights;
  12561. data.clipping = this.clipping;
  12562. const extensions = {};
  12563. for ( const key in this.extensions ) {
  12564. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  12565. }
  12566. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  12567. return data;
  12568. }
  12569. }
  12570. /**
  12571. * Abstract base class for cameras. This class should always be inherited
  12572. * when you build a new camera.
  12573. *
  12574. * @abstract
  12575. * @augments Object3D
  12576. */
  12577. class Camera extends Object3D {
  12578. /**
  12579. * Constructs a new camera.
  12580. */
  12581. constructor() {
  12582. super();
  12583. /**
  12584. * This flag can be used for type testing.
  12585. *
  12586. * @type {boolean}
  12587. * @readonly
  12588. * @default true
  12589. */
  12590. this.isCamera = true;
  12591. this.type = 'Camera';
  12592. /**
  12593. * The inverse of the camera's world matrix.
  12594. *
  12595. * @type {Matrix4}
  12596. */
  12597. this.matrixWorldInverse = new Matrix4();
  12598. /**
  12599. * The camera's projection matrix.
  12600. *
  12601. * @type {Matrix4}
  12602. */
  12603. this.projectionMatrix = new Matrix4();
  12604. /**
  12605. * The inverse of the camera's projection matrix.
  12606. *
  12607. * @type {Matrix4}
  12608. */
  12609. this.projectionMatrixInverse = new Matrix4();
  12610. /**
  12611. * The coordinate system in which the camera is used.
  12612. *
  12613. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  12614. */
  12615. this.coordinateSystem = WebGLCoordinateSystem;
  12616. }
  12617. copy( source, recursive ) {
  12618. super.copy( source, recursive );
  12619. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  12620. this.projectionMatrix.copy( source.projectionMatrix );
  12621. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  12622. this.coordinateSystem = source.coordinateSystem;
  12623. return this;
  12624. }
  12625. /**
  12626. * Returns a vector representing the ("look") direction of the 3D object in world space.
  12627. *
  12628. * This method is overwritten since cameras have a different forward vector compared to other
  12629. * 3D objects. A camera looks down its local, negative z-axis by default.
  12630. *
  12631. * @param {Vector3} target - The target vector the result is stored to.
  12632. * @return {Vector3} The 3D object's direction in world space.
  12633. */
  12634. getWorldDirection( target ) {
  12635. return super.getWorldDirection( target ).negate();
  12636. }
  12637. updateMatrixWorld( force ) {
  12638. super.updateMatrixWorld( force );
  12639. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12640. }
  12641. updateWorldMatrix( updateParents, updateChildren ) {
  12642. super.updateWorldMatrix( updateParents, updateChildren );
  12643. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  12644. }
  12645. clone() {
  12646. return new this.constructor().copy( this );
  12647. }
  12648. }
  12649. const _v3$1 = /*@__PURE__*/ new Vector3();
  12650. const _minTarget = /*@__PURE__*/ new Vector2();
  12651. const _maxTarget = /*@__PURE__*/ new Vector2();
  12652. /**
  12653. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  12654. *
  12655. * This projection mode is designed to mimic the way the human eye sees. It
  12656. * is the most common projection mode used for rendering a 3D scene.
  12657. *
  12658. * ```js
  12659. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  12660. * scene.add( camera );
  12661. * ```
  12662. *
  12663. * @augments Camera
  12664. */
  12665. class PerspectiveCamera extends Camera {
  12666. /**
  12667. * Constructs a new perspective camera.
  12668. *
  12669. * @param {number} [fov=50] - The vertical field of view.
  12670. * @param {number} [aspect=1] - The aspect ratio.
  12671. * @param {number} [near=0.1] - The camera's near plane.
  12672. * @param {number} [far=2000] - The camera's far plane.
  12673. */
  12674. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  12675. super();
  12676. /**
  12677. * This flag can be used for type testing.
  12678. *
  12679. * @type {boolean}
  12680. * @readonly
  12681. * @default true
  12682. */
  12683. this.isPerspectiveCamera = true;
  12684. this.type = 'PerspectiveCamera';
  12685. /**
  12686. * The vertical field of view, from bottom to top of view,
  12687. * in degrees.
  12688. *
  12689. * @type {number}
  12690. * @default 50
  12691. */
  12692. this.fov = fov;
  12693. /**
  12694. * The zoom factor of the camera.
  12695. *
  12696. * @type {number}
  12697. * @default 1
  12698. */
  12699. this.zoom = 1;
  12700. /**
  12701. * The camera's near plane. The valid range is greater than `0`
  12702. * and less than the current value of {@link PerspectiveCamera#far}.
  12703. *
  12704. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  12705. * valid value for a perspective camera's near plane.
  12706. *
  12707. * @type {number}
  12708. * @default 0.1
  12709. */
  12710. this.near = near;
  12711. /**
  12712. * The camera's far plane. Must be greater than the
  12713. * current value of {@link PerspectiveCamera#near}.
  12714. *
  12715. * @type {number}
  12716. * @default 2000
  12717. */
  12718. this.far = far;
  12719. /**
  12720. * Object distance used for stereoscopy and depth-of-field effects. This
  12721. * parameter does not influence the projection matrix unless a
  12722. * {@link StereoCamera} is being used.
  12723. *
  12724. * @type {number}
  12725. * @default 10
  12726. */
  12727. this.focus = 10;
  12728. /**
  12729. * The aspect ratio, usually the canvas width / canvas height.
  12730. *
  12731. * @type {number}
  12732. * @default 1
  12733. */
  12734. this.aspect = aspect;
  12735. /**
  12736. * Represents the frustum window specification. This property should not be edited
  12737. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  12738. *
  12739. * @type {?Object}
  12740. * @default null
  12741. */
  12742. this.view = null;
  12743. /**
  12744. * Film size used for the larger axis. Default is `35` (millimeters). This
  12745. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  12746. * is set to a nonzero value.
  12747. *
  12748. * @type {number}
  12749. * @default 35
  12750. */
  12751. this.filmGauge = 35;
  12752. /**
  12753. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  12754. *
  12755. * @type {number}
  12756. * @default 0
  12757. */
  12758. this.filmOffset = 0;
  12759. this.updateProjectionMatrix();
  12760. }
  12761. copy( source, recursive ) {
  12762. super.copy( source, recursive );
  12763. this.fov = source.fov;
  12764. this.zoom = source.zoom;
  12765. this.near = source.near;
  12766. this.far = source.far;
  12767. this.focus = source.focus;
  12768. this.aspect = source.aspect;
  12769. this.view = source.view === null ? null : Object.assign( {}, source.view );
  12770. this.filmGauge = source.filmGauge;
  12771. this.filmOffset = source.filmOffset;
  12772. return this;
  12773. }
  12774. /**
  12775. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  12776. *
  12777. * The default film gauge is 35, so that the focal length can be specified for
  12778. * a 35mm (full frame) camera.
  12779. *
  12780. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  12781. */
  12782. setFocalLength( focalLength ) {
  12783. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  12784. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  12785. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  12786. this.updateProjectionMatrix();
  12787. }
  12788. /**
  12789. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  12790. * {@link PerspectiveCamera#filmGauge}.
  12791. *
  12792. * @return {number} The computed focal length.
  12793. */
  12794. getFocalLength() {
  12795. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  12796. return 0.5 * this.getFilmHeight() / vExtentSlope;
  12797. }
  12798. /**
  12799. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  12800. *
  12801. * @return {number} The effective FOV.
  12802. */
  12803. getEffectiveFOV() {
  12804. return RAD2DEG * 2 * Math.atan(
  12805. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  12806. }
  12807. /**
  12808. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12809. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12810. *
  12811. * @return {number} The film width.
  12812. */
  12813. getFilmWidth() {
  12814. // film not completely covered in portrait format (aspect < 1)
  12815. return this.filmGauge * Math.min( this.aspect, 1 );
  12816. }
  12817. /**
  12818. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  12819. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  12820. *
  12821. * @return {number} The film width.
  12822. */
  12823. getFilmHeight() {
  12824. // film not completely covered in landscape format (aspect > 1)
  12825. return this.filmGauge / Math.max( this.aspect, 1 );
  12826. }
  12827. /**
  12828. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  12829. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  12830. *
  12831. * @param {number} distance - The viewing distance.
  12832. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  12833. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  12834. */
  12835. getViewBounds( distance, minTarget, maxTarget ) {
  12836. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12837. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12838. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  12839. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  12840. }
  12841. /**
  12842. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  12843. *
  12844. * @param {number} distance - The viewing distance.
  12845. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  12846. * @returns {Vector2} The view size.
  12847. */
  12848. getViewSize( distance, target ) {
  12849. this.getViewBounds( distance, _minTarget, _maxTarget );
  12850. return target.subVectors( _maxTarget, _minTarget );
  12851. }
  12852. /**
  12853. * Sets an offset in a larger frustum. This is useful for multi-window or
  12854. * multi-monitor/multi-machine setups.
  12855. *
  12856. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  12857. * the monitors are in grid like this
  12858. *```
  12859. * +---+---+---+
  12860. * | A | B | C |
  12861. * +---+---+---+
  12862. * | D | E | F |
  12863. * +---+---+---+
  12864. *```
  12865. * then for each monitor you would call it like this:
  12866. *```js
  12867. * const w = 1920;
  12868. * const h = 1080;
  12869. * const fullWidth = w * 3;
  12870. * const fullHeight = h * 2;
  12871. *
  12872. * // --A--
  12873. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  12874. * // --B--
  12875. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  12876. * // --C--
  12877. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  12878. * // --D--
  12879. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  12880. * // --E--
  12881. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  12882. * // --F--
  12883. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  12884. * ```
  12885. *
  12886. * Note there is no reason monitors have to be the same size or in a grid.
  12887. *
  12888. * @param {number} fullWidth - The full width of multiview setup.
  12889. * @param {number} fullHeight - The full height of multiview setup.
  12890. * @param {number} x - The horizontal offset of the subcamera.
  12891. * @param {number} y - The vertical offset of the subcamera.
  12892. * @param {number} width - The width of subcamera.
  12893. * @param {number} height - The height of subcamera.
  12894. */
  12895. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  12896. this.aspect = fullWidth / fullHeight;
  12897. if ( this.view === null ) {
  12898. this.view = {
  12899. enabled: true,
  12900. fullWidth: 1,
  12901. fullHeight: 1,
  12902. offsetX: 0,
  12903. offsetY: 0,
  12904. width: 1,
  12905. height: 1
  12906. };
  12907. }
  12908. this.view.enabled = true;
  12909. this.view.fullWidth = fullWidth;
  12910. this.view.fullHeight = fullHeight;
  12911. this.view.offsetX = x;
  12912. this.view.offsetY = y;
  12913. this.view.width = width;
  12914. this.view.height = height;
  12915. this.updateProjectionMatrix();
  12916. }
  12917. /**
  12918. * Removes the view offset from the projection matrix.
  12919. */
  12920. clearViewOffset() {
  12921. if ( this.view !== null ) {
  12922. this.view.enabled = false;
  12923. }
  12924. this.updateProjectionMatrix();
  12925. }
  12926. /**
  12927. * Updates the camera's projection matrix. Must be called after any change of
  12928. * camera properties.
  12929. */
  12930. updateProjectionMatrix() {
  12931. const near = this.near;
  12932. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  12933. let height = 2 * top;
  12934. let width = this.aspect * height;
  12935. let left = -0.5 * width;
  12936. const view = this.view;
  12937. if ( this.view !== null && this.view.enabled ) {
  12938. const fullWidth = view.fullWidth,
  12939. fullHeight = view.fullHeight;
  12940. left += view.offsetX * width / fullWidth;
  12941. top -= view.offsetY * height / fullHeight;
  12942. width *= view.width / fullWidth;
  12943. height *= view.height / fullHeight;
  12944. }
  12945. const skew = this.filmOffset;
  12946. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  12947. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  12948. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  12949. }
  12950. toJSON( meta ) {
  12951. const data = super.toJSON( meta );
  12952. data.object.fov = this.fov;
  12953. data.object.zoom = this.zoom;
  12954. data.object.near = this.near;
  12955. data.object.far = this.far;
  12956. data.object.focus = this.focus;
  12957. data.object.aspect = this.aspect;
  12958. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  12959. data.object.filmGauge = this.filmGauge;
  12960. data.object.filmOffset = this.filmOffset;
  12961. return data;
  12962. }
  12963. }
  12964. const fov = -90; // negative fov is not an error
  12965. const aspect = 1;
  12966. /**
  12967. * A special type of camera that is positioned in 3D space to render its surroundings into a
  12968. * cube render target. The render target can then be used as an environment map for rendering
  12969. * realtime reflections in your scene.
  12970. *
  12971. * ```js
  12972. * // Create cube render target
  12973. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  12974. *
  12975. * // Create cube camera
  12976. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  12977. * scene.add( cubeCamera );
  12978. *
  12979. * // Create car
  12980. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  12981. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  12982. * scene.add( car );
  12983. *
  12984. * // Update the render target cube
  12985. * car.visible = false;
  12986. * cubeCamera.position.copy( car.position );
  12987. * cubeCamera.update( renderer, scene );
  12988. *
  12989. * // Render the scene
  12990. * car.visible = true;
  12991. * renderer.render( scene, camera );
  12992. * ```
  12993. *
  12994. * @augments Object3D
  12995. */
  12996. class CubeCamera extends Object3D {
  12997. /**
  12998. * Constructs a new cube camera.
  12999. *
  13000. * @param {number} near - The camera's near plane.
  13001. * @param {number} far - The camera's far plane.
  13002. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  13003. */
  13004. constructor( near, far, renderTarget ) {
  13005. super();
  13006. this.type = 'CubeCamera';
  13007. /**
  13008. * A reference to the cube render target.
  13009. *
  13010. * @type {WebGLCubeRenderTarget}
  13011. */
  13012. this.renderTarget = renderTarget;
  13013. /**
  13014. * The current active coordinate system.
  13015. *
  13016. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  13017. * @default null
  13018. */
  13019. this.coordinateSystem = null;
  13020. /**
  13021. * The current active mipmap level
  13022. *
  13023. * @type {number}
  13024. * @default 0
  13025. */
  13026. this.activeMipmapLevel = 0;
  13027. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  13028. cameraPX.layers = this.layers;
  13029. this.add( cameraPX );
  13030. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  13031. cameraNX.layers = this.layers;
  13032. this.add( cameraNX );
  13033. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  13034. cameraPY.layers = this.layers;
  13035. this.add( cameraPY );
  13036. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  13037. cameraNY.layers = this.layers;
  13038. this.add( cameraNY );
  13039. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  13040. cameraPZ.layers = this.layers;
  13041. this.add( cameraPZ );
  13042. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  13043. cameraNZ.layers = this.layers;
  13044. this.add( cameraNZ );
  13045. }
  13046. /**
  13047. * Must be called when the coordinate system of the cube camera is changed.
  13048. */
  13049. updateCoordinateSystem() {
  13050. const coordinateSystem = this.coordinateSystem;
  13051. const cameras = this.children.concat();
  13052. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  13053. for ( const camera of cameras ) this.remove( camera );
  13054. if ( coordinateSystem === WebGLCoordinateSystem ) {
  13055. cameraPX.up.set( 0, 1, 0 );
  13056. cameraPX.lookAt( 1, 0, 0 );
  13057. cameraNX.up.set( 0, 1, 0 );
  13058. cameraNX.lookAt( -1, 0, 0 );
  13059. cameraPY.up.set( 0, 0, -1 );
  13060. cameraPY.lookAt( 0, 1, 0 );
  13061. cameraNY.up.set( 0, 0, 1 );
  13062. cameraNY.lookAt( 0, -1, 0 );
  13063. cameraPZ.up.set( 0, 1, 0 );
  13064. cameraPZ.lookAt( 0, 0, 1 );
  13065. cameraNZ.up.set( 0, 1, 0 );
  13066. cameraNZ.lookAt( 0, 0, -1 );
  13067. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  13068. cameraPX.up.set( 0, -1, 0 );
  13069. cameraPX.lookAt( -1, 0, 0 );
  13070. cameraNX.up.set( 0, -1, 0 );
  13071. cameraNX.lookAt( 1, 0, 0 );
  13072. cameraPY.up.set( 0, 0, 1 );
  13073. cameraPY.lookAt( 0, 1, 0 );
  13074. cameraNY.up.set( 0, 0, -1 );
  13075. cameraNY.lookAt( 0, -1, 0 );
  13076. cameraPZ.up.set( 0, -1, 0 );
  13077. cameraPZ.lookAt( 0, 0, 1 );
  13078. cameraNZ.up.set( 0, -1, 0 );
  13079. cameraNZ.lookAt( 0, 0, -1 );
  13080. } else {
  13081. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  13082. }
  13083. for ( const camera of cameras ) {
  13084. this.add( camera );
  13085. camera.updateMatrixWorld();
  13086. }
  13087. }
  13088. /**
  13089. * Calling this method will render the given scene with the given renderer
  13090. * into the cube render target of the camera.
  13091. *
  13092. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  13093. * @param {Scene} scene - The scene to render.
  13094. */
  13095. update( renderer, scene ) {
  13096. if ( this.parent === null ) this.updateMatrixWorld();
  13097. const { renderTarget, activeMipmapLevel } = this;
  13098. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  13099. this.coordinateSystem = renderer.coordinateSystem;
  13100. this.updateCoordinateSystem();
  13101. }
  13102. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  13103. const currentRenderTarget = renderer.getRenderTarget();
  13104. const currentActiveCubeFace = renderer.getActiveCubeFace();
  13105. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  13106. const currentXrEnabled = renderer.xr.enabled;
  13107. renderer.xr.enabled = false;
  13108. const generateMipmaps = renderTarget.texture.generateMipmaps;
  13109. renderTarget.texture.generateMipmaps = false;
  13110. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  13111. renderer.render( scene, cameraPX );
  13112. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  13113. renderer.render( scene, cameraNX );
  13114. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  13115. renderer.render( scene, cameraPY );
  13116. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  13117. renderer.render( scene, cameraNY );
  13118. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  13119. renderer.render( scene, cameraPZ );
  13120. // mipmaps are generated during the last call of render()
  13121. // at this point, all sides of the cube render target are defined
  13122. renderTarget.texture.generateMipmaps = generateMipmaps;
  13123. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  13124. renderer.render( scene, cameraNZ );
  13125. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  13126. renderer.xr.enabled = currentXrEnabled;
  13127. renderTarget.texture.needsPMREMUpdate = true;
  13128. }
  13129. }
  13130. class CubeTexture extends Texture {
  13131. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  13132. images = images !== undefined ? images : [];
  13133. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  13134. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  13135. this.isCubeTexture = true;
  13136. this.flipY = false;
  13137. }
  13138. get images() {
  13139. return this.image;
  13140. }
  13141. set images( value ) {
  13142. this.image = value;
  13143. }
  13144. }
  13145. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  13146. constructor( size = 1, options = {} ) {
  13147. super( size, size, options );
  13148. this.isWebGLCubeRenderTarget = true;
  13149. const image = { width: size, height: size, depth: 1 };
  13150. const images = [ image, image, image, image, image, image ];
  13151. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  13152. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  13153. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  13154. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  13155. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  13156. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  13157. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  13158. this.texture.isRenderTargetTexture = true;
  13159. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  13160. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  13161. }
  13162. fromEquirectangularTexture( renderer, texture ) {
  13163. this.texture.type = texture.type;
  13164. this.texture.colorSpace = texture.colorSpace;
  13165. this.texture.generateMipmaps = texture.generateMipmaps;
  13166. this.texture.minFilter = texture.minFilter;
  13167. this.texture.magFilter = texture.magFilter;
  13168. const shader = {
  13169. uniforms: {
  13170. tEquirect: { value: null },
  13171. },
  13172. vertexShader: /* glsl */`
  13173. varying vec3 vWorldDirection;
  13174. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  13175. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  13176. }
  13177. void main() {
  13178. vWorldDirection = transformDirection( position, modelMatrix );
  13179. #include <begin_vertex>
  13180. #include <project_vertex>
  13181. }
  13182. `,
  13183. fragmentShader: /* glsl */`
  13184. uniform sampler2D tEquirect;
  13185. varying vec3 vWorldDirection;
  13186. #include <common>
  13187. void main() {
  13188. vec3 direction = normalize( vWorldDirection );
  13189. vec2 sampleUV = equirectUv( direction );
  13190. gl_FragColor = texture2D( tEquirect, sampleUV );
  13191. }
  13192. `
  13193. };
  13194. const geometry = new BoxGeometry( 5, 5, 5 );
  13195. const material = new ShaderMaterial( {
  13196. name: 'CubemapFromEquirect',
  13197. uniforms: cloneUniforms( shader.uniforms ),
  13198. vertexShader: shader.vertexShader,
  13199. fragmentShader: shader.fragmentShader,
  13200. side: BackSide,
  13201. blending: NoBlending
  13202. } );
  13203. material.uniforms.tEquirect.value = texture;
  13204. const mesh = new Mesh( geometry, material );
  13205. const currentMinFilter = texture.minFilter;
  13206. // Avoid blurred poles
  13207. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  13208. const camera = new CubeCamera( 1, 10, this );
  13209. camera.update( renderer, mesh );
  13210. texture.minFilter = currentMinFilter;
  13211. mesh.geometry.dispose();
  13212. mesh.material.dispose();
  13213. return this;
  13214. }
  13215. clear( renderer, color, depth, stencil ) {
  13216. const currentRenderTarget = renderer.getRenderTarget();
  13217. for ( let i = 0; i < 6; i ++ ) {
  13218. renderer.setRenderTarget( this, i );
  13219. renderer.clear( color, depth, stencil );
  13220. }
  13221. renderer.setRenderTarget( currentRenderTarget );
  13222. }
  13223. }
  13224. /**
  13225. * This is almost identical to an {@link Object3D}. Its purpose is to
  13226. * make working with groups of objects syntactically clearer.
  13227. *
  13228. * ```js
  13229. * // Create a group and add the two cubes.
  13230. * // These cubes can now be rotated / scaled etc as a group.
  13231. * const group = new THREE.Group();
  13232. *
  13233. * group.add( meshA );
  13234. * group.add( meshB );
  13235. *
  13236. * scene.add( group );
  13237. * ```
  13238. *
  13239. * @augments Object3D
  13240. */
  13241. class Group extends Object3D {
  13242. constructor() {
  13243. super();
  13244. /**
  13245. * This flag can be used for type testing.
  13246. *
  13247. * @type {boolean}
  13248. * @readonly
  13249. * @default true
  13250. */
  13251. this.isGroup = true;
  13252. this.type = 'Group';
  13253. }
  13254. }
  13255. const _moveEvent = { type: 'move' };
  13256. class WebXRController {
  13257. constructor() {
  13258. this._targetRay = null;
  13259. this._grip = null;
  13260. this._hand = null;
  13261. }
  13262. getHandSpace() {
  13263. if ( this._hand === null ) {
  13264. this._hand = new Group();
  13265. this._hand.matrixAutoUpdate = false;
  13266. this._hand.visible = false;
  13267. this._hand.joints = {};
  13268. this._hand.inputState = { pinching: false };
  13269. }
  13270. return this._hand;
  13271. }
  13272. getTargetRaySpace() {
  13273. if ( this._targetRay === null ) {
  13274. this._targetRay = new Group();
  13275. this._targetRay.matrixAutoUpdate = false;
  13276. this._targetRay.visible = false;
  13277. this._targetRay.hasLinearVelocity = false;
  13278. this._targetRay.linearVelocity = new Vector3();
  13279. this._targetRay.hasAngularVelocity = false;
  13280. this._targetRay.angularVelocity = new Vector3();
  13281. }
  13282. return this._targetRay;
  13283. }
  13284. getGripSpace() {
  13285. if ( this._grip === null ) {
  13286. this._grip = new Group();
  13287. this._grip.matrixAutoUpdate = false;
  13288. this._grip.visible = false;
  13289. this._grip.hasLinearVelocity = false;
  13290. this._grip.linearVelocity = new Vector3();
  13291. this._grip.hasAngularVelocity = false;
  13292. this._grip.angularVelocity = new Vector3();
  13293. }
  13294. return this._grip;
  13295. }
  13296. dispatchEvent( event ) {
  13297. if ( this._targetRay !== null ) {
  13298. this._targetRay.dispatchEvent( event );
  13299. }
  13300. if ( this._grip !== null ) {
  13301. this._grip.dispatchEvent( event );
  13302. }
  13303. if ( this._hand !== null ) {
  13304. this._hand.dispatchEvent( event );
  13305. }
  13306. return this;
  13307. }
  13308. connect( inputSource ) {
  13309. if ( inputSource && inputSource.hand ) {
  13310. const hand = this._hand;
  13311. if ( hand ) {
  13312. for ( const inputjoint of inputSource.hand.values() ) {
  13313. // Initialize hand with joints when connected
  13314. this._getHandJoint( hand, inputjoint );
  13315. }
  13316. }
  13317. }
  13318. this.dispatchEvent( { type: 'connected', data: inputSource } );
  13319. return this;
  13320. }
  13321. disconnect( inputSource ) {
  13322. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13323. if ( this._targetRay !== null ) {
  13324. this._targetRay.visible = false;
  13325. }
  13326. if ( this._grip !== null ) {
  13327. this._grip.visible = false;
  13328. }
  13329. if ( this._hand !== null ) {
  13330. this._hand.visible = false;
  13331. }
  13332. return this;
  13333. }
  13334. update( inputSource, frame, referenceSpace ) {
  13335. let inputPose = null;
  13336. let gripPose = null;
  13337. let handPose = null;
  13338. const targetRay = this._targetRay;
  13339. const grip = this._grip;
  13340. const hand = this._hand;
  13341. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13342. if ( hand && inputSource.hand ) {
  13343. handPose = true;
  13344. for ( const inputjoint of inputSource.hand.values() ) {
  13345. // Update the joints groups with the XRJoint poses
  13346. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  13347. // The transform of this joint will be updated with the joint pose on each frame
  13348. const joint = this._getHandJoint( hand, inputjoint );
  13349. if ( jointPose !== null ) {
  13350. joint.matrix.fromArray( jointPose.transform.matrix );
  13351. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13352. joint.matrixWorldNeedsUpdate = true;
  13353. joint.jointRadius = jointPose.radius;
  13354. }
  13355. joint.visible = jointPose !== null;
  13356. }
  13357. // Custom events
  13358. // Check pinchz
  13359. const indexTip = hand.joints[ 'index-finger-tip' ];
  13360. const thumbTip = hand.joints[ 'thumb-tip' ];
  13361. const distance = indexTip.position.distanceTo( thumbTip.position );
  13362. const distanceToPinch = 0.02;
  13363. const threshold = 0.005;
  13364. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13365. hand.inputState.pinching = false;
  13366. this.dispatchEvent( {
  13367. type: 'pinchend',
  13368. handedness: inputSource.handedness,
  13369. target: this
  13370. } );
  13371. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13372. hand.inputState.pinching = true;
  13373. this.dispatchEvent( {
  13374. type: 'pinchstart',
  13375. handedness: inputSource.handedness,
  13376. target: this
  13377. } );
  13378. }
  13379. } else {
  13380. if ( grip !== null && inputSource.gripSpace ) {
  13381. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13382. if ( gripPose !== null ) {
  13383. grip.matrix.fromArray( gripPose.transform.matrix );
  13384. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13385. grip.matrixWorldNeedsUpdate = true;
  13386. if ( gripPose.linearVelocity ) {
  13387. grip.hasLinearVelocity = true;
  13388. grip.linearVelocity.copy( gripPose.linearVelocity );
  13389. } else {
  13390. grip.hasLinearVelocity = false;
  13391. }
  13392. if ( gripPose.angularVelocity ) {
  13393. grip.hasAngularVelocity = true;
  13394. grip.angularVelocity.copy( gripPose.angularVelocity );
  13395. } else {
  13396. grip.hasAngularVelocity = false;
  13397. }
  13398. }
  13399. }
  13400. }
  13401. if ( targetRay !== null ) {
  13402. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13403. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  13404. if ( inputPose === null && gripPose !== null ) {
  13405. inputPose = gripPose;
  13406. }
  13407. if ( inputPose !== null ) {
  13408. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13409. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13410. targetRay.matrixWorldNeedsUpdate = true;
  13411. if ( inputPose.linearVelocity ) {
  13412. targetRay.hasLinearVelocity = true;
  13413. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  13414. } else {
  13415. targetRay.hasLinearVelocity = false;
  13416. }
  13417. if ( inputPose.angularVelocity ) {
  13418. targetRay.hasAngularVelocity = true;
  13419. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  13420. } else {
  13421. targetRay.hasAngularVelocity = false;
  13422. }
  13423. this.dispatchEvent( _moveEvent );
  13424. }
  13425. }
  13426. }
  13427. if ( targetRay !== null ) {
  13428. targetRay.visible = ( inputPose !== null );
  13429. }
  13430. if ( grip !== null ) {
  13431. grip.visible = ( gripPose !== null );
  13432. }
  13433. if ( hand !== null ) {
  13434. hand.visible = ( handPose !== null );
  13435. }
  13436. return this;
  13437. }
  13438. // private method
  13439. _getHandJoint( hand, inputjoint ) {
  13440. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  13441. const joint = new Group();
  13442. joint.matrixAutoUpdate = false;
  13443. joint.visible = false;
  13444. hand.joints[ inputjoint.jointName ] = joint;
  13445. hand.add( joint );
  13446. }
  13447. return hand.joints[ inputjoint.jointName ];
  13448. }
  13449. }
  13450. /**
  13451. * This class can be used to define an exponential squared fog,
  13452. * which gives a clear view near the camera and a faster than exponentially
  13453. * densening fog farther from the camera.
  13454. *
  13455. * ```js
  13456. * const scene = new THREE.Scene();
  13457. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  13458. * ```
  13459. */
  13460. class FogExp2 {
  13461. /**
  13462. * Constructs a new fog.
  13463. *
  13464. * @param {number|Color} color - The fog's color.
  13465. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  13466. */
  13467. constructor( color, density = 0.00025 ) {
  13468. /**
  13469. * This flag can be used for type testing.
  13470. *
  13471. * @type {boolean}
  13472. * @readonly
  13473. * @default true
  13474. */
  13475. this.isFogExp2 = true;
  13476. /**
  13477. * The name of the fog.
  13478. *
  13479. * @type {string}
  13480. */
  13481. this.name = '';
  13482. /**
  13483. * The fog's color.
  13484. *
  13485. * @type {Color}
  13486. */
  13487. this.color = new Color( color );
  13488. /**
  13489. * Defines how fast the fog will grow dense.
  13490. *
  13491. * @type {number}
  13492. * @default 0.00025
  13493. */
  13494. this.density = density;
  13495. }
  13496. /**
  13497. * Returns a new fog with copied values from this instance.
  13498. *
  13499. * @return {FogExp2} A clone of this instance.
  13500. */
  13501. clone() {
  13502. return new FogExp2( this.color, this.density );
  13503. }
  13504. /**
  13505. * Serializes the fog into JSON.
  13506. *
  13507. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13508. * @return {Object} A JSON object representing the serialized fog
  13509. */
  13510. toJSON( /* meta */ ) {
  13511. return {
  13512. type: 'FogExp2',
  13513. name: this.name,
  13514. color: this.color.getHex(),
  13515. density: this.density
  13516. };
  13517. }
  13518. }
  13519. /**
  13520. * This class can be used to define a linear fog that grows linearly denser
  13521. * with the distance.
  13522. *
  13523. * ```js
  13524. * const scene = new THREE.Scene();
  13525. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  13526. * ```
  13527. */
  13528. class Fog {
  13529. /**
  13530. * Constructs a new fog.
  13531. *
  13532. * @param {number|Color} color - The fog's color.
  13533. * @param {number} [near=1] - The minimum distance to start applying fog.
  13534. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  13535. */
  13536. constructor( color, near = 1, far = 1000 ) {
  13537. /**
  13538. * This flag can be used for type testing.
  13539. *
  13540. * @type {boolean}
  13541. * @readonly
  13542. * @default true
  13543. */
  13544. this.isFog = true;
  13545. /**
  13546. * The name of the fog.
  13547. *
  13548. * @type {string}
  13549. */
  13550. this.name = '';
  13551. /**
  13552. * The fog's color.
  13553. *
  13554. * @type {Color}
  13555. */
  13556. this.color = new Color( color );
  13557. /**
  13558. * The minimum distance to start applying fog. Objects that are less than
  13559. * `near` units from the active camera won't be affected by fog.
  13560. *
  13561. * @type {number}
  13562. * @default 1
  13563. */
  13564. this.near = near;
  13565. /**
  13566. * The maximum distance at which fog stops being calculated and applied.
  13567. * Objects that are more than `far` units away from the active camera won't
  13568. * be affected by fog.
  13569. *
  13570. * @type {number}
  13571. * @default 1000
  13572. */
  13573. this.far = far;
  13574. }
  13575. /**
  13576. * Returns a new fog with copied values from this instance.
  13577. *
  13578. * @return {Fog} A clone of this instance.
  13579. */
  13580. clone() {
  13581. return new Fog( this.color, this.near, this.far );
  13582. }
  13583. /**
  13584. * Serializes the fog into JSON.
  13585. *
  13586. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13587. * @return {Object} A JSON object representing the serialized fog
  13588. */
  13589. toJSON( /* meta */ ) {
  13590. return {
  13591. type: 'Fog',
  13592. name: this.name,
  13593. color: this.color.getHex(),
  13594. near: this.near,
  13595. far: this.far
  13596. };
  13597. }
  13598. }
  13599. /**
  13600. * Scenes allow you to set up what is to be rendered and where by three.js.
  13601. * This is where you place 3D objects like meshes, lines or lights.
  13602. *
  13603. * @augments Object3D
  13604. */
  13605. class Scene extends Object3D {
  13606. /**
  13607. * Constructs a new scene.
  13608. */
  13609. constructor() {
  13610. super();
  13611. /**
  13612. * This flag can be used for type testing.
  13613. *
  13614. * @type {boolean}
  13615. * @readonly
  13616. * @default true
  13617. */
  13618. this.isScene = true;
  13619. this.type = 'Scene';
  13620. /**
  13621. * Defines the background of the scene. Valid inputs are:
  13622. *
  13623. * - A color for defining a uniform colored background.
  13624. * - A texture for defining a (flat) textured background.
  13625. * - Cube textures or equirectangular textures for defining a skybox.
  13626. *
  13627. * @type {?(Color|Texture)}
  13628. * @default null
  13629. */
  13630. this.background = null;
  13631. /**
  13632. * Sets the environment map for all physical materials in the scene. However,
  13633. * it's not possible to overwrite an existing texture assigned to the `envMap`
  13634. * material property.
  13635. *
  13636. * @type {?Texture}
  13637. * @default null
  13638. */
  13639. this.environment = null;
  13640. /**
  13641. * A fog instance defining the type of fog that affects everything
  13642. * rendered in the scene.
  13643. *
  13644. * @type {?(Fog|FogExp2)}
  13645. * @default null
  13646. */
  13647. this.fog = null;
  13648. /**
  13649. * Sets the blurriness of the background. Only influences environment maps
  13650. * assigned to {@link Scene#background}. Valid input is a float between `0`
  13651. * and `1`.
  13652. *
  13653. * @type {number}
  13654. * @default 0
  13655. */
  13656. this.backgroundBlurriness = 0;
  13657. /**
  13658. * Attenuates the color of the background. Only applies to background textures.
  13659. *
  13660. * @type {number}
  13661. * @default 1
  13662. */
  13663. this.backgroundIntensity = 1;
  13664. /**
  13665. * The rotation of the background in radians. Only influences environment maps
  13666. * assigned to {@link Scene#background}.
  13667. *
  13668. * @type {Euler}
  13669. * @default (0,0,0)
  13670. */
  13671. this.backgroundRotation = new Euler();
  13672. /**
  13673. * Attenuates the color of the environment. Only influences environment maps
  13674. * assigned to {@link Scene#environment}.
  13675. *
  13676. * @type {number}
  13677. * @default 1
  13678. */
  13679. this.environmentIntensity = 1;
  13680. /**
  13681. * The rotation of the environment map in radians. Only influences physical materials
  13682. * in the scene when {@link Scene#environment} is used.
  13683. *
  13684. * @type {Euler}
  13685. * @default (0,0,0)
  13686. */
  13687. this.environmentRotation = new Euler();
  13688. /**
  13689. * Forces everything in the scene to be rendered with the defined material.
  13690. *
  13691. * @type {?Material}
  13692. * @default null
  13693. */
  13694. this.overrideMaterial = null;
  13695. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  13696. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  13697. }
  13698. }
  13699. copy( source, recursive ) {
  13700. super.copy( source, recursive );
  13701. if ( source.background !== null ) this.background = source.background.clone();
  13702. if ( source.environment !== null ) this.environment = source.environment.clone();
  13703. if ( source.fog !== null ) this.fog = source.fog.clone();
  13704. this.backgroundBlurriness = source.backgroundBlurriness;
  13705. this.backgroundIntensity = source.backgroundIntensity;
  13706. this.backgroundRotation.copy( source.backgroundRotation );
  13707. this.environmentIntensity = source.environmentIntensity;
  13708. this.environmentRotation.copy( source.environmentRotation );
  13709. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  13710. this.matrixAutoUpdate = source.matrixAutoUpdate;
  13711. return this;
  13712. }
  13713. toJSON( meta ) {
  13714. const data = super.toJSON( meta );
  13715. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  13716. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  13717. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  13718. data.object.backgroundRotation = this.backgroundRotation.toArray();
  13719. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  13720. data.object.environmentRotation = this.environmentRotation.toArray();
  13721. return data;
  13722. }
  13723. }
  13724. class InterleavedBuffer {
  13725. constructor( array, stride ) {
  13726. this.isInterleavedBuffer = true;
  13727. this.array = array;
  13728. this.stride = stride;
  13729. this.count = array !== undefined ? array.length / stride : 0;
  13730. this.usage = StaticDrawUsage;
  13731. this.updateRanges = [];
  13732. this.version = 0;
  13733. this.uuid = generateUUID();
  13734. }
  13735. onUploadCallback() {}
  13736. set needsUpdate( value ) {
  13737. if ( value === true ) this.version ++;
  13738. }
  13739. setUsage( value ) {
  13740. this.usage = value;
  13741. return this;
  13742. }
  13743. addUpdateRange( start, count ) {
  13744. this.updateRanges.push( { start, count } );
  13745. }
  13746. clearUpdateRanges() {
  13747. this.updateRanges.length = 0;
  13748. }
  13749. copy( source ) {
  13750. this.array = new source.array.constructor( source.array );
  13751. this.count = source.count;
  13752. this.stride = source.stride;
  13753. this.usage = source.usage;
  13754. return this;
  13755. }
  13756. copyAt( index1, attribute, index2 ) {
  13757. index1 *= this.stride;
  13758. index2 *= attribute.stride;
  13759. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  13760. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13761. }
  13762. return this;
  13763. }
  13764. set( value, offset = 0 ) {
  13765. this.array.set( value, offset );
  13766. return this;
  13767. }
  13768. clone( data ) {
  13769. if ( data.arrayBuffers === undefined ) {
  13770. data.arrayBuffers = {};
  13771. }
  13772. if ( this.array.buffer._uuid === undefined ) {
  13773. this.array.buffer._uuid = generateUUID();
  13774. }
  13775. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13776. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  13777. }
  13778. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  13779. const ib = new this.constructor( array, this.stride );
  13780. ib.setUsage( this.usage );
  13781. return ib;
  13782. }
  13783. onUpload( callback ) {
  13784. this.onUploadCallback = callback;
  13785. return this;
  13786. }
  13787. toJSON( data ) {
  13788. if ( data.arrayBuffers === undefined ) {
  13789. data.arrayBuffers = {};
  13790. }
  13791. // generate UUID for array buffer if necessary
  13792. if ( this.array.buffer._uuid === undefined ) {
  13793. this.array.buffer._uuid = generateUUID();
  13794. }
  13795. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  13796. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  13797. }
  13798. //
  13799. return {
  13800. uuid: this.uuid,
  13801. buffer: this.array.buffer._uuid,
  13802. type: this.array.constructor.name,
  13803. stride: this.stride
  13804. };
  13805. }
  13806. }
  13807. const _vector$7 = /*@__PURE__*/ new Vector3();
  13808. class InterleavedBufferAttribute {
  13809. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  13810. this.isInterleavedBufferAttribute = true;
  13811. this.name = '';
  13812. this.data = interleavedBuffer;
  13813. this.itemSize = itemSize;
  13814. this.offset = offset;
  13815. this.normalized = normalized;
  13816. }
  13817. get count() {
  13818. return this.data.count;
  13819. }
  13820. get array() {
  13821. return this.data.array;
  13822. }
  13823. set needsUpdate( value ) {
  13824. this.data.needsUpdate = value;
  13825. }
  13826. applyMatrix4( m ) {
  13827. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  13828. _vector$7.fromBufferAttribute( this, i );
  13829. _vector$7.applyMatrix4( m );
  13830. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13831. }
  13832. return this;
  13833. }
  13834. applyNormalMatrix( m ) {
  13835. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13836. _vector$7.fromBufferAttribute( this, i );
  13837. _vector$7.applyNormalMatrix( m );
  13838. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13839. }
  13840. return this;
  13841. }
  13842. transformDirection( m ) {
  13843. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13844. _vector$7.fromBufferAttribute( this, i );
  13845. _vector$7.transformDirection( m );
  13846. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  13847. }
  13848. return this;
  13849. }
  13850. getComponent( index, component ) {
  13851. let value = this.array[ index * this.data.stride + this.offset + component ];
  13852. if ( this.normalized ) value = denormalize( value, this.array );
  13853. return value;
  13854. }
  13855. setComponent( index, component, value ) {
  13856. if ( this.normalized ) value = normalize( value, this.array );
  13857. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  13858. return this;
  13859. }
  13860. setX( index, x ) {
  13861. if ( this.normalized ) x = normalize( x, this.array );
  13862. this.data.array[ index * this.data.stride + this.offset ] = x;
  13863. return this;
  13864. }
  13865. setY( index, y ) {
  13866. if ( this.normalized ) y = normalize( y, this.array );
  13867. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  13868. return this;
  13869. }
  13870. setZ( index, z ) {
  13871. if ( this.normalized ) z = normalize( z, this.array );
  13872. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  13873. return this;
  13874. }
  13875. setW( index, w ) {
  13876. if ( this.normalized ) w = normalize( w, this.array );
  13877. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  13878. return this;
  13879. }
  13880. getX( index ) {
  13881. let x = this.data.array[ index * this.data.stride + this.offset ];
  13882. if ( this.normalized ) x = denormalize( x, this.array );
  13883. return x;
  13884. }
  13885. getY( index ) {
  13886. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  13887. if ( this.normalized ) y = denormalize( y, this.array );
  13888. return y;
  13889. }
  13890. getZ( index ) {
  13891. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  13892. if ( this.normalized ) z = denormalize( z, this.array );
  13893. return z;
  13894. }
  13895. getW( index ) {
  13896. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  13897. if ( this.normalized ) w = denormalize( w, this.array );
  13898. return w;
  13899. }
  13900. setXY( index, x, y ) {
  13901. index = index * this.data.stride + this.offset;
  13902. if ( this.normalized ) {
  13903. x = normalize( x, this.array );
  13904. y = normalize( y, this.array );
  13905. }
  13906. this.data.array[ index + 0 ] = x;
  13907. this.data.array[ index + 1 ] = y;
  13908. return this;
  13909. }
  13910. setXYZ( index, x, y, z ) {
  13911. index = index * this.data.stride + this.offset;
  13912. if ( this.normalized ) {
  13913. x = normalize( x, this.array );
  13914. y = normalize( y, this.array );
  13915. z = normalize( z, this.array );
  13916. }
  13917. this.data.array[ index + 0 ] = x;
  13918. this.data.array[ index + 1 ] = y;
  13919. this.data.array[ index + 2 ] = z;
  13920. return this;
  13921. }
  13922. setXYZW( index, x, y, z, w ) {
  13923. index = index * this.data.stride + this.offset;
  13924. if ( this.normalized ) {
  13925. x = normalize( x, this.array );
  13926. y = normalize( y, this.array );
  13927. z = normalize( z, this.array );
  13928. w = normalize( w, this.array );
  13929. }
  13930. this.data.array[ index + 0 ] = x;
  13931. this.data.array[ index + 1 ] = y;
  13932. this.data.array[ index + 2 ] = z;
  13933. this.data.array[ index + 3 ] = w;
  13934. return this;
  13935. }
  13936. clone( data ) {
  13937. if ( data === undefined ) {
  13938. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  13939. const array = [];
  13940. for ( let i = 0; i < this.count; i ++ ) {
  13941. const index = i * this.data.stride + this.offset;
  13942. for ( let j = 0; j < this.itemSize; j ++ ) {
  13943. array.push( this.data.array[ index + j ] );
  13944. }
  13945. }
  13946. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  13947. } else {
  13948. if ( data.interleavedBuffers === undefined ) {
  13949. data.interleavedBuffers = {};
  13950. }
  13951. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13952. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  13953. }
  13954. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  13955. }
  13956. }
  13957. toJSON( data ) {
  13958. if ( data === undefined ) {
  13959. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  13960. const array = [];
  13961. for ( let i = 0; i < this.count; i ++ ) {
  13962. const index = i * this.data.stride + this.offset;
  13963. for ( let j = 0; j < this.itemSize; j ++ ) {
  13964. array.push( this.data.array[ index + j ] );
  13965. }
  13966. }
  13967. // de-interleave data and save it as an ordinary buffer attribute for now
  13968. return {
  13969. itemSize: this.itemSize,
  13970. type: this.array.constructor.name,
  13971. array: array,
  13972. normalized: this.normalized
  13973. };
  13974. } else {
  13975. // save as true interleaved attribute
  13976. if ( data.interleavedBuffers === undefined ) {
  13977. data.interleavedBuffers = {};
  13978. }
  13979. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  13980. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  13981. }
  13982. return {
  13983. isInterleavedBufferAttribute: true,
  13984. itemSize: this.itemSize,
  13985. data: this.data.uuid,
  13986. offset: this.offset,
  13987. normalized: this.normalized
  13988. };
  13989. }
  13990. }
  13991. }
  13992. class SpriteMaterial extends Material {
  13993. constructor( parameters ) {
  13994. super();
  13995. this.isSpriteMaterial = true;
  13996. this.type = 'SpriteMaterial';
  13997. this.color = new Color( 0xffffff );
  13998. this.map = null;
  13999. this.alphaMap = null;
  14000. this.rotation = 0;
  14001. this.sizeAttenuation = true;
  14002. this.transparent = true;
  14003. this.fog = true;
  14004. this.setValues( parameters );
  14005. }
  14006. copy( source ) {
  14007. super.copy( source );
  14008. this.color.copy( source.color );
  14009. this.map = source.map;
  14010. this.alphaMap = source.alphaMap;
  14011. this.rotation = source.rotation;
  14012. this.sizeAttenuation = source.sizeAttenuation;
  14013. this.fog = source.fog;
  14014. return this;
  14015. }
  14016. }
  14017. let _geometry;
  14018. const _intersectPoint = /*@__PURE__*/ new Vector3();
  14019. const _worldScale = /*@__PURE__*/ new Vector3();
  14020. const _mvPosition = /*@__PURE__*/ new Vector3();
  14021. const _alignedPosition = /*@__PURE__*/ new Vector2();
  14022. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  14023. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  14024. const _vA = /*@__PURE__*/ new Vector3();
  14025. const _vB = /*@__PURE__*/ new Vector3();
  14026. const _vC = /*@__PURE__*/ new Vector3();
  14027. const _uvA = /*@__PURE__*/ new Vector2();
  14028. const _uvB = /*@__PURE__*/ new Vector2();
  14029. const _uvC = /*@__PURE__*/ new Vector2();
  14030. /**
  14031. * A sprite is a plane that always faces towards the camera, generally with a
  14032. * partially transparent texture applied.
  14033. *
  14034. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  14035. * have no effect.
  14036. *
  14037. * ```js
  14038. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  14039. * const material = new THREE.SpriteMaterial( { map: map } );
  14040. *
  14041. * const sprite = new THREE.Sprite( material );
  14042. * scene.add( sprite );
  14043. * ```
  14044. *
  14045. * @augments Object3D
  14046. */
  14047. class Sprite extends Object3D {
  14048. /**
  14049. * Constructs a new sprite.
  14050. *
  14051. * @param {SpriteMaterial} [material] - The sprite material.
  14052. */
  14053. constructor( material = new SpriteMaterial() ) {
  14054. super();
  14055. /**
  14056. * This flag can be used for type testing.
  14057. *
  14058. * @type {boolean}
  14059. * @readonly
  14060. * @default true
  14061. */
  14062. this.isSprite = true;
  14063. this.type = 'Sprite';
  14064. if ( _geometry === undefined ) {
  14065. _geometry = new BufferGeometry();
  14066. const float32Array = new Float32Array( [
  14067. -0.5, -0.5, 0, 0, 0,
  14068. 0.5, -0.5, 0, 1, 0,
  14069. 0.5, 0.5, 0, 1, 1,
  14070. -0.5, 0.5, 0, 0, 1
  14071. ] );
  14072. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  14073. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  14074. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  14075. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  14076. }
  14077. /**
  14078. * The sprite geometry.
  14079. *
  14080. * @type {BufferGeometry}
  14081. */
  14082. this.geometry = _geometry;
  14083. /**
  14084. * The sprite material.
  14085. *
  14086. * @type {SpriteMaterial}
  14087. */
  14088. this.material = material;
  14089. /**
  14090. * The sprite's anchor point, and the point around which the sprite rotates.
  14091. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  14092. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  14093. *
  14094. * @type {Vector2}
  14095. * @default (0.5,0.5)
  14096. */
  14097. this.center = new Vector2( 0.5, 0.5 );
  14098. }
  14099. /**
  14100. * Computes intersection points between a casted ray and this sprite.
  14101. *
  14102. * @param {Raycaster} raycaster - The raycaster.
  14103. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  14104. */
  14105. raycast( raycaster, intersects ) {
  14106. if ( raycaster.camera === null ) {
  14107. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  14108. }
  14109. _worldScale.setFromMatrixScale( this.matrixWorld );
  14110. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  14111. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  14112. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  14113. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  14114. _worldScale.multiplyScalar( - _mvPosition.z );
  14115. }
  14116. const rotation = this.material.rotation;
  14117. let sin, cos;
  14118. if ( rotation !== 0 ) {
  14119. cos = Math.cos( rotation );
  14120. sin = Math.sin( rotation );
  14121. }
  14122. const center = this.center;
  14123. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14124. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14125. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14126. _uvA.set( 0, 0 );
  14127. _uvB.set( 1, 0 );
  14128. _uvC.set( 1, 1 );
  14129. // check first triangle
  14130. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  14131. if ( intersect === null ) {
  14132. // check second triangle
  14133. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  14134. _uvB.set( 0, 1 );
  14135. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  14136. if ( intersect === null ) {
  14137. return;
  14138. }
  14139. }
  14140. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  14141. if ( distance < raycaster.near || distance > raycaster.far ) return;
  14142. intersects.push( {
  14143. distance: distance,
  14144. point: _intersectPoint.clone(),
  14145. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  14146. face: null,
  14147. object: this
  14148. } );
  14149. }
  14150. copy( source, recursive ) {
  14151. super.copy( source, recursive );
  14152. if ( source.center !== undefined ) this.center.copy( source.center );
  14153. this.material = source.material;
  14154. return this;
  14155. }
  14156. }
  14157. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  14158. // compute position in camera space
  14159. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  14160. // to check if rotation is not zero
  14161. if ( sin !== undefined ) {
  14162. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  14163. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  14164. } else {
  14165. _rotatedPosition.copy( _alignedPosition );
  14166. }
  14167. vertexPosition.copy( mvPosition );
  14168. vertexPosition.x += _rotatedPosition.x;
  14169. vertexPosition.y += _rotatedPosition.y;
  14170. // transform to world space
  14171. vertexPosition.applyMatrix4( _viewWorldMatrix );
  14172. }
  14173. const _v1$2 = /*@__PURE__*/ new Vector3();
  14174. const _v2$1 = /*@__PURE__*/ new Vector3();
  14175. /**
  14176. * A component for providing a basic Level of Detail (LOD) mechanism.
  14177. *
  14178. * Every LOD level is associated with an object, and rendering can be switched
  14179. * between them at the distances specified. Typically you would create, say,
  14180. * three meshes, one for far away (low detail), one for mid range (medium
  14181. * detail) and one for close up (high detail).
  14182. *
  14183. * ```js
  14184. * const lod = new THREE.LOD();
  14185. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  14186. *
  14187. * //Create spheres with 3 levels of detail and create new LOD levels for them
  14188. * for( let i = 0; i < 3; i++ ) {
  14189. *
  14190. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  14191. * const mesh = new THREE.Mesh( geometry, material );
  14192. * lod.addLevel( mesh, i * 75 );
  14193. *
  14194. * }
  14195. *
  14196. * scene.add( lod );
  14197. * ```
  14198. *
  14199. * @augments Object3D
  14200. */
  14201. class LOD extends Object3D {
  14202. /**
  14203. * Constructs a new LOD.
  14204. */
  14205. constructor() {
  14206. super();
  14207. /**
  14208. * This flag can be used for type testing.
  14209. *
  14210. * @type {boolean}
  14211. * @readonly
  14212. * @default true
  14213. */
  14214. this.isLOD = true;
  14215. /**
  14216. * The current LOD index.
  14217. *
  14218. * @private
  14219. * @type {number}
  14220. * @default 0
  14221. */
  14222. this._currentLevel = 0;
  14223. this.type = 'LOD';
  14224. Object.defineProperties( this, {
  14225. /**
  14226. * This array holds the LOD levels.
  14227. *
  14228. * @name LOD#levels
  14229. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  14230. */
  14231. levels: {
  14232. enumerable: true,
  14233. value: []
  14234. }
  14235. } );
  14236. /**
  14237. * Whether the LOD object is updated automatically by the renderer per frame
  14238. * or not. If set to `false`, you have to call {@link LOD#update} in the
  14239. * render loop by yourself.
  14240. *
  14241. * @type {boolean}
  14242. * @default true
  14243. */
  14244. this.autoUpdate = true;
  14245. }
  14246. copy( source ) {
  14247. super.copy( source, false );
  14248. const levels = source.levels;
  14249. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14250. const level = levels[ i ];
  14251. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  14252. }
  14253. this.autoUpdate = source.autoUpdate;
  14254. return this;
  14255. }
  14256. /**
  14257. * Adds a mesh that will display at a certain distance and greater. Typically
  14258. * the further away the distance, the lower the detail on the mesh.
  14259. *
  14260. * @param {Object3D} object - The 3D object to display at this level.
  14261. * @param {number} [distance=0] - The distance at which to display this level of detail.
  14262. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  14263. * @return {LOD} A reference to this instance.
  14264. */
  14265. addLevel( object, distance = 0, hysteresis = 0 ) {
  14266. distance = Math.abs( distance );
  14267. const levels = this.levels;
  14268. let l;
  14269. for ( l = 0; l < levels.length; l ++ ) {
  14270. if ( distance < levels[ l ].distance ) {
  14271. break;
  14272. }
  14273. }
  14274. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  14275. this.add( object );
  14276. return this;
  14277. }
  14278. /**
  14279. * Removes an existing level, based on the distance from the camera.
  14280. * Returns `true` when the level has been removed. Otherwise `false`.
  14281. *
  14282. * @param {number} distance - Distance of the level to remove.
  14283. * @return {boolean} Whether the level has been removed or not.
  14284. */
  14285. removeLevel( distance ) {
  14286. const levels = this.levels;
  14287. for ( let i = 0; i < levels.length; i ++ ) {
  14288. if ( levels[ i ].distance === distance ) {
  14289. const removedElements = levels.splice( i, 1 );
  14290. this.remove( removedElements[ 0 ].object );
  14291. return true;
  14292. }
  14293. }
  14294. return false;
  14295. }
  14296. /**
  14297. * Returns the currently active LOD level index.
  14298. *
  14299. * @return {number} The current active LOD level index.
  14300. */
  14301. getCurrentLevel() {
  14302. return this._currentLevel;
  14303. }
  14304. /**
  14305. * Returns a reference to the first 3D object that is greater than
  14306. * the given distance.
  14307. *
  14308. * @param {number} distance - The LOD distance.
  14309. * @return {Object3D|null} The found 3D object. `null` if no 3D object has been found.
  14310. */
  14311. getObjectForDistance( distance ) {
  14312. const levels = this.levels;
  14313. if ( levels.length > 0 ) {
  14314. let i, l;
  14315. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14316. let levelDistance = levels[ i ].distance;
  14317. if ( levels[ i ].object.visible ) {
  14318. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14319. }
  14320. if ( distance < levelDistance ) {
  14321. break;
  14322. }
  14323. }
  14324. return levels[ i - 1 ].object;
  14325. }
  14326. return null;
  14327. }
  14328. /**
  14329. * Computes intersection points between a casted ray and this LOD.
  14330. *
  14331. * @param {Raycaster} raycaster - The raycaster.
  14332. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  14333. */
  14334. raycast( raycaster, intersects ) {
  14335. const levels = this.levels;
  14336. if ( levels.length > 0 ) {
  14337. _v1$2.setFromMatrixPosition( this.matrixWorld );
  14338. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  14339. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  14340. }
  14341. }
  14342. /**
  14343. * Updates the LOD by computing which LOD level should be visible according
  14344. * to the current distance of the given camera.
  14345. *
  14346. * @param {Camera} camera - The camera the scene is renderd with.
  14347. */
  14348. update( camera ) {
  14349. const levels = this.levels;
  14350. if ( levels.length > 1 ) {
  14351. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  14352. _v2$1.setFromMatrixPosition( this.matrixWorld );
  14353. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  14354. levels[ 0 ].object.visible = true;
  14355. let i, l;
  14356. for ( i = 1, l = levels.length; i < l; i ++ ) {
  14357. let levelDistance = levels[ i ].distance;
  14358. if ( levels[ i ].object.visible ) {
  14359. levelDistance -= levelDistance * levels[ i ].hysteresis;
  14360. }
  14361. if ( distance >= levelDistance ) {
  14362. levels[ i - 1 ].object.visible = false;
  14363. levels[ i ].object.visible = true;
  14364. } else {
  14365. break;
  14366. }
  14367. }
  14368. this._currentLevel = i - 1;
  14369. for ( ; i < l; i ++ ) {
  14370. levels[ i ].object.visible = false;
  14371. }
  14372. }
  14373. }
  14374. toJSON( meta ) {
  14375. const data = super.toJSON( meta );
  14376. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  14377. data.object.levels = [];
  14378. const levels = this.levels;
  14379. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  14380. const level = levels[ i ];
  14381. data.object.levels.push( {
  14382. object: level.object.uuid,
  14383. distance: level.distance,
  14384. hysteresis: level.hysteresis
  14385. } );
  14386. }
  14387. return data;
  14388. }
  14389. }
  14390. const _basePosition = /*@__PURE__*/ new Vector3();
  14391. const _skinIndex = /*@__PURE__*/ new Vector4();
  14392. const _skinWeight = /*@__PURE__*/ new Vector4();
  14393. const _vector3 = /*@__PURE__*/ new Vector3();
  14394. const _matrix4 = /*@__PURE__*/ new Matrix4();
  14395. const _vertex = /*@__PURE__*/ new Vector3();
  14396. const _sphere$5 = /*@__PURE__*/ new Sphere();
  14397. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  14398. const _ray$2 = /*@__PURE__*/ new Ray();
  14399. /**
  14400. * A mesh that has a {@link Skeleton} that can then be used to animate the
  14401. * vertices of the geometry with skinning/skeleton animation.
  14402. *
  14403. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  14404. * as buffer attributes in its geometry. These attribute define which bones affect a single
  14405. * vertex to a certain extend.
  14406. *
  14407. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  14408. * or {@link FBXLoader } import respective models.
  14409. *
  14410. * @augments Mesh
  14411. */
  14412. class SkinnedMesh extends Mesh {
  14413. /**
  14414. * Constructs a new skinned mesh.
  14415. *
  14416. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14417. * @param {Material|Array<Material>} [material] - The mesh material.
  14418. */
  14419. constructor( geometry, material ) {
  14420. super( geometry, material );
  14421. /**
  14422. * This flag can be used for type testing.
  14423. *
  14424. * @type {boolean}
  14425. * @readonly
  14426. * @default true
  14427. */
  14428. this.isSkinnedMesh = true;
  14429. this.type = 'SkinnedMesh';
  14430. /**
  14431. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  14432. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  14433. * across multiple skinned meshes.
  14434. *
  14435. * @type {(AttachedBindMode|DetachedBindMode)}
  14436. * @default AttachedBindMode
  14437. */
  14438. this.bindMode = AttachedBindMode;
  14439. /**
  14440. * The base matrix that is used for the bound bone transforms.
  14441. *
  14442. * @type {Matrix4}
  14443. */
  14444. this.bindMatrix = new Matrix4();
  14445. /**
  14446. * The base matrix that is used for resetting the bound bone transforms.
  14447. *
  14448. * @type {Matrix4}
  14449. */
  14450. this.bindMatrixInverse = new Matrix4();
  14451. /**
  14452. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  14453. *
  14454. * @type {?Box3}
  14455. * @default null
  14456. */
  14457. this.boundingBox = null;
  14458. /**
  14459. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  14460. *
  14461. * @type {?Sphere}
  14462. * @default null
  14463. */
  14464. this.boundingSphere = null;
  14465. }
  14466. /**
  14467. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  14468. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  14469. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  14470. * the current animation state.
  14471. */
  14472. computeBoundingBox() {
  14473. const geometry = this.geometry;
  14474. if ( this.boundingBox === null ) {
  14475. this.boundingBox = new Box3();
  14476. }
  14477. this.boundingBox.makeEmpty();
  14478. const positionAttribute = geometry.getAttribute( 'position' );
  14479. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14480. this.getVertexPosition( i, _vertex );
  14481. this.boundingBox.expandByPoint( _vertex );
  14482. }
  14483. }
  14484. /**
  14485. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  14486. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  14487. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  14488. * per frame in order to reflect the current animation state.
  14489. */
  14490. computeBoundingSphere() {
  14491. const geometry = this.geometry;
  14492. if ( this.boundingSphere === null ) {
  14493. this.boundingSphere = new Sphere();
  14494. }
  14495. this.boundingSphere.makeEmpty();
  14496. const positionAttribute = geometry.getAttribute( 'position' );
  14497. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14498. this.getVertexPosition( i, _vertex );
  14499. this.boundingSphere.expandByPoint( _vertex );
  14500. }
  14501. }
  14502. copy( source, recursive ) {
  14503. super.copy( source, recursive );
  14504. this.bindMode = source.bindMode;
  14505. this.bindMatrix.copy( source.bindMatrix );
  14506. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  14507. this.skeleton = source.skeleton;
  14508. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  14509. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  14510. return this;
  14511. }
  14512. raycast( raycaster, intersects ) {
  14513. const material = this.material;
  14514. const matrixWorld = this.matrixWorld;
  14515. if ( material === undefined ) return;
  14516. // test with bounding sphere in world space
  14517. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  14518. _sphere$5.copy( this.boundingSphere );
  14519. _sphere$5.applyMatrix4( matrixWorld );
  14520. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  14521. // convert ray to local space of skinned mesh
  14522. _inverseMatrix$2.copy( matrixWorld ).invert();
  14523. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  14524. // test with bounding box in local space
  14525. if ( this.boundingBox !== null ) {
  14526. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  14527. }
  14528. // test for intersections with geometry
  14529. this._computeIntersections( raycaster, intersects, _ray$2 );
  14530. }
  14531. getVertexPosition( index, target ) {
  14532. super.getVertexPosition( index, target );
  14533. this.applyBoneTransform( index, target );
  14534. return target;
  14535. }
  14536. /**
  14537. * Binds the given skeleton to the skinned mesh.
  14538. *
  14539. * @param {Skeleton} skeleton - The skeleton to bind.
  14540. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  14541. * the skinned mesh's world matrix will be used instead.
  14542. */
  14543. bind( skeleton, bindMatrix ) {
  14544. this.skeleton = skeleton;
  14545. if ( bindMatrix === undefined ) {
  14546. this.updateMatrixWorld( true );
  14547. this.skeleton.calculateInverses();
  14548. bindMatrix = this.matrixWorld;
  14549. }
  14550. this.bindMatrix.copy( bindMatrix );
  14551. this.bindMatrixInverse.copy( bindMatrix ).invert();
  14552. }
  14553. /**
  14554. * This method sets the skinned mesh in the rest pose).
  14555. */
  14556. pose() {
  14557. this.skeleton.pose();
  14558. }
  14559. /**
  14560. * Normalizes the skin weights which are defined as a buffer attribute
  14561. * in the skinned mesh's geometry.
  14562. */
  14563. normalizeSkinWeights() {
  14564. const vector = new Vector4();
  14565. const skinWeight = this.geometry.attributes.skinWeight;
  14566. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  14567. vector.fromBufferAttribute( skinWeight, i );
  14568. const scale = 1.0 / vector.manhattanLength();
  14569. if ( scale !== Infinity ) {
  14570. vector.multiplyScalar( scale );
  14571. } else {
  14572. vector.set( 1, 0, 0, 0 ); // do something reasonable
  14573. }
  14574. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  14575. }
  14576. }
  14577. updateMatrixWorld( force ) {
  14578. super.updateMatrixWorld( force );
  14579. if ( this.bindMode === AttachedBindMode ) {
  14580. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  14581. } else if ( this.bindMode === DetachedBindMode ) {
  14582. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  14583. } else {
  14584. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  14585. }
  14586. }
  14587. /**
  14588. * Applies the bone transform associated with the given index to the given
  14589. * vertex position. Returns the updated vector.
  14590. *
  14591. * @param {number} index - The vertex index.
  14592. * @param {Vector3} target - The target object that is used to store the method's result.
  14593. * the skinned mesh's world matrix will be used instead.
  14594. * @return {Vector3} The updated vertex position.
  14595. */
  14596. applyBoneTransform( index, target ) {
  14597. const skeleton = this.skeleton;
  14598. const geometry = this.geometry;
  14599. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  14600. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  14601. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  14602. target.set( 0, 0, 0 );
  14603. for ( let i = 0; i < 4; i ++ ) {
  14604. const weight = _skinWeight.getComponent( i );
  14605. if ( weight !== 0 ) {
  14606. const boneIndex = _skinIndex.getComponent( i );
  14607. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  14608. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  14609. }
  14610. }
  14611. return target.applyMatrix4( this.bindMatrixInverse );
  14612. }
  14613. }
  14614. /**
  14615. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  14616. * the {@link SkinnedMesh}.
  14617. *
  14618. * ```js
  14619. * const root = new THREE.Bone();
  14620. * const child = new THREE.Bone();
  14621. *
  14622. * root.add( child );
  14623. * child.position.y = 5;
  14624. * ```
  14625. *
  14626. * @augments Object3D
  14627. */
  14628. class Bone extends Object3D {
  14629. /**
  14630. * Constructs a new bone.
  14631. */
  14632. constructor() {
  14633. super();
  14634. /**
  14635. * This flag can be used for type testing.
  14636. *
  14637. * @type {boolean}
  14638. * @readonly
  14639. * @default true
  14640. */
  14641. this.isBone = true;
  14642. this.type = 'Bone';
  14643. }
  14644. }
  14645. class DataTexture extends Texture {
  14646. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  14647. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  14648. this.isDataTexture = true;
  14649. this.image = { data: data, width: width, height: height };
  14650. this.generateMipmaps = false;
  14651. this.flipY = false;
  14652. this.unpackAlignment = 1;
  14653. }
  14654. }
  14655. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  14656. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  14657. /**
  14658. * Class for representing the armatures in `three.js`. The skeleton
  14659. * is defined by a hierarchy of bones.
  14660. *
  14661. * ```js
  14662. * const bones = [];
  14663. *
  14664. * const shoulder = new THREE.Bone();
  14665. * const elbow = new THREE.Bone();
  14666. * const hand = new THREE.Bone();
  14667. *
  14668. * shoulder.add( elbow );
  14669. * elbow.add( hand );
  14670. *
  14671. * bones.push( shoulder , elbow, hand);
  14672. *
  14673. * shoulder.position.y = -5;
  14674. * elbow.position.y = 0;
  14675. * hand.position.y = 5;
  14676. *
  14677. * const armSkeleton = new THREE.Skeleton( bones );
  14678. * ```
  14679. */
  14680. class Skeleton {
  14681. /**
  14682. * Constructs a new skeleton.
  14683. *
  14684. * @param {Array<Bone>} [bones] - An array of bones.
  14685. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  14686. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  14687. */
  14688. constructor( bones = [], boneInverses = [] ) {
  14689. this.uuid = generateUUID();
  14690. /**
  14691. * An array of bones defining the skeleton.
  14692. *
  14693. * @type {Array<Bone>}
  14694. */
  14695. this.bones = bones.slice( 0 );
  14696. /**
  14697. * An array of bone inverse matrices.
  14698. *
  14699. * @type {Array<Matrix4>}
  14700. */
  14701. this.boneInverses = boneInverses;
  14702. /**
  14703. * An array buffer holding the bone data.
  14704. * Input data for {@link Skeleton#boneTexture}.
  14705. *
  14706. * @type {?Float32Array}
  14707. * @default null
  14708. */
  14709. this.boneMatrices = null;
  14710. /**
  14711. * A texture holding the bone data for use
  14712. * in the vertex shader.
  14713. *
  14714. * @type {?DataTexture}
  14715. * @default null
  14716. */
  14717. this.boneTexture = null;
  14718. this.init();
  14719. }
  14720. /**
  14721. * Initializes the skeleton. This method gets automatically called by the constructor
  14722. * but depending on how the skeleton is created it might be necessary to call this method
  14723. * manually.
  14724. */
  14725. init() {
  14726. const bones = this.bones;
  14727. const boneInverses = this.boneInverses;
  14728. this.boneMatrices = new Float32Array( bones.length * 16 );
  14729. // calculate inverse bone matrices if necessary
  14730. if ( boneInverses.length === 0 ) {
  14731. this.calculateInverses();
  14732. } else {
  14733. // handle special case
  14734. if ( bones.length !== boneInverses.length ) {
  14735. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  14736. this.boneInverses = [];
  14737. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14738. this.boneInverses.push( new Matrix4() );
  14739. }
  14740. }
  14741. }
  14742. }
  14743. /**
  14744. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  14745. * and fills it with new matrices.
  14746. */
  14747. calculateInverses() {
  14748. this.boneInverses.length = 0;
  14749. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14750. const inverse = new Matrix4();
  14751. if ( this.bones[ i ] ) {
  14752. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  14753. }
  14754. this.boneInverses.push( inverse );
  14755. }
  14756. }
  14757. /**
  14758. * Resets the skeleton to the base pose.
  14759. */
  14760. pose() {
  14761. // recover the bind-time world matrices
  14762. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14763. const bone = this.bones[ i ];
  14764. if ( bone ) {
  14765. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  14766. }
  14767. }
  14768. // compute the local matrices, positions, rotations and scales
  14769. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14770. const bone = this.bones[ i ];
  14771. if ( bone ) {
  14772. if ( bone.parent && bone.parent.isBone ) {
  14773. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  14774. bone.matrix.multiply( bone.matrixWorld );
  14775. } else {
  14776. bone.matrix.copy( bone.matrixWorld );
  14777. }
  14778. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  14779. }
  14780. }
  14781. }
  14782. /**
  14783. * Resets the skeleton to the base pose.
  14784. */
  14785. update() {
  14786. const bones = this.bones;
  14787. const boneInverses = this.boneInverses;
  14788. const boneMatrices = this.boneMatrices;
  14789. const boneTexture = this.boneTexture;
  14790. // flatten bone matrices to array
  14791. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  14792. // compute the offset between the current and the original transform
  14793. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  14794. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  14795. _offsetMatrix.toArray( boneMatrices, i * 16 );
  14796. }
  14797. if ( boneTexture !== null ) {
  14798. boneTexture.needsUpdate = true;
  14799. }
  14800. }
  14801. /**
  14802. * Returns a new skeleton with copied values from this instance.
  14803. *
  14804. * @return {Skeleton} A clone of this instance.
  14805. */
  14806. clone() {
  14807. return new Skeleton( this.bones, this.boneInverses );
  14808. }
  14809. /**
  14810. * Computes a data texture for passing bone data to the vertex shader.
  14811. *
  14812. * @return {Skeleton} A reference of this instance.
  14813. */
  14814. computeBoneTexture() {
  14815. // layout (1 matrix = 4 pixels)
  14816. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14817. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14818. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14819. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14820. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14821. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  14822. size = Math.ceil( size / 4 ) * 4;
  14823. size = Math.max( size, 4 );
  14824. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  14825. boneMatrices.set( this.boneMatrices ); // copy current values
  14826. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  14827. boneTexture.needsUpdate = true;
  14828. this.boneMatrices = boneMatrices;
  14829. this.boneTexture = boneTexture;
  14830. return this;
  14831. }
  14832. /**
  14833. * Searches through the skeleton's bone array and returns the first with a
  14834. * matching name.
  14835. *
  14836. * @param {string} name - The name of the bone.
  14837. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  14838. */
  14839. getBoneByName( name ) {
  14840. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  14841. const bone = this.bones[ i ];
  14842. if ( bone.name === name ) {
  14843. return bone;
  14844. }
  14845. }
  14846. return undefined;
  14847. }
  14848. /**
  14849. * Frees the GPU-related resources allocated by this instance. Call this
  14850. * method whenever this instance is no longer used in your app.
  14851. */
  14852. dispose( ) {
  14853. if ( this.boneTexture !== null ) {
  14854. this.boneTexture.dispose();
  14855. this.boneTexture = null;
  14856. }
  14857. }
  14858. /**
  14859. * Setups the skeleton by the given JSON and bones.
  14860. *
  14861. * @param {Object} json - The skeleton as serialized JSON.
  14862. * @param {Array<Bone>} bones - An array of bones.
  14863. * @return {Skeleton} A reference of this instance.
  14864. */
  14865. fromJSON( json, bones ) {
  14866. this.uuid = json.uuid;
  14867. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  14868. const uuid = json.bones[ i ];
  14869. let bone = bones[ uuid ];
  14870. if ( bone === undefined ) {
  14871. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  14872. bone = new Bone();
  14873. }
  14874. this.bones.push( bone );
  14875. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  14876. }
  14877. this.init();
  14878. return this;
  14879. }
  14880. /**
  14881. * Serializes the skeleton into JSON.
  14882. *
  14883. * @return {Object} A JSON object representing the serialized skeleton.
  14884. * @see {@link ObjectLoader#parse}
  14885. */
  14886. toJSON() {
  14887. const data = {
  14888. metadata: {
  14889. version: 4.6,
  14890. type: 'Skeleton',
  14891. generator: 'Skeleton.toJSON'
  14892. },
  14893. bones: [],
  14894. boneInverses: []
  14895. };
  14896. data.uuid = this.uuid;
  14897. const bones = this.bones;
  14898. const boneInverses = this.boneInverses;
  14899. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  14900. const bone = bones[ i ];
  14901. data.bones.push( bone.uuid );
  14902. const boneInverse = boneInverses[ i ];
  14903. data.boneInverses.push( boneInverse.toArray() );
  14904. }
  14905. return data;
  14906. }
  14907. }
  14908. class InstancedBufferAttribute extends BufferAttribute {
  14909. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  14910. super( array, itemSize, normalized );
  14911. this.isInstancedBufferAttribute = true;
  14912. this.meshPerAttribute = meshPerAttribute;
  14913. }
  14914. copy( source ) {
  14915. super.copy( source );
  14916. this.meshPerAttribute = source.meshPerAttribute;
  14917. return this;
  14918. }
  14919. toJSON() {
  14920. const data = super.toJSON();
  14921. data.meshPerAttribute = this.meshPerAttribute;
  14922. data.isInstancedBufferAttribute = true;
  14923. return data;
  14924. }
  14925. }
  14926. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  14927. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  14928. const _instanceIntersects = [];
  14929. const _box3 = /*@__PURE__*/ new Box3();
  14930. const _identity = /*@__PURE__*/ new Matrix4();
  14931. const _mesh$1 = /*@__PURE__*/ new Mesh();
  14932. const _sphere$4 = /*@__PURE__*/ new Sphere();
  14933. /**
  14934. * A special version of a mesh with instanced rendering support. Use
  14935. * this class if you have to render a large number of objects with the same
  14936. * geometry and material(s) but with different world transformations. The usage
  14937. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  14938. * improve the overall rendering performance in your application.
  14939. *
  14940. * @augments Mesh
  14941. */
  14942. class InstancedMesh extends Mesh {
  14943. /**
  14944. * Constructs a new instanced mesh.
  14945. *
  14946. * @param {BufferGeometry} [geometry] - The mesh geometry.
  14947. * @param {Material|Array<Material>} [material] - The mesh material.
  14948. * @param {number} count - The number of instances.
  14949. */
  14950. constructor( geometry, material, count ) {
  14951. super( geometry, material );
  14952. /**
  14953. * This flag can be used for type testing.
  14954. *
  14955. * @type {boolean}
  14956. * @readonly
  14957. * @default true
  14958. */
  14959. this.isInstancedMesh = true;
  14960. /**
  14961. * Represents the local transformation of all instances. You have to set its
  14962. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  14963. * via {@link InstancedMesh#setMatrixAt}.
  14964. *
  14965. * @type {InstancedBufferAttribute}
  14966. */
  14967. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  14968. /**
  14969. * Represents the color of all instances. You have to set its
  14970. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  14971. * via {@link InstancedMesh#setColorAt}.
  14972. *
  14973. * @type {?InstancedBufferAttribute}
  14974. * @default null
  14975. */
  14976. this.instanceColor = null;
  14977. /**
  14978. * Represents the morph target weights of all instances. You have to set its
  14979. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  14980. * via {@link InstancedMesh#setMorphAt}.
  14981. *
  14982. * @type {?InstancedBufferAttribute}
  14983. * @default null
  14984. */
  14985. this.morphTexture = null;
  14986. /**
  14987. * The number of instances.
  14988. *
  14989. * @type {number}
  14990. */
  14991. this.count = count;
  14992. /**
  14993. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  14994. *
  14995. * @type {?Box3}
  14996. * @default null
  14997. */
  14998. this.boundingBox = null;
  14999. /**
  15000. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  15001. *
  15002. * @type {?Sphere}
  15003. * @default null
  15004. */
  15005. this.boundingSphere = null;
  15006. for ( let i = 0; i < count; i ++ ) {
  15007. this.setMatrixAt( i, _identity );
  15008. }
  15009. }
  15010. /**
  15011. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  15012. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  15013. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  15014. */
  15015. computeBoundingBox() {
  15016. const geometry = this.geometry;
  15017. const count = this.count;
  15018. if ( this.boundingBox === null ) {
  15019. this.boundingBox = new Box3();
  15020. }
  15021. if ( geometry.boundingBox === null ) {
  15022. geometry.computeBoundingBox();
  15023. }
  15024. this.boundingBox.makeEmpty();
  15025. for ( let i = 0; i < count; i ++ ) {
  15026. this.getMatrixAt( i, _instanceLocalMatrix );
  15027. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  15028. this.boundingBox.union( _box3 );
  15029. }
  15030. }
  15031. /**
  15032. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  15033. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  15034. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  15035. */
  15036. computeBoundingSphere() {
  15037. const geometry = this.geometry;
  15038. const count = this.count;
  15039. if ( this.boundingSphere === null ) {
  15040. this.boundingSphere = new Sphere();
  15041. }
  15042. if ( geometry.boundingSphere === null ) {
  15043. geometry.computeBoundingSphere();
  15044. }
  15045. this.boundingSphere.makeEmpty();
  15046. for ( let i = 0; i < count; i ++ ) {
  15047. this.getMatrixAt( i, _instanceLocalMatrix );
  15048. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  15049. this.boundingSphere.union( _sphere$4 );
  15050. }
  15051. }
  15052. copy( source, recursive ) {
  15053. super.copy( source, recursive );
  15054. this.instanceMatrix.copy( source.instanceMatrix );
  15055. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  15056. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  15057. this.count = source.count;
  15058. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  15059. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  15060. return this;
  15061. }
  15062. /**
  15063. * Gets the color of the defined instance.
  15064. *
  15065. * @param {number} index - The instance index.
  15066. * @param {Color} color - The target object that is used to store the method's result.
  15067. */
  15068. getColorAt( index, color ) {
  15069. color.fromArray( this.instanceColor.array, index * 3 );
  15070. }
  15071. /**
  15072. * Gets the local transformation matrix of the defined instance.
  15073. *
  15074. * @param {number} index - The instance index.
  15075. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  15076. */
  15077. getMatrixAt( index, matrix ) {
  15078. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  15079. }
  15080. /**
  15081. * Gets the morph target weights of the defined instance.
  15082. *
  15083. * @param {number} index - The instance index.
  15084. * @param {Mesh} object - The target object that is used to store the method's result.
  15085. */
  15086. getMorphAt( index, object ) {
  15087. const objectInfluences = object.morphTargetInfluences;
  15088. const array = this.morphTexture.source.data.data;
  15089. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  15090. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  15091. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  15092. objectInfluences[ i ] = array[ dataIndex + i ];
  15093. }
  15094. }
  15095. raycast( raycaster, intersects ) {
  15096. const matrixWorld = this.matrixWorld;
  15097. const raycastTimes = this.count;
  15098. _mesh$1.geometry = this.geometry;
  15099. _mesh$1.material = this.material;
  15100. if ( _mesh$1.material === undefined ) return;
  15101. // test with bounding sphere first
  15102. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  15103. _sphere$4.copy( this.boundingSphere );
  15104. _sphere$4.applyMatrix4( matrixWorld );
  15105. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  15106. // now test each instance
  15107. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  15108. // calculate the world matrix for each instance
  15109. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  15110. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  15111. // the mesh represents this single instance
  15112. _mesh$1.matrixWorld = _instanceWorldMatrix;
  15113. _mesh$1.raycast( raycaster, _instanceIntersects );
  15114. // process the result of raycast
  15115. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  15116. const intersect = _instanceIntersects[ i ];
  15117. intersect.instanceId = instanceId;
  15118. intersect.object = this;
  15119. intersects.push( intersect );
  15120. }
  15121. _instanceIntersects.length = 0;
  15122. }
  15123. }
  15124. /**
  15125. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  15126. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  15127. *
  15128. * @param {number} index - The instance index.
  15129. * @param {Color} color - The instance color.
  15130. */
  15131. setColorAt( index, color ) {
  15132. if ( this.instanceColor === null ) {
  15133. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  15134. }
  15135. color.toArray( this.instanceColor.array, index * 3 );
  15136. }
  15137. /**
  15138. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  15139. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  15140. *
  15141. * @param {number} index - The instance index.
  15142. * @param {Matrix4} matrix - The the local transformation.
  15143. */
  15144. setMatrixAt( index, matrix ) {
  15145. matrix.toArray( this.instanceMatrix.array, index * 16 );
  15146. }
  15147. /**
  15148. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  15149. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  15150. *
  15151. * @param {number} index - The instance index.
  15152. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  15153. * of a single instance.
  15154. */
  15155. setMorphAt( index, object ) {
  15156. const objectInfluences = object.morphTargetInfluences;
  15157. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  15158. if ( this.morphTexture === null ) {
  15159. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  15160. }
  15161. const array = this.morphTexture.source.data.data;
  15162. let morphInfluencesSum = 0;
  15163. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  15164. morphInfluencesSum += objectInfluences[ i ];
  15165. }
  15166. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  15167. const dataIndex = len * index;
  15168. array[ dataIndex ] = morphBaseInfluence;
  15169. array.set( objectInfluences, dataIndex + 1 );
  15170. }
  15171. updateMorphTargets() {
  15172. }
  15173. /**
  15174. * Frees the GPU-related resources allocated by this instance. Call this
  15175. * method whenever this instance is no longer used in your app.
  15176. */
  15177. dispose() {
  15178. this.dispatchEvent( { type: 'dispose' } );
  15179. if ( this.morphTexture !== null ) {
  15180. this.morphTexture.dispose();
  15181. this.morphTexture = null;
  15182. }
  15183. }
  15184. }
  15185. const _vector1 = /*@__PURE__*/ new Vector3();
  15186. const _vector2 = /*@__PURE__*/ new Vector3();
  15187. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  15188. /**
  15189. * A two dimensional surface that extends infinitely in 3D space, represented
  15190. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  15191. * by a unit length normal vector and a constant.
  15192. */
  15193. class Plane {
  15194. /**
  15195. * Constructs a new plane.
  15196. *
  15197. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  15198. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  15199. */
  15200. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  15201. /**
  15202. * This flag can be used for type testing.
  15203. *
  15204. * @type {boolean}
  15205. * @readonly
  15206. * @default true
  15207. */
  15208. this.isPlane = true;
  15209. /**
  15210. * A unit length vector defining the normal of the plane.
  15211. *
  15212. * @type {Vector3}
  15213. */
  15214. this.normal = normal;
  15215. /**
  15216. * The signed distance from the origin to the plane.
  15217. *
  15218. * @type {number}
  15219. * @default 0
  15220. */
  15221. this.constant = constant;
  15222. }
  15223. /**
  15224. * Sets the plane components by copying the given values.
  15225. *
  15226. * @param {Vector3} normal - The normal.
  15227. * @param {number} constant - The constant.
  15228. * @return {Plane} A reference to this plane.
  15229. */
  15230. set( normal, constant ) {
  15231. this.normal.copy( normal );
  15232. this.constant = constant;
  15233. return this;
  15234. }
  15235. /**
  15236. * Sets the plane components by defining `x`, `y`, `z` as the
  15237. * plane normal and `w` as the constant.
  15238. *
  15239. * @param {number} x - The value for the normal's x component.
  15240. * @param {number} y - The value for the normal's y component.
  15241. * @param {number} z - The value for the normal's z component.
  15242. * @param {number} w - The constant value.
  15243. * @return {Plane} A reference to this plane.
  15244. */
  15245. setComponents( x, y, z, w ) {
  15246. this.normal.set( x, y, z );
  15247. this.constant = w;
  15248. return this;
  15249. }
  15250. /**
  15251. * Sets the plane from the given normal and coplanar point (that is a point
  15252. * that lies onto the plane).
  15253. *
  15254. * @param {Vector3} normal - The normal.
  15255. * @param {Vector3} point - A coplanar point.
  15256. * @return {Plane} A reference to this plane.
  15257. */
  15258. setFromNormalAndCoplanarPoint( normal, point ) {
  15259. this.normal.copy( normal );
  15260. this.constant = - point.dot( this.normal );
  15261. return this;
  15262. }
  15263. /**
  15264. * Sets the plane from three coplanar points. The winding order is
  15265. * assumed to be counter-clockwise, and determines the direction of
  15266. * the plane normal.
  15267. *
  15268. * @param {Vector3} a - The first coplanar point.
  15269. * @param {Vector3} b - The second coplanar point.
  15270. * @param {Vector3} c - The third coplanar point.
  15271. * @return {Plane} A reference to this plane.
  15272. */
  15273. setFromCoplanarPoints( a, b, c ) {
  15274. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  15275. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  15276. this.setFromNormalAndCoplanarPoint( normal, a );
  15277. return this;
  15278. }
  15279. /**
  15280. * Copies the values of the given plane to this instance.
  15281. *
  15282. * @param {Plane} plane - The plane to copy.
  15283. * @return {Plane} A reference to this plane.
  15284. */
  15285. copy( plane ) {
  15286. this.normal.copy( plane.normal );
  15287. this.constant = plane.constant;
  15288. return this;
  15289. }
  15290. /**
  15291. * Normalizes the plane normal and adjusts the constant accordingly.
  15292. *
  15293. * @return {Plane} A reference to this plane.
  15294. */
  15295. normalize() {
  15296. // Note: will lead to a divide by zero if the plane is invalid.
  15297. const inverseNormalLength = 1.0 / this.normal.length();
  15298. this.normal.multiplyScalar( inverseNormalLength );
  15299. this.constant *= inverseNormalLength;
  15300. return this;
  15301. }
  15302. /**
  15303. * Negates both the plane normal and the constant.
  15304. *
  15305. * @return {Plane} A reference to this plane.
  15306. */
  15307. negate() {
  15308. this.constant *= -1;
  15309. this.normal.negate();
  15310. return this;
  15311. }
  15312. /**
  15313. * Returns the signed distance from the given point to this plane.
  15314. *
  15315. * @param {Vector3} point - The point to compute the distance for.
  15316. * @return {number} The signed distance.
  15317. */
  15318. distanceToPoint( point ) {
  15319. return this.normal.dot( point ) + this.constant;
  15320. }
  15321. /**
  15322. * Returns the signed distance from the given sphere to this plane.
  15323. *
  15324. * @param {Sphere} sphere - The sphere to compute the distance for.
  15325. * @return {number} The signed distance.
  15326. */
  15327. distanceToSphere( sphere ) {
  15328. return this.distanceToPoint( sphere.center ) - sphere.radius;
  15329. }
  15330. /**
  15331. * Projects a the given point onto the plane.
  15332. *
  15333. * @param {Vector3} point - The point to project.
  15334. * @param {Vector3} target - The target vector that is used to store the method's result.
  15335. * @return {Vector3} The projected point on the plane.
  15336. */
  15337. projectPoint( point, target ) {
  15338. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  15339. }
  15340. /**
  15341. * Returns the intersection point of the passed line and the plane. Returns
  15342. * `null` if the line does not intersect. Returns the line's starting point if
  15343. * the line is coplanar with the plane.
  15344. *
  15345. * @param {Line3} line - The line to compute the intersection for.
  15346. * @param {Vector3} target - The target vector that is used to store the method's result.
  15347. * @return {?Vector3} The intersection point.
  15348. */
  15349. intersectLine( line, target ) {
  15350. const direction = line.delta( _vector1 );
  15351. const denominator = this.normal.dot( direction );
  15352. if ( denominator === 0 ) {
  15353. // line is coplanar, return origin
  15354. if ( this.distanceToPoint( line.start ) === 0 ) {
  15355. return target.copy( line.start );
  15356. }
  15357. // Unsure if this is the correct method to handle this case.
  15358. return null;
  15359. }
  15360. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  15361. if ( t < 0 || t > 1 ) {
  15362. return null;
  15363. }
  15364. return target.copy( line.start ).addScaledVector( direction, t );
  15365. }
  15366. /**
  15367. * Returns `true` if the given line segment intersects with (passes through) the plane.
  15368. *
  15369. * @param {Line3} line - The line to test.
  15370. * @return {boolean} Whether the given line segment intersects with the plane or not.
  15371. */
  15372. intersectsLine( line ) {
  15373. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  15374. const startSign = this.distanceToPoint( line.start );
  15375. const endSign = this.distanceToPoint( line.end );
  15376. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  15377. }
  15378. /**
  15379. * Returns `true` if the given bounding box intersects with the plane.
  15380. *
  15381. * @param {Box3} box - The bounding box to test.
  15382. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  15383. */
  15384. intersectsBox( box ) {
  15385. return box.intersectsPlane( this );
  15386. }
  15387. /**
  15388. * Returns `true` if the given bounding sphere intersects with the plane.
  15389. *
  15390. * @param {Sphere} sphere - The bounding sphere to test.
  15391. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  15392. */
  15393. intersectsSphere( sphere ) {
  15394. return sphere.intersectsPlane( this );
  15395. }
  15396. /**
  15397. * Returns a coplanar vector to the plane, by calculating the
  15398. * projection of the normal at the origin onto the plane.
  15399. *
  15400. * @param {Vector3} target - The target vector that is used to store the method's result.
  15401. * @return {Vector3} The coplanar point.
  15402. */
  15403. coplanarPoint( target ) {
  15404. return target.copy( this.normal ).multiplyScalar( - this.constant );
  15405. }
  15406. /**
  15407. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  15408. *
  15409. * The optional normal matrix can be pre-computed like so:
  15410. * ```js
  15411. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15412. * ```
  15413. *
  15414. * @param {Matrix4} matrix - The transformation matrix.
  15415. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  15416. * @return {Plane} A reference to this plane.
  15417. */
  15418. applyMatrix4( matrix, optionalNormalMatrix ) {
  15419. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  15420. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  15421. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  15422. this.constant = - referencePoint.dot( normal );
  15423. return this;
  15424. }
  15425. /**
  15426. * Translates the plane by the distance defined by the given offset vector.
  15427. * Note that this only affects the plane constant and will not affect the normal vector.
  15428. *
  15429. * @param {Vector3} offset - The offset vector.
  15430. * @return {Plane} A reference to this plane.
  15431. */
  15432. translate( offset ) {
  15433. this.constant -= offset.dot( this.normal );
  15434. return this;
  15435. }
  15436. /**
  15437. * Returns `true` if this plane is equal with the given one.
  15438. *
  15439. * @param {Plane} plane - The plane to test for equality.
  15440. * @return {boolean} Whether this plane is equal with the given one.
  15441. */
  15442. equals( plane ) {
  15443. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  15444. }
  15445. /**
  15446. * Returns a new plane with copied values from this instance.
  15447. *
  15448. * @return {Plane} A clone of this instance.
  15449. */
  15450. clone() {
  15451. return new this.constructor().copy( this );
  15452. }
  15453. }
  15454. const _sphere$3 = /*@__PURE__*/ new Sphere();
  15455. const _vector$6 = /*@__PURE__*/ new Vector3();
  15456. /**
  15457. * Frustums are used to determine what is inside the camera's field of view.
  15458. * They help speed up the rendering process - objects which lie outside a camera's
  15459. * frustum can safely be excluded from rendering.
  15460. *
  15461. * This class is mainly intended for use internally by a renderer.
  15462. */
  15463. class Frustum {
  15464. /**
  15465. * Constructs a new frustum.
  15466. *
  15467. * @param {Plane} [p0] - The first plane that encloses the frustum.
  15468. * @param {Plane} [p1] - The second plane that encloses the frustum.
  15469. * @param {Plane} [p2] - The third plane that encloses the frustum.
  15470. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  15471. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  15472. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  15473. */
  15474. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  15475. /**
  15476. * This array holds the planes that enclose the frustum.
  15477. *
  15478. * @type {Array<Plane>}
  15479. */
  15480. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  15481. }
  15482. /**
  15483. * Sets the frustum planes by copying the given planes.
  15484. *
  15485. * @param {Plane} [p0] - The first plane that encloses the frustum.
  15486. * @param {Plane} [p1] - The second plane that encloses the frustum.
  15487. * @param {Plane} [p2] - The third plane that encloses the frustum.
  15488. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  15489. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  15490. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  15491. * @return {Frustum} A reference to this frustum.
  15492. */
  15493. set( p0, p1, p2, p3, p4, p5 ) {
  15494. const planes = this.planes;
  15495. planes[ 0 ].copy( p0 );
  15496. planes[ 1 ].copy( p1 );
  15497. planes[ 2 ].copy( p2 );
  15498. planes[ 3 ].copy( p3 );
  15499. planes[ 4 ].copy( p4 );
  15500. planes[ 5 ].copy( p5 );
  15501. return this;
  15502. }
  15503. /**
  15504. * Copies the values of the given frustum to this instance.
  15505. *
  15506. * @param {Frustum} frustum - The frustum to copy.
  15507. * @return {Frustum} A reference to this frustum.
  15508. */
  15509. copy( frustum ) {
  15510. const planes = this.planes;
  15511. for ( let i = 0; i < 6; i ++ ) {
  15512. planes[ i ].copy( frustum.planes[ i ] );
  15513. }
  15514. return this;
  15515. }
  15516. /**
  15517. * Sets the frustum planes from the given projection matrix.
  15518. *
  15519. * @param {Matrix4} m - The projection matrix.
  15520. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  15521. * @return {Frustum} A reference to this frustum.
  15522. */
  15523. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  15524. const planes = this.planes;
  15525. const me = m.elements;
  15526. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  15527. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  15528. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  15529. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  15530. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  15531. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  15532. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  15533. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  15534. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  15535. if ( coordinateSystem === WebGLCoordinateSystem ) {
  15536. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  15537. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  15538. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  15539. } else {
  15540. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  15541. }
  15542. return this;
  15543. }
  15544. /**
  15545. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  15546. *
  15547. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  15548. *
  15549. * @param {Object3D} object - The 3D object to test.
  15550. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  15551. */
  15552. intersectsObject( object ) {
  15553. if ( object.boundingSphere !== undefined ) {
  15554. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  15555. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  15556. } else {
  15557. const geometry = object.geometry;
  15558. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15559. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  15560. }
  15561. return this.intersectsSphere( _sphere$3 );
  15562. }
  15563. /**
  15564. * Returns `true` if the given sprite is intersecting this frustum.
  15565. *
  15566. * @param {Sprite} sprite - The sprite to test.
  15567. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  15568. */
  15569. intersectsSprite( sprite ) {
  15570. _sphere$3.center.set( 0, 0, 0 );
  15571. _sphere$3.radius = 0.7071067811865476;
  15572. _sphere$3.applyMatrix4( sprite.matrixWorld );
  15573. return this.intersectsSphere( _sphere$3 );
  15574. }
  15575. /**
  15576. * Returns `true` if the given bounding sphere is intersecting this frustum.
  15577. *
  15578. * @param {Sphere} sphere - The bounding sphere to test.
  15579. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  15580. */
  15581. intersectsSphere( sphere ) {
  15582. const planes = this.planes;
  15583. const center = sphere.center;
  15584. const negRadius = - sphere.radius;
  15585. for ( let i = 0; i < 6; i ++ ) {
  15586. const distance = planes[ i ].distanceToPoint( center );
  15587. if ( distance < negRadius ) {
  15588. return false;
  15589. }
  15590. }
  15591. return true;
  15592. }
  15593. /**
  15594. * Returns `true` if the given bounding box is intersecting this frustum.
  15595. *
  15596. * @param {Box3} box - The bounding box to test.
  15597. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  15598. */
  15599. intersectsBox( box ) {
  15600. const planes = this.planes;
  15601. for ( let i = 0; i < 6; i ++ ) {
  15602. const plane = planes[ i ];
  15603. // corner at max distance
  15604. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  15605. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  15606. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  15607. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  15608. return false;
  15609. }
  15610. }
  15611. return true;
  15612. }
  15613. /**
  15614. * Returns `true` if the given point lies within the frustum.
  15615. *
  15616. * @param {Vector3} point - The point to test.
  15617. * @return {boolean} Whether the point lies within this frustum or not.
  15618. */
  15619. containsPoint( point ) {
  15620. const planes = this.planes;
  15621. for ( let i = 0; i < 6; i ++ ) {
  15622. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  15623. return false;
  15624. }
  15625. }
  15626. return true;
  15627. }
  15628. /**
  15629. * Returns a new frustum with copied values from this instance.
  15630. *
  15631. * @return {Frustum} A clone of this instance.
  15632. */
  15633. clone() {
  15634. return new this.constructor().copy( this );
  15635. }
  15636. }
  15637. function ascIdSort( a, b ) {
  15638. return a - b;
  15639. }
  15640. function sortOpaque( a, b ) {
  15641. return a.z - b.z;
  15642. }
  15643. function sortTransparent( a, b ) {
  15644. return b.z - a.z;
  15645. }
  15646. class MultiDrawRenderList {
  15647. constructor() {
  15648. this.index = 0;
  15649. this.pool = [];
  15650. this.list = [];
  15651. }
  15652. push( start, count, z, index ) {
  15653. const pool = this.pool;
  15654. const list = this.list;
  15655. if ( this.index >= pool.length ) {
  15656. pool.push( {
  15657. start: -1,
  15658. count: -1,
  15659. z: -1,
  15660. index: -1,
  15661. } );
  15662. }
  15663. const item = pool[ this.index ];
  15664. list.push( item );
  15665. this.index ++;
  15666. item.start = start;
  15667. item.count = count;
  15668. item.z = z;
  15669. item.index = index;
  15670. }
  15671. reset() {
  15672. this.list.length = 0;
  15673. this.index = 0;
  15674. }
  15675. }
  15676. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  15677. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  15678. const _frustum = /*@__PURE__*/ new Frustum();
  15679. const _box$1 = /*@__PURE__*/ new Box3();
  15680. const _sphere$2 = /*@__PURE__*/ new Sphere();
  15681. const _vector$5 = /*@__PURE__*/ new Vector3();
  15682. const _forward = /*@__PURE__*/ new Vector3();
  15683. const _temp = /*@__PURE__*/ new Vector3();
  15684. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  15685. const _mesh = /*@__PURE__*/ new Mesh();
  15686. const _batchIntersects = [];
  15687. // copies data from attribute "src" into "target" starting at "targetOffset"
  15688. function copyAttributeData( src, target, targetOffset = 0 ) {
  15689. const itemSize = target.itemSize;
  15690. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  15691. // use the component getters and setters if the array data cannot
  15692. // be copied directly
  15693. const vertexCount = src.count;
  15694. for ( let i = 0; i < vertexCount; i ++ ) {
  15695. for ( let c = 0; c < itemSize; c ++ ) {
  15696. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  15697. }
  15698. }
  15699. } else {
  15700. // faster copy approach using typed array set function
  15701. target.array.set( src.array, targetOffset * itemSize );
  15702. }
  15703. target.needsUpdate = true;
  15704. }
  15705. // safely copies array contents to a potentially smaller array
  15706. function copyArrayContents( src, target ) {
  15707. if ( src.constructor !== target.constructor ) {
  15708. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  15709. const len = Math.min( src.length, target.length );
  15710. for ( let i = 0; i < len; i ++ ) {
  15711. target[ i ] = src[ i ];
  15712. }
  15713. } else {
  15714. // if the arrays use the same data layout we can use a fast block copy
  15715. const len = Math.min( src.length, target.length );
  15716. target.set( new src.constructor( src.buffer, 0, len ) );
  15717. }
  15718. }
  15719. /**
  15720. * A special version of a mesh with multi draw batch rendering support. Use
  15721. * this class if you have to render a large number of objects with the same
  15722. * material but with different geometries or world transformations. The usage of
  15723. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  15724. * rendering performance in your application.
  15725. *
  15726. * ```js
  15727. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  15728. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  15729. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15730. *
  15731. * // initialize and add geometries into the batched mesh
  15732. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  15733. * const boxGeometryId = batchedMesh.addGeometry( box );
  15734. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  15735. *
  15736. * // create instances of those geometries
  15737. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  15738. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  15739. *
  15740. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  15741. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  15742. *
  15743. * // position the geometries
  15744. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  15745. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  15746. *
  15747. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  15748. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  15749. *
  15750. * scene.add( batchedMesh );
  15751. * ```
  15752. *
  15753. * @augments Mesh
  15754. */
  15755. class BatchedMesh extends Mesh {
  15756. /**
  15757. * Constructs a new batched mesh.
  15758. *
  15759. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  15760. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  15761. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  15762. * @param {Material|Array<Material>} [material] - The mesh material.
  15763. */
  15764. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  15765. super( new BufferGeometry(), material );
  15766. /**
  15767. * This flag can be used for type testing.
  15768. *
  15769. * @type {boolean}
  15770. * @readonly
  15771. * @default true
  15772. */
  15773. this.isBatchedMesh = true;
  15774. /**
  15775. * When set ot `true`, the individual objects of a batch are frustum culled.
  15776. *
  15777. * @type {boolean}
  15778. * @default true
  15779. */
  15780. this.perObjectFrustumCulled = true;
  15781. /**
  15782. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  15783. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  15784. * rendered front to back.
  15785. *
  15786. * @type {boolean}
  15787. * @default true
  15788. */
  15789. this.sortObjects = true;
  15790. /**
  15791. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  15792. *
  15793. * @type {?Box3}
  15794. * @default null
  15795. */
  15796. this.boundingBox = null;
  15797. /**
  15798. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  15799. *
  15800. * @type {?Sphere}
  15801. * @default null
  15802. */
  15803. this.boundingSphere = null;
  15804. /**
  15805. * Takes a sort a function that is run before render. The function takes a list of instances to
  15806. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  15807. * sort with.
  15808. *
  15809. * @type {?Function}
  15810. * @default null
  15811. */
  15812. this.customSort = null;
  15813. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  15814. this._instanceInfo = [];
  15815. this._geometryInfo = [];
  15816. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  15817. this._availableInstanceIds = [];
  15818. this._availableGeometryIds = [];
  15819. // used to track where the next point is that geometry should be inserted
  15820. this._nextIndexStart = 0;
  15821. this._nextVertexStart = 0;
  15822. this._geometryCount = 0;
  15823. // flags
  15824. this._visibilityChanged = true;
  15825. this._geometryInitialized = false;
  15826. // cached user options
  15827. this._maxInstanceCount = maxInstanceCount;
  15828. this._maxVertexCount = maxVertexCount;
  15829. this._maxIndexCount = maxIndexCount;
  15830. // buffers for multi draw
  15831. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  15832. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  15833. this._multiDrawCount = 0;
  15834. this._multiDrawInstances = null;
  15835. // Local matrix per geometry by using data texture
  15836. this._matricesTexture = null;
  15837. this._indirectTexture = null;
  15838. this._colorsTexture = null;
  15839. this._initMatricesTexture();
  15840. this._initIndirectTexture();
  15841. }
  15842. /**
  15843. * The maximum number of individual instances that can be stored in the batch.
  15844. *
  15845. * @type {number}
  15846. * @readonly
  15847. */
  15848. get maxInstanceCount() {
  15849. return this._maxInstanceCount;
  15850. }
  15851. /**
  15852. * The instance count.
  15853. *
  15854. * @type {number}
  15855. * @readonly
  15856. */
  15857. get instanceCount() {
  15858. return this._instanceInfo.length - this._availableInstanceIds.length;
  15859. }
  15860. /**
  15861. * The number of unused vertices.
  15862. *
  15863. * @type {number}
  15864. * @readonly
  15865. */
  15866. get unusedVertexCount() {
  15867. return this._maxVertexCount - this._nextVertexStart;
  15868. }
  15869. /**
  15870. * The number of unused indices.
  15871. *
  15872. * @type {number}
  15873. * @readonly
  15874. */
  15875. get unusedIndexCount() {
  15876. return this._maxIndexCount - this._nextIndexStart;
  15877. }
  15878. _initMatricesTexture() {
  15879. // layout (1 matrix = 4 pixels)
  15880. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15881. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  15882. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  15883. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  15884. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  15885. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  15886. size = Math.ceil( size / 4 ) * 4;
  15887. size = Math.max( size, 4 );
  15888. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15889. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  15890. this._matricesTexture = matricesTexture;
  15891. }
  15892. _initIndirectTexture() {
  15893. let size = Math.sqrt( this._maxInstanceCount );
  15894. size = Math.ceil( size );
  15895. const indirectArray = new Uint32Array( size * size );
  15896. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  15897. this._indirectTexture = indirectTexture;
  15898. }
  15899. _initColorsTexture() {
  15900. let size = Math.sqrt( this._maxInstanceCount );
  15901. size = Math.ceil( size );
  15902. // 4 floats per RGBA pixel initialized to white
  15903. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  15904. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  15905. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  15906. this._colorsTexture = colorsTexture;
  15907. }
  15908. _initializeGeometry( reference ) {
  15909. const geometry = this.geometry;
  15910. const maxVertexCount = this._maxVertexCount;
  15911. const maxIndexCount = this._maxIndexCount;
  15912. if ( this._geometryInitialized === false ) {
  15913. for ( const attributeName in reference.attributes ) {
  15914. const srcAttribute = reference.getAttribute( attributeName );
  15915. const { array, itemSize, normalized } = srcAttribute;
  15916. const dstArray = new array.constructor( maxVertexCount * itemSize );
  15917. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  15918. geometry.setAttribute( attributeName, dstAttribute );
  15919. }
  15920. if ( reference.getIndex() !== null ) {
  15921. // Reserve last u16 index for primitive restart.
  15922. const indexArray = maxVertexCount > 65535
  15923. ? new Uint32Array( maxIndexCount )
  15924. : new Uint16Array( maxIndexCount );
  15925. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  15926. }
  15927. this._geometryInitialized = true;
  15928. }
  15929. }
  15930. // Make sure the geometry is compatible with the existing combined geometry attributes
  15931. _validateGeometry( geometry ) {
  15932. // check to ensure the geometries are using consistent attributes and indices
  15933. const batchGeometry = this.geometry;
  15934. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  15935. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  15936. }
  15937. for ( const attributeName in batchGeometry.attributes ) {
  15938. if ( ! geometry.hasAttribute( attributeName ) ) {
  15939. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  15940. }
  15941. const srcAttribute = geometry.getAttribute( attributeName );
  15942. const dstAttribute = batchGeometry.getAttribute( attributeName );
  15943. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  15944. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  15945. }
  15946. }
  15947. }
  15948. /**
  15949. * Validates the instance defined by the given ID.
  15950. *
  15951. * @param {number} instanceId - The the instance to validate.
  15952. */
  15953. validateInstanceId( instanceId ) {
  15954. const instanceInfo = this._instanceInfo;
  15955. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  15956. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  15957. }
  15958. }
  15959. /**
  15960. * Validates the geometry defined by the given ID.
  15961. *
  15962. * @param {number} geometryId - The the geometry to validate.
  15963. */
  15964. validateGeometryId( geometryId ) {
  15965. const geometryInfoList = this._geometryInfo;
  15966. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  15967. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  15968. }
  15969. }
  15970. /**
  15971. * Takes a sort a function that is run before render. The function takes a list of instances to
  15972. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  15973. *
  15974. * @param {Function} func - The custom sort function.
  15975. * @return {BatchedMesh} A reference to this batched mesh.
  15976. */
  15977. setCustomSort( func ) {
  15978. this.customSort = func;
  15979. return this;
  15980. }
  15981. /**
  15982. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  15983. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  15984. * otherwise they are `null`.
  15985. */
  15986. computeBoundingBox() {
  15987. if ( this.boundingBox === null ) {
  15988. this.boundingBox = new Box3();
  15989. }
  15990. const boundingBox = this.boundingBox;
  15991. const instanceInfo = this._instanceInfo;
  15992. boundingBox.makeEmpty();
  15993. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  15994. if ( instanceInfo[ i ].active === false ) continue;
  15995. const geometryId = instanceInfo[ i ].geometryIndex;
  15996. this.getMatrixAt( i, _matrix$1 );
  15997. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  15998. boundingBox.union( _box$1 );
  15999. }
  16000. }
  16001. /**
  16002. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  16003. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  16004. * otherwise they are `null`.
  16005. */
  16006. computeBoundingSphere() {
  16007. if ( this.boundingSphere === null ) {
  16008. this.boundingSphere = new Sphere();
  16009. }
  16010. const boundingSphere = this.boundingSphere;
  16011. const instanceInfo = this._instanceInfo;
  16012. boundingSphere.makeEmpty();
  16013. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16014. if ( instanceInfo[ i ].active === false ) continue;
  16015. const geometryId = instanceInfo[ i ].geometryIndex;
  16016. this.getMatrixAt( i, _matrix$1 );
  16017. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  16018. boundingSphere.union( _sphere$2 );
  16019. }
  16020. }
  16021. /**
  16022. * Adds a new instance to the batch using the geometry of the given ID and returns
  16023. * a new id referring to the new instance to be used by other functions.
  16024. *
  16025. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  16026. * @return {number} The instance ID.
  16027. */
  16028. addInstance( geometryId ) {
  16029. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  16030. // ensure we're not over geometry
  16031. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  16032. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  16033. }
  16034. const instanceInfo = {
  16035. visible: true,
  16036. active: true,
  16037. geometryIndex: geometryId,
  16038. };
  16039. let drawId = null;
  16040. // Prioritize using previously freed instance ids
  16041. if ( this._availableInstanceIds.length > 0 ) {
  16042. this._availableInstanceIds.sort( ascIdSort );
  16043. drawId = this._availableInstanceIds.shift();
  16044. this._instanceInfo[ drawId ] = instanceInfo;
  16045. } else {
  16046. drawId = this._instanceInfo.length;
  16047. this._instanceInfo.push( instanceInfo );
  16048. }
  16049. const matricesTexture = this._matricesTexture;
  16050. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  16051. matricesTexture.needsUpdate = true;
  16052. const colorsTexture = this._colorsTexture;
  16053. if ( colorsTexture ) {
  16054. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  16055. colorsTexture.needsUpdate = true;
  16056. }
  16057. this._visibilityChanged = true;
  16058. return drawId;
  16059. }
  16060. /**
  16061. * Adds the given geometry to the batch and returns the associated
  16062. * geometry id referring to it to be used in other functions.
  16063. *
  16064. * @param {BufferGeometry} geometry - The geometry to add.
  16065. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  16066. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  16067. * to set a new geometry at this index at a later time that is larger than the original geometry.
  16068. * Defaults to the length of the given geometry vertex buffer.
  16069. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  16070. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  16071. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  16072. * the length of the given geometry index buffer.
  16073. * @return {number} The geometry ID.
  16074. */
  16075. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  16076. this._initializeGeometry( geometry );
  16077. this._validateGeometry( geometry );
  16078. const geometryInfo = {
  16079. // geometry information
  16080. vertexStart: -1,
  16081. vertexCount: -1,
  16082. reservedVertexCount: -1,
  16083. indexStart: -1,
  16084. indexCount: -1,
  16085. reservedIndexCount: -1,
  16086. // draw range information
  16087. start: -1,
  16088. count: -1,
  16089. // state
  16090. boundingBox: null,
  16091. boundingSphere: null,
  16092. active: true,
  16093. };
  16094. const geometryInfoList = this._geometryInfo;
  16095. geometryInfo.vertexStart = this._nextVertexStart;
  16096. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  16097. const index = geometry.getIndex();
  16098. const hasIndex = index !== null;
  16099. if ( hasIndex ) {
  16100. geometryInfo.indexStart = this._nextIndexStart;
  16101. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  16102. }
  16103. if (
  16104. geometryInfo.indexStart !== -1 &&
  16105. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  16106. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  16107. ) {
  16108. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  16109. }
  16110. // update id
  16111. let geometryId;
  16112. if ( this._availableGeometryIds.length > 0 ) {
  16113. this._availableGeometryIds.sort( ascIdSort );
  16114. geometryId = this._availableGeometryIds.shift();
  16115. geometryInfoList[ geometryId ] = geometryInfo;
  16116. } else {
  16117. geometryId = this._geometryCount;
  16118. this._geometryCount ++;
  16119. geometryInfoList.push( geometryInfo );
  16120. }
  16121. // update the geometry
  16122. this.setGeometryAt( geometryId, geometry );
  16123. // increment the next geometry position
  16124. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  16125. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  16126. return geometryId;
  16127. }
  16128. /**
  16129. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  16130. * is not enough space reserved for geometry. Calling this will change all instances that are
  16131. * rendering that geometry.
  16132. *
  16133. * @param {number} geometryId - The ID of the geomtry that should be replaced with the given geometry.
  16134. * @param {BufferGeometry} geometry - The new geometry.
  16135. * @return {number} The geometry ID.
  16136. */
  16137. setGeometryAt( geometryId, geometry ) {
  16138. if ( geometryId >= this._geometryCount ) {
  16139. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  16140. }
  16141. this._validateGeometry( geometry );
  16142. const batchGeometry = this.geometry;
  16143. const hasIndex = batchGeometry.getIndex() !== null;
  16144. const dstIndex = batchGeometry.getIndex();
  16145. const srcIndex = geometry.getIndex();
  16146. const geometryInfo = this._geometryInfo[ geometryId ];
  16147. if (
  16148. hasIndex &&
  16149. srcIndex.count > geometryInfo.reservedIndexCount ||
  16150. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  16151. ) {
  16152. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  16153. }
  16154. // copy geometry buffer data over
  16155. const vertexStart = geometryInfo.vertexStart;
  16156. const reservedVertexCount = geometryInfo.reservedVertexCount;
  16157. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  16158. for ( const attributeName in batchGeometry.attributes ) {
  16159. // copy attribute data
  16160. const srcAttribute = geometry.getAttribute( attributeName );
  16161. const dstAttribute = batchGeometry.getAttribute( attributeName );
  16162. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  16163. // fill the rest in with zeroes
  16164. const itemSize = srcAttribute.itemSize;
  16165. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  16166. const index = vertexStart + i;
  16167. for ( let c = 0; c < itemSize; c ++ ) {
  16168. dstAttribute.setComponent( index, c, 0 );
  16169. }
  16170. }
  16171. dstAttribute.needsUpdate = true;
  16172. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  16173. }
  16174. // copy index
  16175. if ( hasIndex ) {
  16176. const indexStart = geometryInfo.indexStart;
  16177. const reservedIndexCount = geometryInfo.reservedIndexCount;
  16178. geometryInfo.indexCount = geometry.getIndex().count;
  16179. // copy index data over
  16180. for ( let i = 0; i < srcIndex.count; i ++ ) {
  16181. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  16182. }
  16183. // fill the rest in with zeroes
  16184. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  16185. dstIndex.setX( indexStart + i, vertexStart );
  16186. }
  16187. dstIndex.needsUpdate = true;
  16188. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  16189. }
  16190. // update the draw range
  16191. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  16192. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  16193. // store the bounding boxes
  16194. geometryInfo.boundingBox = null;
  16195. if ( geometry.boundingBox !== null ) {
  16196. geometryInfo.boundingBox = geometry.boundingBox.clone();
  16197. }
  16198. geometryInfo.boundingSphere = null;
  16199. if ( geometry.boundingSphere !== null ) {
  16200. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  16201. }
  16202. this._visibilityChanged = true;
  16203. return geometryId;
  16204. }
  16205. /**
  16206. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  16207. * this geometry will also be removed as a side effect.
  16208. *
  16209. * @param {number} geometryId - The ID of the geomtry to remove from the batch.
  16210. * @return {BatchedMesh} A reference to this batched mesh.
  16211. */
  16212. deleteGeometry( geometryId ) {
  16213. const geometryInfoList = this._geometryInfo;
  16214. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  16215. return this;
  16216. }
  16217. // delete any instances associated with this geometry
  16218. const instanceInfo = this._instanceInfo;
  16219. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16220. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  16221. this.deleteInstance( i );
  16222. }
  16223. }
  16224. geometryInfoList[ geometryId ].active = false;
  16225. this._availableGeometryIds.push( geometryId );
  16226. this._visibilityChanged = true;
  16227. return this;
  16228. }
  16229. /**
  16230. * Deletes an existing instance from the batch using the given ID.
  16231. *
  16232. * @param {number} instanceId - The ID of the instance to remove from the batch.
  16233. * @return {BatchedMesh} A reference to this batched mesh.
  16234. */
  16235. deleteInstance( instanceId ) {
  16236. this.validateInstanceId( instanceId );
  16237. this._instanceInfo[ instanceId ].active = false;
  16238. this._availableInstanceIds.push( instanceId );
  16239. this._visibilityChanged = true;
  16240. return this;
  16241. }
  16242. /**
  16243. * Repacks the sub geometries in [name] to remove any unused space remaining from
  16244. * previously deleted geometry, freeing up space to add new geometry.
  16245. *
  16246. * @param {number} instanceId - The ID of the instance to remove from the batch.
  16247. * @return {BatchedMesh} A reference to this batched mesh.
  16248. */
  16249. optimize() {
  16250. // track the next indices to copy data to
  16251. let nextVertexStart = 0;
  16252. let nextIndexStart = 0;
  16253. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  16254. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  16255. const geometryInfoList = this._geometryInfo;
  16256. const indices = geometryInfoList
  16257. .map( ( e, i ) => i )
  16258. .sort( ( a, b ) => {
  16259. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  16260. } );
  16261. const geometry = this.geometry;
  16262. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  16263. // if a geometry range is inactive then don't copy anything
  16264. const index = indices[ i ];
  16265. const geometryInfo = geometryInfoList[ index ];
  16266. if ( geometryInfo.active === false ) {
  16267. continue;
  16268. }
  16269. // if a geometry contains an index buffer then shift it, as well
  16270. if ( geometry.index !== null ) {
  16271. if ( geometryInfo.indexStart !== nextIndexStart ) {
  16272. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  16273. const index = geometry.index;
  16274. const array = index.array;
  16275. // shift the index pointers based on how the vertex data will shift
  16276. // adjusting the index must happen first so the original vertex start value is available
  16277. const elementDelta = nextVertexStart - vertexStart;
  16278. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  16279. array[ j ] = array[ j ] + elementDelta;
  16280. }
  16281. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  16282. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  16283. geometryInfo.indexStart = nextIndexStart;
  16284. }
  16285. nextIndexStart += geometryInfo.reservedIndexCount;
  16286. }
  16287. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  16288. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  16289. const { vertexStart, reservedVertexCount } = geometryInfo;
  16290. const attributes = geometry.attributes;
  16291. for ( const key in attributes ) {
  16292. const attribute = attributes[ key ];
  16293. const { array, itemSize } = attribute;
  16294. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  16295. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  16296. }
  16297. geometryInfo.vertexStart = nextVertexStart;
  16298. }
  16299. nextVertexStart += geometryInfo.reservedVertexCount;
  16300. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  16301. // step the next geometry points to the shifted position
  16302. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  16303. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  16304. }
  16305. return this;
  16306. }
  16307. /**
  16308. * Returns the bounding box for the given geometry.
  16309. *
  16310. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  16311. * @param {Box3} target - The target object that is used to store the method's result.
  16312. * @return {Box3|null} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  16313. */
  16314. getBoundingBoxAt( geometryId, target ) {
  16315. if ( geometryId >= this._geometryCount ) {
  16316. return null;
  16317. }
  16318. // compute bounding box
  16319. const geometry = this.geometry;
  16320. const geometryInfo = this._geometryInfo[ geometryId ];
  16321. if ( geometryInfo.boundingBox === null ) {
  16322. const box = new Box3();
  16323. const index = geometry.index;
  16324. const position = geometry.attributes.position;
  16325. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  16326. let iv = i;
  16327. if ( index ) {
  16328. iv = index.getX( iv );
  16329. }
  16330. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  16331. }
  16332. geometryInfo.boundingBox = box;
  16333. }
  16334. target.copy( geometryInfo.boundingBox );
  16335. return target;
  16336. }
  16337. /**
  16338. * Returns the bounding sphere for the given geometry.
  16339. *
  16340. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  16341. * @param {Sphere} target - The target object that is used to store the method's result.
  16342. * @return {Sphere|null} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  16343. */
  16344. getBoundingSphereAt( geometryId, target ) {
  16345. if ( geometryId >= this._geometryCount ) {
  16346. return null;
  16347. }
  16348. // compute bounding sphere
  16349. const geometry = this.geometry;
  16350. const geometryInfo = this._geometryInfo[ geometryId ];
  16351. if ( geometryInfo.boundingSphere === null ) {
  16352. const sphere = new Sphere();
  16353. this.getBoundingBoxAt( geometryId, _box$1 );
  16354. _box$1.getCenter( sphere.center );
  16355. const index = geometry.index;
  16356. const position = geometry.attributes.position;
  16357. let maxRadiusSq = 0;
  16358. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  16359. let iv = i;
  16360. if ( index ) {
  16361. iv = index.getX( iv );
  16362. }
  16363. _vector$5.fromBufferAttribute( position, iv );
  16364. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  16365. }
  16366. sphere.radius = Math.sqrt( maxRadiusSq );
  16367. geometryInfo.boundingSphere = sphere;
  16368. }
  16369. target.copy( geometryInfo.boundingSphere );
  16370. return target;
  16371. }
  16372. /**
  16373. * Sets the given local transformation matrix to the defined instance.
  16374. * Negatively scaled matrices are not supported.
  16375. *
  16376. * @param {number} instanceId - The ID of an instance to set the matrix of.
  16377. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  16378. * @return {BatchedMesh} A reference to this batched mesh.
  16379. */
  16380. setMatrixAt( instanceId, matrix ) {
  16381. this.validateInstanceId( instanceId );
  16382. const matricesTexture = this._matricesTexture;
  16383. const matricesArray = this._matricesTexture.image.data;
  16384. matrix.toArray( matricesArray, instanceId * 16 );
  16385. matricesTexture.needsUpdate = true;
  16386. return this;
  16387. }
  16388. /**
  16389. * Returns the local transformation matrix of the defined instance.
  16390. *
  16391. * @param {number} instanceId - The ID of an instance to get the matrix of.
  16392. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  16393. * @return {Matrix4} The instance's local transformation matrix.
  16394. */
  16395. getMatrixAt( instanceId, matrix ) {
  16396. this.validateInstanceId( instanceId );
  16397. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  16398. }
  16399. /**
  16400. * Sets the given color to the defined instance.
  16401. *
  16402. * @param {number} instanceId - The ID of an instance to set the color of.
  16403. * @param {Color} color - The color to set the instance to.
  16404. * @return {BatchedMesh} A reference to this batched mesh.
  16405. */
  16406. setColorAt( instanceId, color ) {
  16407. this.validateInstanceId( instanceId );
  16408. if ( this._colorsTexture === null ) {
  16409. this._initColorsTexture();
  16410. }
  16411. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  16412. this._colorsTexture.needsUpdate = true;
  16413. return this;
  16414. }
  16415. /**
  16416. * Returns the color of the defined instance.
  16417. *
  16418. * @param {number} instanceId - The ID of an instance to get the color of.
  16419. * @param {Color} color - The target object that is used to store the method's result.
  16420. * @return {Color} The instance's color.
  16421. */
  16422. getColorAt( instanceId, color ) {
  16423. this.validateInstanceId( instanceId );
  16424. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  16425. }
  16426. /**
  16427. * Sets the visibility of the instance.
  16428. *
  16429. * @param {number} instanceId - The id of the instance to set the visibility of.
  16430. * @param {boolean} visible - Whether the instance is visible or not.
  16431. * @return {BatchedMesh} A reference to this batched mesh.
  16432. */
  16433. setVisibleAt( instanceId, visible ) {
  16434. this.validateInstanceId( instanceId );
  16435. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  16436. return this;
  16437. }
  16438. this._instanceInfo[ instanceId ].visible = visible;
  16439. this._visibilityChanged = true;
  16440. return this;
  16441. }
  16442. /**
  16443. * Returns the visibility state of the defined instance.
  16444. *
  16445. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  16446. * @return {boolean} Whether the instance is visible or not.
  16447. */
  16448. getVisibleAt( instanceId ) {
  16449. this.validateInstanceId( instanceId );
  16450. return this._instanceInfo[ instanceId ].visible;
  16451. }
  16452. /**
  16453. * Sets the geometry ID of the instance at the given index.
  16454. *
  16455. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  16456. * @param {number} geometryId - The geometry ID to be use by the instance.
  16457. * @return {BatchedMesh} A reference to this batched mesh.
  16458. */
  16459. setGeometryIdAt( instanceId, geometryId ) {
  16460. this.validateInstanceId( instanceId );
  16461. this.validateGeometryId( geometryId );
  16462. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  16463. return this;
  16464. }
  16465. /**
  16466. * Returns the geometry ID of the defined instance.
  16467. *
  16468. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  16469. * @return {number} The instance's geometry ID.
  16470. */
  16471. getGeometryIdAt( instanceId ) {
  16472. this.validateInstanceId( instanceId );
  16473. return this._instanceInfo[ instanceId ].geometryIndex;
  16474. }
  16475. /**
  16476. * Get the range representing the subset of triangles related to the attached geometry,
  16477. * indicating the starting offset and count, or `null` if invalid.
  16478. *
  16479. * @param {number} geometryId - The id of the geometry to get the range of.
  16480. * @param {Object} [target] - The target object that is used to store the method's result.
  16481. * @return {{
  16482. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  16483. * indexStart:number,indexCount:number,reservedIndexCount:number,
  16484. * start:number,count:number
  16485. * }} The result object with range data.
  16486. */
  16487. getGeometryRangeAt( geometryId, target = {} ) {
  16488. this.validateGeometryId( geometryId );
  16489. const geometryInfo = this._geometryInfo[ geometryId ];
  16490. target.vertexStart = geometryInfo.vertexStart;
  16491. target.vertexCount = geometryInfo.vertexCount;
  16492. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  16493. target.indexStart = geometryInfo.indexStart;
  16494. target.indexCount = geometryInfo.indexCount;
  16495. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  16496. target.start = geometryInfo.start;
  16497. target.count = geometryInfo.count;
  16498. return target;
  16499. }
  16500. /**
  16501. * Resizes the necessary buffers to support the provided number of instances.
  16502. * If the provided arguments shrink the number of instances but there are not enough
  16503. * unused Ids at the end of the list then an error is thrown.
  16504. *
  16505. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  16506. */
  16507. setInstanceCount( maxInstanceCount ) {
  16508. // shrink the available instances as much as possible
  16509. const availableInstanceIds = this._availableInstanceIds;
  16510. const instanceInfo = this._instanceInfo;
  16511. availableInstanceIds.sort( ascIdSort );
  16512. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  16513. instanceInfo.pop();
  16514. availableInstanceIds.pop();
  16515. }
  16516. // throw an error if it can't be shrunk to the desired size
  16517. if ( maxInstanceCount < instanceInfo.length ) {
  16518. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  16519. }
  16520. // copy the multi draw counts
  16521. const multiDrawCounts = new Int32Array( maxInstanceCount );
  16522. const multiDrawStarts = new Int32Array( maxInstanceCount );
  16523. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  16524. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  16525. this._multiDrawCounts = multiDrawCounts;
  16526. this._multiDrawStarts = multiDrawStarts;
  16527. this._maxInstanceCount = maxInstanceCount;
  16528. // update texture data for instance sampling
  16529. const indirectTexture = this._indirectTexture;
  16530. const matricesTexture = this._matricesTexture;
  16531. const colorsTexture = this._colorsTexture;
  16532. indirectTexture.dispose();
  16533. this._initIndirectTexture();
  16534. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  16535. matricesTexture.dispose();
  16536. this._initMatricesTexture();
  16537. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  16538. if ( colorsTexture ) {
  16539. colorsTexture.dispose();
  16540. this._initColorsTexture();
  16541. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  16542. }
  16543. }
  16544. /**
  16545. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  16546. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  16547. * end of the geometry attributes then an error is thrown.
  16548. *
  16549. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  16550. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  16551. */
  16552. setGeometrySize( maxVertexCount, maxIndexCount ) {
  16553. // Check if we can shrink to the requested vertex attribute size
  16554. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  16555. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  16556. if ( requiredVertexLength > maxVertexCount ) {
  16557. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  16558. }
  16559. // Check if we can shrink to the requested index attribute size
  16560. if ( this.geometry.index ) {
  16561. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  16562. if ( requiredIndexLength > maxIndexCount ) {
  16563. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  16564. }
  16565. }
  16566. //
  16567. // dispose of the previous geometry
  16568. const oldGeometry = this.geometry;
  16569. oldGeometry.dispose();
  16570. // recreate the geometry needed based on the previous variant
  16571. this._maxVertexCount = maxVertexCount;
  16572. this._maxIndexCount = maxIndexCount;
  16573. if ( this._geometryInitialized ) {
  16574. this._geometryInitialized = false;
  16575. this.geometry = new BufferGeometry();
  16576. this._initializeGeometry( oldGeometry );
  16577. }
  16578. // copy data from the previous geometry
  16579. const geometry = this.geometry;
  16580. if ( oldGeometry.index ) {
  16581. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  16582. }
  16583. for ( const key in oldGeometry.attributes ) {
  16584. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  16585. }
  16586. }
  16587. raycast( raycaster, intersects ) {
  16588. const instanceInfo = this._instanceInfo;
  16589. const geometryInfoList = this._geometryInfo;
  16590. const matrixWorld = this.matrixWorld;
  16591. const batchGeometry = this.geometry;
  16592. // iterate over each geometry
  16593. _mesh.material = this.material;
  16594. _mesh.geometry.index = batchGeometry.index;
  16595. _mesh.geometry.attributes = batchGeometry.attributes;
  16596. if ( _mesh.geometry.boundingBox === null ) {
  16597. _mesh.geometry.boundingBox = new Box3();
  16598. }
  16599. if ( _mesh.geometry.boundingSphere === null ) {
  16600. _mesh.geometry.boundingSphere = new Sphere();
  16601. }
  16602. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16603. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  16604. continue;
  16605. }
  16606. const geometryId = instanceInfo[ i ].geometryIndex;
  16607. const geometryInfo = geometryInfoList[ geometryId ];
  16608. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  16609. // get the intersects
  16610. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  16611. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  16612. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  16613. _mesh.raycast( raycaster, _batchIntersects );
  16614. // add batch id to the intersects
  16615. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  16616. const intersect = _batchIntersects[ j ];
  16617. intersect.object = this;
  16618. intersect.batchId = i;
  16619. intersects.push( intersect );
  16620. }
  16621. _batchIntersects.length = 0;
  16622. }
  16623. _mesh.material = null;
  16624. _mesh.geometry.index = null;
  16625. _mesh.geometry.attributes = {};
  16626. _mesh.geometry.setDrawRange( 0, Infinity );
  16627. }
  16628. copy( source ) {
  16629. super.copy( source );
  16630. this.geometry = source.geometry.clone();
  16631. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  16632. this.sortObjects = source.sortObjects;
  16633. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  16634. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  16635. this._geometryInfo = source._geometryInfo.map( info => ( {
  16636. ...info,
  16637. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  16638. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  16639. } ) );
  16640. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  16641. this._maxInstanceCount = source._maxInstanceCount;
  16642. this._maxVertexCount = source._maxVertexCount;
  16643. this._maxIndexCount = source._maxIndexCount;
  16644. this._geometryInitialized = source._geometryInitialized;
  16645. this._geometryCount = source._geometryCount;
  16646. this._multiDrawCounts = source._multiDrawCounts.slice();
  16647. this._multiDrawStarts = source._multiDrawStarts.slice();
  16648. this._matricesTexture = source._matricesTexture.clone();
  16649. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  16650. if ( this._colorsTexture !== null ) {
  16651. this._colorsTexture = source._colorsTexture.clone();
  16652. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  16653. }
  16654. return this;
  16655. }
  16656. /**
  16657. * Frees the GPU-related resources allocated by this instance. Call this
  16658. * method whenever this instance is no longer used in your app.
  16659. */
  16660. dispose() {
  16661. // Assuming the geometry is not shared with other meshes
  16662. this.geometry.dispose();
  16663. this._matricesTexture.dispose();
  16664. this._matricesTexture = null;
  16665. this._indirectTexture.dispose();
  16666. this._indirectTexture = null;
  16667. if ( this._colorsTexture !== null ) {
  16668. this._colorsTexture.dispose();
  16669. this._colorsTexture = null;
  16670. }
  16671. }
  16672. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  16673. // if visibility has not changed and frustum culling and object sorting is not required
  16674. // then skip iterating over all items
  16675. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  16676. return;
  16677. }
  16678. // the indexed version of the multi draw function requires specifying the start
  16679. // offset in bytes.
  16680. const index = geometry.getIndex();
  16681. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  16682. const instanceInfo = this._instanceInfo;
  16683. const multiDrawStarts = this._multiDrawStarts;
  16684. const multiDrawCounts = this._multiDrawCounts;
  16685. const geometryInfoList = this._geometryInfo;
  16686. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  16687. const indirectTexture = this._indirectTexture;
  16688. const indirectArray = indirectTexture.image.data;
  16689. // prepare the frustum in the local frame
  16690. if ( perObjectFrustumCulled ) {
  16691. _matrix$1
  16692. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  16693. .multiply( this.matrixWorld );
  16694. _frustum.setFromProjectionMatrix(
  16695. _matrix$1,
  16696. renderer.coordinateSystem
  16697. );
  16698. }
  16699. let multiDrawCount = 0;
  16700. if ( this.sortObjects ) {
  16701. // get the camera position in the local frame
  16702. _matrix$1.copy( this.matrixWorld ).invert();
  16703. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  16704. _forward.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  16705. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16706. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  16707. const geometryId = instanceInfo[ i ].geometryIndex;
  16708. // get the bounds in world space
  16709. this.getMatrixAt( i, _matrix$1 );
  16710. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  16711. // determine whether the batched geometry is within the frustum
  16712. let culled = false;
  16713. if ( perObjectFrustumCulled ) {
  16714. culled = ! _frustum.intersectsSphere( _sphere$2 );
  16715. }
  16716. if ( ! culled ) {
  16717. // get the distance from camera used for sorting
  16718. const geometryInfo = geometryInfoList[ geometryId ];
  16719. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  16720. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  16721. }
  16722. }
  16723. }
  16724. // Sort the draw ranges and prep for rendering
  16725. const list = _renderList.list;
  16726. const customSort = this.customSort;
  16727. if ( customSort === null ) {
  16728. list.sort( material.transparent ? sortTransparent : sortOpaque );
  16729. } else {
  16730. customSort.call( this, list, camera );
  16731. }
  16732. for ( let i = 0, l = list.length; i < l; i ++ ) {
  16733. const item = list[ i ];
  16734. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  16735. multiDrawCounts[ multiDrawCount ] = item.count;
  16736. indirectArray[ multiDrawCount ] = item.index;
  16737. multiDrawCount ++;
  16738. }
  16739. _renderList.reset();
  16740. } else {
  16741. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  16742. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  16743. const geometryId = instanceInfo[ i ].geometryIndex;
  16744. // determine whether the batched geometry is within the frustum
  16745. let culled = false;
  16746. if ( perObjectFrustumCulled ) {
  16747. // get the bounds in world space
  16748. this.getMatrixAt( i, _matrix$1 );
  16749. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  16750. culled = ! _frustum.intersectsSphere( _sphere$2 );
  16751. }
  16752. if ( ! culled ) {
  16753. const geometryInfo = geometryInfoList[ geometryId ];
  16754. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  16755. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  16756. indirectArray[ multiDrawCount ] = i;
  16757. multiDrawCount ++;
  16758. }
  16759. }
  16760. }
  16761. }
  16762. indirectTexture.needsUpdate = true;
  16763. this._multiDrawCount = multiDrawCount;
  16764. this._visibilityChanged = false;
  16765. }
  16766. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  16767. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  16768. }
  16769. }
  16770. class LineBasicMaterial extends Material {
  16771. constructor( parameters ) {
  16772. super();
  16773. this.isLineBasicMaterial = true;
  16774. this.type = 'LineBasicMaterial';
  16775. this.color = new Color( 0xffffff );
  16776. this.map = null;
  16777. this.linewidth = 1;
  16778. this.linecap = 'round';
  16779. this.linejoin = 'round';
  16780. this.fog = true;
  16781. this.setValues( parameters );
  16782. }
  16783. copy( source ) {
  16784. super.copy( source );
  16785. this.color.copy( source.color );
  16786. this.map = source.map;
  16787. this.linewidth = source.linewidth;
  16788. this.linecap = source.linecap;
  16789. this.linejoin = source.linejoin;
  16790. this.fog = source.fog;
  16791. return this;
  16792. }
  16793. }
  16794. const _vStart = /*@__PURE__*/ new Vector3();
  16795. const _vEnd = /*@__PURE__*/ new Vector3();
  16796. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  16797. const _ray$1 = /*@__PURE__*/ new Ray();
  16798. const _sphere$1 = /*@__PURE__*/ new Sphere();
  16799. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  16800. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  16801. /**
  16802. * A continuous line. The line are rendered by connecting consecutive
  16803. * vertices with straight lines.
  16804. *
  16805. * ```js
  16806. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  16807. *
  16808. * const points = [];
  16809. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  16810. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  16811. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  16812. *
  16813. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  16814. *
  16815. * const line = new THREE.Line( geometry, material );
  16816. * scene.add( line );
  16817. * ```
  16818. *
  16819. * @augments Object3D
  16820. */
  16821. class Line extends Object3D {
  16822. /**
  16823. * Constructs a new line.
  16824. *
  16825. * @param {BufferGeometry} [geometry] - The line geometry.
  16826. * @param {Material|Array<Material>} [material] - The line material.
  16827. */
  16828. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  16829. super();
  16830. /**
  16831. * This flag can be used for type testing.
  16832. *
  16833. * @type {boolean}
  16834. * @readonly
  16835. * @default true
  16836. */
  16837. this.isLine = true;
  16838. this.type = 'Line';
  16839. /**
  16840. * The line geometry.
  16841. *
  16842. * @type {BufferGeometry}
  16843. */
  16844. this.geometry = geometry;
  16845. /**
  16846. * The line material.
  16847. *
  16848. * @type {Material|Array<Material>}
  16849. * @default LineBasicMaterial
  16850. */
  16851. this.material = material;
  16852. /**
  16853. * A dictionary representing the morph targets in the geometry. The key is the
  16854. * morph targets name, the value its attribute index. This member is `undefined`
  16855. * by default and only set when morph targets are detected in the geometry.
  16856. *
  16857. * @type {Object<String,number>|undefined}
  16858. * @default undefined
  16859. */
  16860. this.morphTargetDictionary = undefined;
  16861. /**
  16862. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  16863. * is applied. This member is `undefined` by default and only set when morph targets are
  16864. * detected in the geometry.
  16865. *
  16866. * @type {Array<number>|undefined}
  16867. * @default undefined
  16868. */
  16869. this.morphTargetInfluences = undefined;
  16870. this.updateMorphTargets();
  16871. }
  16872. copy( source, recursive ) {
  16873. super.copy( source, recursive );
  16874. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  16875. this.geometry = source.geometry;
  16876. return this;
  16877. }
  16878. /**
  16879. * Computes an array of distance values which are necessary for rendering dashed lines.
  16880. * For each vertex in the geometry, the method calculates the cumulative length from the
  16881. * current point to the very beginning of the line.
  16882. *
  16883. * @return {Line} A reference to this line.
  16884. */
  16885. computeLineDistances() {
  16886. const geometry = this.geometry;
  16887. // we assume non-indexed geometry
  16888. if ( geometry.index === null ) {
  16889. const positionAttribute = geometry.attributes.position;
  16890. const lineDistances = [ 0 ];
  16891. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16892. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  16893. _vEnd.fromBufferAttribute( positionAttribute, i );
  16894. lineDistances[ i ] = lineDistances[ i - 1 ];
  16895. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  16896. }
  16897. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16898. } else {
  16899. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16900. }
  16901. return this;
  16902. }
  16903. /**
  16904. * Computes intersection points between a casted ray and this line.
  16905. *
  16906. * @param {Raycaster} raycaster - The raycaster.
  16907. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  16908. */
  16909. raycast( raycaster, intersects ) {
  16910. const geometry = this.geometry;
  16911. const matrixWorld = this.matrixWorld;
  16912. const threshold = raycaster.params.Line.threshold;
  16913. const drawRange = geometry.drawRange;
  16914. // Checking boundingSphere distance to ray
  16915. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16916. _sphere$1.copy( geometry.boundingSphere );
  16917. _sphere$1.applyMatrix4( matrixWorld );
  16918. _sphere$1.radius += threshold;
  16919. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  16920. //
  16921. _inverseMatrix$1.copy( matrixWorld ).invert();
  16922. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16923. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16924. const localThresholdSq = localThreshold * localThreshold;
  16925. const step = this.isLineSegments ? 2 : 1;
  16926. const index = geometry.index;
  16927. const attributes = geometry.attributes;
  16928. const positionAttribute = attributes.position;
  16929. if ( index !== null ) {
  16930. const start = Math.max( 0, drawRange.start );
  16931. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  16932. for ( let i = start, l = end - 1; i < l; i += step ) {
  16933. const a = index.getX( i );
  16934. const b = index.getX( i + 1 );
  16935. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  16936. if ( intersect ) {
  16937. intersects.push( intersect );
  16938. }
  16939. }
  16940. if ( this.isLineLoop ) {
  16941. const a = index.getX( end - 1 );
  16942. const b = index.getX( start );
  16943. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  16944. if ( intersect ) {
  16945. intersects.push( intersect );
  16946. }
  16947. }
  16948. } else {
  16949. const start = Math.max( 0, drawRange.start );
  16950. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  16951. for ( let i = start, l = end - 1; i < l; i += step ) {
  16952. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  16953. if ( intersect ) {
  16954. intersects.push( intersect );
  16955. }
  16956. }
  16957. if ( this.isLineLoop ) {
  16958. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  16959. if ( intersect ) {
  16960. intersects.push( intersect );
  16961. }
  16962. }
  16963. }
  16964. }
  16965. /**
  16966. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  16967. * to make sure existing morph targets can influence this 3D object.
  16968. */
  16969. updateMorphTargets() {
  16970. const geometry = this.geometry;
  16971. const morphAttributes = geometry.morphAttributes;
  16972. const keys = Object.keys( morphAttributes );
  16973. if ( keys.length > 0 ) {
  16974. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16975. if ( morphAttribute !== undefined ) {
  16976. this.morphTargetInfluences = [];
  16977. this.morphTargetDictionary = {};
  16978. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16979. const name = morphAttribute[ m ].name || String( m );
  16980. this.morphTargetInfluences.push( 0 );
  16981. this.morphTargetDictionary[ name ] = m;
  16982. }
  16983. }
  16984. }
  16985. }
  16986. }
  16987. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  16988. const positionAttribute = object.geometry.attributes.position;
  16989. _vStart.fromBufferAttribute( positionAttribute, a );
  16990. _vEnd.fromBufferAttribute( positionAttribute, b );
  16991. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  16992. if ( distSq > thresholdSq ) return;
  16993. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  16994. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  16995. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16996. return {
  16997. distance: distance,
  16998. // What do we want? intersection point on the ray or on the segment??
  16999. // point: raycaster.ray.at( distance ),
  17000. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  17001. index: i,
  17002. face: null,
  17003. faceIndex: null,
  17004. barycoord: null,
  17005. object: object
  17006. };
  17007. }
  17008. const _start = /*@__PURE__*/ new Vector3();
  17009. const _end = /*@__PURE__*/ new Vector3();
  17010. /**
  17011. * A series of lines drawn between pairs of vertices.
  17012. *
  17013. * @augments Line
  17014. */
  17015. class LineSegments extends Line {
  17016. /**
  17017. * Constructs a new line segments.
  17018. *
  17019. * @param {BufferGeometry} [geometry] - The line geometry.
  17020. * @param {Material|Array<Material>} [material] - The line material.
  17021. */
  17022. constructor( geometry, material ) {
  17023. super( geometry, material );
  17024. /**
  17025. * This flag can be used for type testing.
  17026. *
  17027. * @type {boolean}
  17028. * @readonly
  17029. * @default true
  17030. */
  17031. this.isLineSegments = true;
  17032. this.type = 'LineSegments';
  17033. }
  17034. computeLineDistances() {
  17035. const geometry = this.geometry;
  17036. // we assume non-indexed geometry
  17037. if ( geometry.index === null ) {
  17038. const positionAttribute = geometry.attributes.position;
  17039. const lineDistances = [];
  17040. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  17041. _start.fromBufferAttribute( positionAttribute, i );
  17042. _end.fromBufferAttribute( positionAttribute, i + 1 );
  17043. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  17044. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  17045. }
  17046. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  17047. } else {
  17048. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  17049. }
  17050. return this;
  17051. }
  17052. }
  17053. /**
  17054. * A continuous line. This is nearly the same as {@link Line} the only difference
  17055. * is that the last vertex is connected with the first vertex in order to close
  17056. * the line to form a loop.
  17057. *
  17058. * @augments Line
  17059. */
  17060. class LineLoop extends Line {
  17061. /**
  17062. * Constructs a new line loop.
  17063. *
  17064. * @param {BufferGeometry} [geometry] - The line geometry.
  17065. * @param {Material|Array<Material>} [material] - The line material.
  17066. */
  17067. constructor( geometry, material ) {
  17068. super( geometry, material );
  17069. /**
  17070. * This flag can be used for type testing.
  17071. *
  17072. * @type {boolean}
  17073. * @readonly
  17074. * @default true
  17075. */
  17076. this.isLineLoop = true;
  17077. this.type = 'LineLoop';
  17078. }
  17079. }
  17080. class PointsMaterial extends Material {
  17081. constructor( parameters ) {
  17082. super();
  17083. this.isPointsMaterial = true;
  17084. this.type = 'PointsMaterial';
  17085. this.color = new Color( 0xffffff );
  17086. this.map = null;
  17087. this.alphaMap = null;
  17088. this.size = 1;
  17089. this.sizeAttenuation = true;
  17090. this.fog = true;
  17091. this.setValues( parameters );
  17092. }
  17093. copy( source ) {
  17094. super.copy( source );
  17095. this.color.copy( source.color );
  17096. this.map = source.map;
  17097. this.alphaMap = source.alphaMap;
  17098. this.size = source.size;
  17099. this.sizeAttenuation = source.sizeAttenuation;
  17100. this.fog = source.fog;
  17101. return this;
  17102. }
  17103. }
  17104. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  17105. const _ray = /*@__PURE__*/ new Ray();
  17106. const _sphere = /*@__PURE__*/ new Sphere();
  17107. const _position$2 = /*@__PURE__*/ new Vector3();
  17108. /**
  17109. * A class for displaying points or point clouds.
  17110. *
  17111. * @augments Object3D
  17112. */
  17113. class Points extends Object3D {
  17114. /**
  17115. * Constructs a new point cloud.
  17116. *
  17117. * @param {BufferGeometry} [geometry] - The points geometry.
  17118. * @param {Material|Array<Material>} [material] - The points material.
  17119. */
  17120. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  17121. super();
  17122. /**
  17123. * This flag can be used for type testing.
  17124. *
  17125. * @type {boolean}
  17126. * @readonly
  17127. * @default true
  17128. */
  17129. this.isPoints = true;
  17130. this.type = 'Points';
  17131. /**
  17132. * The points geometry.
  17133. *
  17134. * @type {BufferGeometry}
  17135. */
  17136. this.geometry = geometry;
  17137. /**
  17138. * The line material.
  17139. *
  17140. * @type {Material|Array<Material>}
  17141. * @default PointsMaterial
  17142. */
  17143. this.material = material;
  17144. /**
  17145. * A dictionary representing the morph targets in the geometry. The key is the
  17146. * morph targets name, the value its attribute index. This member is `undefined`
  17147. * by default and only set when morph targets are detected in the geometry.
  17148. *
  17149. * @type {Object<String,number>|undefined}
  17150. * @default undefined
  17151. */
  17152. this.morphTargetDictionary = undefined;
  17153. /**
  17154. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  17155. * is applied. This member is `undefined` by default and only set when morph targets are
  17156. * detected in the geometry.
  17157. *
  17158. * @type {Array<number>|undefined}
  17159. * @default undefined
  17160. */
  17161. this.morphTargetInfluences = undefined;
  17162. this.updateMorphTargets();
  17163. }
  17164. copy( source, recursive ) {
  17165. super.copy( source, recursive );
  17166. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  17167. this.geometry = source.geometry;
  17168. return this;
  17169. }
  17170. /**
  17171. * Computes intersection points between a casted ray and this point cloud.
  17172. *
  17173. * @param {Raycaster} raycaster - The raycaster.
  17174. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  17175. */
  17176. raycast( raycaster, intersects ) {
  17177. const geometry = this.geometry;
  17178. const matrixWorld = this.matrixWorld;
  17179. const threshold = raycaster.params.Points.threshold;
  17180. const drawRange = geometry.drawRange;
  17181. // Checking boundingSphere distance to ray
  17182. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17183. _sphere.copy( geometry.boundingSphere );
  17184. _sphere.applyMatrix4( matrixWorld );
  17185. _sphere.radius += threshold;
  17186. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  17187. //
  17188. _inverseMatrix.copy( matrixWorld ).invert();
  17189. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  17190. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  17191. const localThresholdSq = localThreshold * localThreshold;
  17192. const index = geometry.index;
  17193. const attributes = geometry.attributes;
  17194. const positionAttribute = attributes.position;
  17195. if ( index !== null ) {
  17196. const start = Math.max( 0, drawRange.start );
  17197. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  17198. for ( let i = start, il = end; i < il; i ++ ) {
  17199. const a = index.getX( i );
  17200. _position$2.fromBufferAttribute( positionAttribute, a );
  17201. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17202. }
  17203. } else {
  17204. const start = Math.max( 0, drawRange.start );
  17205. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  17206. for ( let i = start, l = end; i < l; i ++ ) {
  17207. _position$2.fromBufferAttribute( positionAttribute, i );
  17208. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  17209. }
  17210. }
  17211. }
  17212. /**
  17213. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  17214. * to make sure existing morph targets can influence this 3D object.
  17215. */
  17216. updateMorphTargets() {
  17217. const geometry = this.geometry;
  17218. const morphAttributes = geometry.morphAttributes;
  17219. const keys = Object.keys( morphAttributes );
  17220. if ( keys.length > 0 ) {
  17221. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  17222. if ( morphAttribute !== undefined ) {
  17223. this.morphTargetInfluences = [];
  17224. this.morphTargetDictionary = {};
  17225. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  17226. const name = morphAttribute[ m ].name || String( m );
  17227. this.morphTargetInfluences.push( 0 );
  17228. this.morphTargetDictionary[ name ] = m;
  17229. }
  17230. }
  17231. }
  17232. }
  17233. }
  17234. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  17235. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  17236. if ( rayPointDistanceSq < localThresholdSq ) {
  17237. const intersectPoint = new Vector3();
  17238. _ray.closestPointToPoint( point, intersectPoint );
  17239. intersectPoint.applyMatrix4( matrixWorld );
  17240. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  17241. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17242. intersects.push( {
  17243. distance: distance,
  17244. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  17245. point: intersectPoint,
  17246. index: index,
  17247. face: null,
  17248. faceIndex: null,
  17249. barycoord: null,
  17250. object: object
  17251. } );
  17252. }
  17253. }
  17254. class VideoTexture extends Texture {
  17255. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17256. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17257. this.isVideoTexture = true;
  17258. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17259. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17260. this.generateMipmaps = false;
  17261. const scope = this;
  17262. function updateVideo() {
  17263. scope.needsUpdate = true;
  17264. video.requestVideoFrameCallback( updateVideo );
  17265. }
  17266. if ( 'requestVideoFrameCallback' in video ) {
  17267. video.requestVideoFrameCallback( updateVideo );
  17268. }
  17269. }
  17270. clone() {
  17271. return new this.constructor( this.image ).copy( this );
  17272. }
  17273. update() {
  17274. const video = this.image;
  17275. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  17276. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  17277. this.needsUpdate = true;
  17278. }
  17279. }
  17280. }
  17281. class VideoFrameTexture extends VideoTexture {
  17282. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17283. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17284. this.isVideoFrameTexture = true;
  17285. }
  17286. update() {
  17287. // overwrites `VideoTexture.update()` with an empty method since
  17288. // this type of texture is updated via `setFrame()`.
  17289. }
  17290. clone() {
  17291. return new this.constructor().copy( this ); // restoring Texture.clone()
  17292. }
  17293. setFrame( frame ) {
  17294. this.image = frame;
  17295. this.needsUpdate = true;
  17296. }
  17297. }
  17298. class FramebufferTexture extends Texture {
  17299. constructor( width, height ) {
  17300. super( { width, height } );
  17301. this.isFramebufferTexture = true;
  17302. this.magFilter = NearestFilter;
  17303. this.minFilter = NearestFilter;
  17304. this.generateMipmaps = false;
  17305. this.needsUpdate = true;
  17306. }
  17307. }
  17308. class CompressedTexture extends Texture {
  17309. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  17310. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  17311. this.isCompressedTexture = true;
  17312. this.image = { width: width, height: height };
  17313. this.mipmaps = mipmaps;
  17314. // no flipping for cube textures
  17315. // (also flipping doesn't work for compressed textures )
  17316. this.flipY = false;
  17317. // can't generate mipmaps for compressed textures
  17318. // mips must be embedded in DDS files
  17319. this.generateMipmaps = false;
  17320. }
  17321. }
  17322. class CompressedArrayTexture extends CompressedTexture {
  17323. constructor( mipmaps, width, height, depth, format, type ) {
  17324. super( mipmaps, width, height, format, type );
  17325. this.isCompressedArrayTexture = true;
  17326. this.image.depth = depth;
  17327. this.wrapR = ClampToEdgeWrapping;
  17328. this.layerUpdates = new Set();
  17329. }
  17330. addLayerUpdate( layerIndex ) {
  17331. this.layerUpdates.add( layerIndex );
  17332. }
  17333. clearLayerUpdates() {
  17334. this.layerUpdates.clear();
  17335. }
  17336. }
  17337. class CompressedCubeTexture extends CompressedTexture {
  17338. constructor( images, format, type ) {
  17339. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  17340. this.isCompressedCubeTexture = true;
  17341. this.isCubeTexture = true;
  17342. this.image = images;
  17343. }
  17344. }
  17345. class CanvasTexture extends Texture {
  17346. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17347. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17348. this.isCanvasTexture = true;
  17349. this.needsUpdate = true;
  17350. }
  17351. }
  17352. class DepthTexture extends Texture {
  17353. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  17354. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17355. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17356. }
  17357. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  17358. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  17359. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17360. this.isDepthTexture = true;
  17361. this.image = { width: width, height: height };
  17362. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17363. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17364. this.flipY = false;
  17365. this.generateMipmaps = false;
  17366. this.compareFunction = null;
  17367. }
  17368. copy( source ) {
  17369. super.copy( source );
  17370. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  17371. this.compareFunction = source.compareFunction;
  17372. return this;
  17373. }
  17374. toJSON( meta ) {
  17375. const data = super.toJSON( meta );
  17376. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  17377. return data;
  17378. }
  17379. }
  17380. /**
  17381. * An abstract base class for creating an analytic curve object that contains methods
  17382. * for interpolation.
  17383. *
  17384. * @abstract
  17385. */
  17386. class Curve {
  17387. /**
  17388. * Constructs a new curve.
  17389. */
  17390. constructor() {
  17391. /**
  17392. * The type property is used for detecting the object type
  17393. * in context of serialization/deserialization.
  17394. *
  17395. * @type {string}
  17396. * @readonly
  17397. */
  17398. this.type = 'Curve';
  17399. /**
  17400. * This value determines the amount of divisions when calculating the
  17401. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  17402. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  17403. * recommended to increase the value of this property if the curve is very large.
  17404. *
  17405. * @type {number}
  17406. * @default 200
  17407. */
  17408. this.arcLengthDivisions = 200;
  17409. /**
  17410. * Must be set to `true` if the curve parameters have changed.
  17411. *
  17412. * @type {boolean}
  17413. * @default false
  17414. */
  17415. this.needsUpdate = false;
  17416. /**
  17417. * An internal cache that holds precomputed curve length values.
  17418. *
  17419. * @private
  17420. * @type {?Array<number>}
  17421. * @default null
  17422. */
  17423. this.cacheArcLengths = null;
  17424. }
  17425. /**
  17426. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  17427. * for the given interpolation factor.
  17428. *
  17429. * @abstract
  17430. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17431. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17432. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  17433. */
  17434. getPoint( /* t, optionalTarget */ ) {
  17435. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  17436. }
  17437. /**
  17438. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  17439. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  17440. * of the curve which equidistant samples.
  17441. *
  17442. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17443. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17444. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  17445. */
  17446. getPointAt( u, optionalTarget ) {
  17447. const t = this.getUtoTmapping( u );
  17448. return this.getPoint( t, optionalTarget );
  17449. }
  17450. /**
  17451. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  17452. * the curve shape.
  17453. *
  17454. * @param {number} [divisions=5] - The number of divisions.
  17455. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  17456. */
  17457. getPoints( divisions = 5 ) {
  17458. const points = [];
  17459. for ( let d = 0; d <= divisions; d ++ ) {
  17460. points.push( this.getPoint( d / divisions ) );
  17461. }
  17462. return points;
  17463. }
  17464. // Get sequence of points using getPointAt( u )
  17465. /**
  17466. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  17467. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  17468. * curve.
  17469. *
  17470. * @param {number} [divisions=5] - The number of divisions.
  17471. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  17472. */
  17473. getSpacedPoints( divisions = 5 ) {
  17474. const points = [];
  17475. for ( let d = 0; d <= divisions; d ++ ) {
  17476. points.push( this.getPointAt( d / divisions ) );
  17477. }
  17478. return points;
  17479. }
  17480. /**
  17481. * Returns the total arc length of the curve.
  17482. *
  17483. * @return {number} The length of the curve.
  17484. */
  17485. getLength() {
  17486. const lengths = this.getLengths();
  17487. return lengths[ lengths.length - 1 ];
  17488. }
  17489. /**
  17490. * Returns an array of cumulative segment lengths of the curve.
  17491. *
  17492. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  17493. * @return {Array<number>} An array holding the cumulative segment lengths.
  17494. */
  17495. getLengths( divisions = this.arcLengthDivisions ) {
  17496. if ( this.cacheArcLengths &&
  17497. ( this.cacheArcLengths.length === divisions + 1 ) &&
  17498. ! this.needsUpdate ) {
  17499. return this.cacheArcLengths;
  17500. }
  17501. this.needsUpdate = false;
  17502. const cache = [];
  17503. let current, last = this.getPoint( 0 );
  17504. let sum = 0;
  17505. cache.push( 0 );
  17506. for ( let p = 1; p <= divisions; p ++ ) {
  17507. current = this.getPoint( p / divisions );
  17508. sum += current.distanceTo( last );
  17509. cache.push( sum );
  17510. last = current;
  17511. }
  17512. this.cacheArcLengths = cache;
  17513. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  17514. }
  17515. /**
  17516. * Update the cumulative segment distance cache. The method must be called
  17517. * every time curve parameters are changed. If an updated curve is part of a
  17518. * composed curve like {@link CurvePath}, this method must be called on the
  17519. * composed curve, too.
  17520. */
  17521. updateArcLengths() {
  17522. this.needsUpdate = true;
  17523. this.getLengths();
  17524. }
  17525. /**
  17526. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  17527. * interpolation factor in the same range that can be ued to sample equidistant points
  17528. * from a curve.
  17529. *
  17530. * @param {number} u - The interpolation factor.
  17531. * @param {?number} distance - An optional distance on the curve.
  17532. * @return {number} The updated interpolation factor.
  17533. */
  17534. getUtoTmapping( u, distance = null ) {
  17535. const arcLengths = this.getLengths();
  17536. let i = 0;
  17537. const il = arcLengths.length;
  17538. let targetArcLength; // The targeted u distance value to get
  17539. if ( distance ) {
  17540. targetArcLength = distance;
  17541. } else {
  17542. targetArcLength = u * arcLengths[ il - 1 ];
  17543. }
  17544. // binary search for the index with largest value smaller than target u distance
  17545. let low = 0, high = il - 1, comparison;
  17546. while ( low <= high ) {
  17547. 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
  17548. comparison = arcLengths[ i ] - targetArcLength;
  17549. if ( comparison < 0 ) {
  17550. low = i + 1;
  17551. } else if ( comparison > 0 ) {
  17552. high = i - 1;
  17553. } else {
  17554. high = i;
  17555. break;
  17556. // DONE
  17557. }
  17558. }
  17559. i = high;
  17560. if ( arcLengths[ i ] === targetArcLength ) {
  17561. return i / ( il - 1 );
  17562. }
  17563. // we could get finer grain at lengths, or use simple interpolation between two points
  17564. const lengthBefore = arcLengths[ i ];
  17565. const lengthAfter = arcLengths[ i + 1 ];
  17566. const segmentLength = lengthAfter - lengthBefore;
  17567. // determine where we are between the 'before' and 'after' points
  17568. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17569. // add that fractional amount to t
  17570. const t = ( i + segmentFraction ) / ( il - 1 );
  17571. return t;
  17572. }
  17573. /**
  17574. * Returns a unit vector tangent for the given interpolation factor.
  17575. * If the derived curve does not implement its tangent derivation,
  17576. * two points a small delta apart will be used to find its gradient
  17577. * which seems to give a reasonable approximation.
  17578. *
  17579. * @param {number} t - The interpolation factor.
  17580. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17581. * @return {(Vector2|Vector3)} The tangent vector.
  17582. */
  17583. getTangent( t, optionalTarget ) {
  17584. const delta = 0.0001;
  17585. let t1 = t - delta;
  17586. let t2 = t + delta;
  17587. // Capping in case of danger
  17588. if ( t1 < 0 ) t1 = 0;
  17589. if ( t2 > 1 ) t2 = 1;
  17590. const pt1 = this.getPoint( t1 );
  17591. const pt2 = this.getPoint( t2 );
  17592. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  17593. tangent.copy( pt2 ).sub( pt1 ).normalize();
  17594. return tangent;
  17595. }
  17596. /**
  17597. * Same as {@link Curve#getTangent} but with equidistant samples.
  17598. *
  17599. * @param {number} u - The interpolation factor.
  17600. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  17601. * @return {(Vector2|Vector3)} The tangent vector.
  17602. * @see {@link Curve#getPointAt}
  17603. */
  17604. getTangentAt( u, optionalTarget ) {
  17605. const t = this.getUtoTmapping( u );
  17606. return this.getTangent( t, optionalTarget );
  17607. }
  17608. /**
  17609. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  17610. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  17611. *
  17612. * @param {number} segments - The number of segments.
  17613. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  17614. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  17615. */
  17616. computeFrenetFrames( segments, closed = false ) {
  17617. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  17618. const normal = new Vector3();
  17619. const tangents = [];
  17620. const normals = [];
  17621. const binormals = [];
  17622. const vec = new Vector3();
  17623. const mat = new Matrix4();
  17624. // compute the tangent vectors for each segment on the curve
  17625. for ( let i = 0; i <= segments; i ++ ) {
  17626. const u = i / segments;
  17627. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  17628. }
  17629. // select an initial normal vector perpendicular to the first tangent vector,
  17630. // and in the direction of the minimum tangent xyz component
  17631. normals[ 0 ] = new Vector3();
  17632. binormals[ 0 ] = new Vector3();
  17633. let min = Number.MAX_VALUE;
  17634. const tx = Math.abs( tangents[ 0 ].x );
  17635. const ty = Math.abs( tangents[ 0 ].y );
  17636. const tz = Math.abs( tangents[ 0 ].z );
  17637. if ( tx <= min ) {
  17638. min = tx;
  17639. normal.set( 1, 0, 0 );
  17640. }
  17641. if ( ty <= min ) {
  17642. min = ty;
  17643. normal.set( 0, 1, 0 );
  17644. }
  17645. if ( tz <= min ) {
  17646. normal.set( 0, 0, 1 );
  17647. }
  17648. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  17649. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  17650. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  17651. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  17652. for ( let i = 1; i <= segments; i ++ ) {
  17653. normals[ i ] = normals[ i - 1 ].clone();
  17654. binormals[ i ] = binormals[ i - 1 ].clone();
  17655. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  17656. if ( vec.length() > Number.EPSILON ) {
  17657. vec.normalize();
  17658. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  17659. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  17660. }
  17661. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  17662. }
  17663. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  17664. if ( closed === true ) {
  17665. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  17666. theta /= segments;
  17667. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  17668. theta = - theta;
  17669. }
  17670. for ( let i = 1; i <= segments; i ++ ) {
  17671. // twist a little...
  17672. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  17673. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  17674. }
  17675. }
  17676. return {
  17677. tangents: tangents,
  17678. normals: normals,
  17679. binormals: binormals
  17680. };
  17681. }
  17682. /**
  17683. * Returns a new curve with copied values from this instance.
  17684. *
  17685. * @return {Curve} A clone of this instance.
  17686. */
  17687. clone() {
  17688. return new this.constructor().copy( this );
  17689. }
  17690. /**
  17691. * Copies the values of the given curve to this instance.
  17692. *
  17693. * @param {Curve} source - The curve to copy.
  17694. * @return {Curve} A reference to this curve.
  17695. */
  17696. copy( source ) {
  17697. this.arcLengthDivisions = source.arcLengthDivisions;
  17698. return this;
  17699. }
  17700. /**
  17701. * Serializes the curve into JSON.
  17702. *
  17703. * @return {Object} A JSON object representing the serialized curve.
  17704. * @see {@link ObjectLoader#parse}
  17705. */
  17706. toJSON() {
  17707. const data = {
  17708. metadata: {
  17709. version: 4.6,
  17710. type: 'Curve',
  17711. generator: 'Curve.toJSON'
  17712. }
  17713. };
  17714. data.arcLengthDivisions = this.arcLengthDivisions;
  17715. data.type = this.type;
  17716. return data;
  17717. }
  17718. /**
  17719. * Deserializes the curve from the given JSON.
  17720. *
  17721. * @param {Object} json - The JSON holding the serialized curve.
  17722. * @return {Curve} A reference to this curve.
  17723. */
  17724. fromJSON( json ) {
  17725. this.arcLengthDivisions = json.arcLengthDivisions;
  17726. return this;
  17727. }
  17728. }
  17729. /**
  17730. * A curve representing an ellipse.
  17731. *
  17732. * ```js
  17733. * const curve = new THREE.EllipseCurve(
  17734. * 0, 0,
  17735. * 10, 10,
  17736. * 0, 2 * Math.PI,
  17737. * false,
  17738. * 0
  17739. * );
  17740. *
  17741. * const points = curve.getPoints( 50 );
  17742. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  17743. *
  17744. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  17745. *
  17746. * // Create the final object to add to the scene
  17747. * const ellipse = new THREE.Line( geometry, material );
  17748. * ```
  17749. *
  17750. * @augments Curve
  17751. */
  17752. class EllipseCurve extends Curve {
  17753. /**
  17754. * Constructs a new ellipse curve.
  17755. *
  17756. * @param {number} [aX=0] - The X center of the ellipse.
  17757. * @param {number} [aY=0] - The Y center of the ellipse.
  17758. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  17759. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  17760. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  17761. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  17762. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  17763. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  17764. */
  17765. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  17766. super();
  17767. /**
  17768. * This flag can be used for type testing.
  17769. *
  17770. * @type {boolean}
  17771. * @readonly
  17772. * @default true
  17773. */
  17774. this.isEllipseCurve = true;
  17775. this.type = 'EllipseCurve';
  17776. /**
  17777. * The X center of the ellipse.
  17778. *
  17779. * @type {number}
  17780. * @default 0
  17781. */
  17782. this.aX = aX;
  17783. /**
  17784. * The Y center of the ellipse.
  17785. *
  17786. * @type {number}
  17787. * @default 0
  17788. */
  17789. this.aY = aY;
  17790. /**
  17791. * The radius of the ellipse in the x direction.
  17792. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  17793. *
  17794. * @type {number}
  17795. * @default 1
  17796. */
  17797. this.xRadius = xRadius;
  17798. /**
  17799. * The radius of the ellipse in the y direction.
  17800. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  17801. *
  17802. * @type {number}
  17803. * @default 1
  17804. */
  17805. this.yRadius = yRadius;
  17806. /**
  17807. * The start angle of the curve in radians starting from the positive X axis.
  17808. *
  17809. * @type {number}
  17810. * @default 0
  17811. */
  17812. this.aStartAngle = aStartAngle;
  17813. /**
  17814. * The end angle of the curve in radians starting from the positive X axis.
  17815. *
  17816. * @type {number}
  17817. * @default Math.PI*2
  17818. */
  17819. this.aEndAngle = aEndAngle;
  17820. /**
  17821. * Whether the ellipse is drawn clockwise or not.
  17822. *
  17823. * @type {boolean}
  17824. * @default false
  17825. */
  17826. this.aClockwise = aClockwise;
  17827. /**
  17828. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  17829. *
  17830. * @type {number}
  17831. * @default 0
  17832. */
  17833. this.aRotation = aRotation;
  17834. }
  17835. /**
  17836. * Returns a point on the curve.
  17837. *
  17838. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  17839. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  17840. * @return {Vector2} The position on the curve.
  17841. */
  17842. getPoint( t, optionalTarget = new Vector2() ) {
  17843. const point = optionalTarget;
  17844. const twoPi = Math.PI * 2;
  17845. let deltaAngle = this.aEndAngle - this.aStartAngle;
  17846. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  17847. // ensures that deltaAngle is 0 .. 2 PI
  17848. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  17849. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  17850. if ( deltaAngle < Number.EPSILON ) {
  17851. if ( samePoints ) {
  17852. deltaAngle = 0;
  17853. } else {
  17854. deltaAngle = twoPi;
  17855. }
  17856. }
  17857. if ( this.aClockwise === true && ! samePoints ) {
  17858. if ( deltaAngle === twoPi ) {
  17859. deltaAngle = - twoPi;
  17860. } else {
  17861. deltaAngle = deltaAngle - twoPi;
  17862. }
  17863. }
  17864. const angle = this.aStartAngle + t * deltaAngle;
  17865. let x = this.aX + this.xRadius * Math.cos( angle );
  17866. let y = this.aY + this.yRadius * Math.sin( angle );
  17867. if ( this.aRotation !== 0 ) {
  17868. const cos = Math.cos( this.aRotation );
  17869. const sin = Math.sin( this.aRotation );
  17870. const tx = x - this.aX;
  17871. const ty = y - this.aY;
  17872. // Rotate the point about the center of the ellipse.
  17873. x = tx * cos - ty * sin + this.aX;
  17874. y = tx * sin + ty * cos + this.aY;
  17875. }
  17876. return point.set( x, y );
  17877. }
  17878. copy( source ) {
  17879. super.copy( source );
  17880. this.aX = source.aX;
  17881. this.aY = source.aY;
  17882. this.xRadius = source.xRadius;
  17883. this.yRadius = source.yRadius;
  17884. this.aStartAngle = source.aStartAngle;
  17885. this.aEndAngle = source.aEndAngle;
  17886. this.aClockwise = source.aClockwise;
  17887. this.aRotation = source.aRotation;
  17888. return this;
  17889. }
  17890. toJSON() {
  17891. const data = super.toJSON();
  17892. data.aX = this.aX;
  17893. data.aY = this.aY;
  17894. data.xRadius = this.xRadius;
  17895. data.yRadius = this.yRadius;
  17896. data.aStartAngle = this.aStartAngle;
  17897. data.aEndAngle = this.aEndAngle;
  17898. data.aClockwise = this.aClockwise;
  17899. data.aRotation = this.aRotation;
  17900. return data;
  17901. }
  17902. fromJSON( json ) {
  17903. super.fromJSON( json );
  17904. this.aX = json.aX;
  17905. this.aY = json.aY;
  17906. this.xRadius = json.xRadius;
  17907. this.yRadius = json.yRadius;
  17908. this.aStartAngle = json.aStartAngle;
  17909. this.aEndAngle = json.aEndAngle;
  17910. this.aClockwise = json.aClockwise;
  17911. this.aRotation = json.aRotation;
  17912. return this;
  17913. }
  17914. }
  17915. /**
  17916. * A curve representing an arc.
  17917. *
  17918. * @augments EllipseCurve
  17919. */
  17920. class ArcCurve extends EllipseCurve {
  17921. /**
  17922. * Constructs a new arc curve.
  17923. *
  17924. * @param {number} [aX=0] - The X center of the ellipse.
  17925. * @param {number} [aY=0] - The Y center of the ellipse.
  17926. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  17927. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  17928. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  17929. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  17930. */
  17931. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17932. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17933. /**
  17934. * This flag can be used for type testing.
  17935. *
  17936. * @type {boolean}
  17937. * @readonly
  17938. * @default true
  17939. */
  17940. this.isArcCurve = true;
  17941. this.type = 'ArcCurve';
  17942. }
  17943. }
  17944. function CubicPoly() {
  17945. /**
  17946. * Centripetal CatmullRom Curve - which is useful for avoiding
  17947. * cusps and self-intersections in non-uniform catmull rom curves.
  17948. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  17949. *
  17950. * curve.type accepts centripetal(default), chordal and catmullrom
  17951. * curve.tension is used for catmullrom which defaults to 0.5
  17952. */
  17953. /*
  17954. Based on an optimized c++ solution in
  17955. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  17956. - http://ideone.com/NoEbVM
  17957. This CubicPoly class could be used for reusing some variables and calculations,
  17958. but for three.js curve use, it could be possible inlined and flatten into a single function call
  17959. which can be placed in CurveUtils.
  17960. */
  17961. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  17962. /*
  17963. * Compute coefficients for a cubic polynomial
  17964. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  17965. * such that
  17966. * p(0) = x0, p(1) = x1
  17967. * and
  17968. * p'(0) = t0, p'(1) = t1.
  17969. */
  17970. function init( x0, x1, t0, t1 ) {
  17971. c0 = x0;
  17972. c1 = t0;
  17973. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  17974. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  17975. }
  17976. return {
  17977. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  17978. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  17979. },
  17980. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  17981. // compute tangents when parameterized in [t1,t2]
  17982. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  17983. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  17984. // rescale tangents for parametrization in [0,1]
  17985. t1 *= dt1;
  17986. t2 *= dt1;
  17987. init( x1, x2, t1, t2 );
  17988. },
  17989. calc: function ( t ) {
  17990. const t2 = t * t;
  17991. const t3 = t2 * t;
  17992. return c0 + c1 * t + c2 * t2 + c3 * t3;
  17993. }
  17994. };
  17995. }
  17996. //
  17997. const tmp = /*@__PURE__*/ new Vector3();
  17998. const px = /*@__PURE__*/ new CubicPoly();
  17999. const py = /*@__PURE__*/ new CubicPoly();
  18000. const pz = /*@__PURE__*/ new CubicPoly();
  18001. /**
  18002. * A curve representing a Catmull-Rom spline.
  18003. *
  18004. * ```js
  18005. * //Create a closed wavey loop
  18006. * const curve = new THREE.CatmullRomCurve3( [
  18007. * new THREE.Vector3( -10, 0, 10 ),
  18008. * new THREE.Vector3( -5, 5, 5 ),
  18009. * new THREE.Vector3( 0, 0, 0 ),
  18010. * new THREE.Vector3( 5, -5, 5 ),
  18011. * new THREE.Vector3( 10, 0, 10 )
  18012. * ] );
  18013. *
  18014. * const points = curve.getPoints( 50 );
  18015. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18016. *
  18017. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18018. *
  18019. * // Create the final object to add to the scene
  18020. * const curveObject = new THREE.Line( geometry, material );
  18021. * ```
  18022. *
  18023. * @augments Curve
  18024. */
  18025. class CatmullRomCurve3 extends Curve {
  18026. /**
  18027. * Constructs a new Catmull-Rom curve.
  18028. *
  18029. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  18030. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  18031. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  18032. * @param {number} [tension=0.5] - Tension of the curve.
  18033. */
  18034. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18035. super();
  18036. /**
  18037. * This flag can be used for type testing.
  18038. *
  18039. * @type {boolean}
  18040. * @readonly
  18041. * @default true
  18042. */
  18043. this.isCatmullRomCurve3 = true;
  18044. this.type = 'CatmullRomCurve3';
  18045. /**
  18046. * An array of 3D points defining the curve.
  18047. *
  18048. * @type {Array<Vector3>}
  18049. */
  18050. this.points = points;
  18051. /**
  18052. * Whether the curve is closed or not.
  18053. *
  18054. * @type {boolean}
  18055. * @default false
  18056. */
  18057. this.closed = closed;
  18058. /**
  18059. * The curve type.
  18060. *
  18061. * @type {('centripetal'|'chordal'|'catmullrom')}
  18062. * @default 'centripetal'
  18063. */
  18064. this.curveType = curveType;
  18065. /**
  18066. * Tension of the curve.
  18067. *
  18068. * @type {number}
  18069. * @default 0.5
  18070. */
  18071. this.tension = tension;
  18072. }
  18073. /**
  18074. * Returns a point on the curve.
  18075. *
  18076. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18077. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18078. * @return {Vector3} The position on the curve.
  18079. */
  18080. getPoint( t, optionalTarget = new Vector3() ) {
  18081. const point = optionalTarget;
  18082. const points = this.points;
  18083. const l = points.length;
  18084. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18085. let intPoint = Math.floor( p );
  18086. let weight = p - intPoint;
  18087. if ( this.closed ) {
  18088. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18089. } else if ( weight === 0 && intPoint === l - 1 ) {
  18090. intPoint = l - 2;
  18091. weight = 1;
  18092. }
  18093. let p0, p3; // 4 points (p1 & p2 defined below)
  18094. if ( this.closed || intPoint > 0 ) {
  18095. p0 = points[ ( intPoint - 1 ) % l ];
  18096. } else {
  18097. // extrapolate first point
  18098. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18099. p0 = tmp;
  18100. }
  18101. const p1 = points[ intPoint % l ];
  18102. const p2 = points[ ( intPoint + 1 ) % l ];
  18103. if ( this.closed || intPoint + 2 < l ) {
  18104. p3 = points[ ( intPoint + 2 ) % l ];
  18105. } else {
  18106. // extrapolate last point
  18107. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18108. p3 = tmp;
  18109. }
  18110. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18111. // init Centripetal / Chordal Catmull-Rom
  18112. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18113. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18114. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18115. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18116. // safety check for repeated points
  18117. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18118. if ( dt0 < 1e-4 ) dt0 = dt1;
  18119. if ( dt2 < 1e-4 ) dt2 = dt1;
  18120. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18121. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18122. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18123. } else if ( this.curveType === 'catmullrom' ) {
  18124. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18125. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18126. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18127. }
  18128. point.set(
  18129. px.calc( weight ),
  18130. py.calc( weight ),
  18131. pz.calc( weight )
  18132. );
  18133. return point;
  18134. }
  18135. copy( source ) {
  18136. super.copy( source );
  18137. this.points = [];
  18138. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18139. const point = source.points[ i ];
  18140. this.points.push( point.clone() );
  18141. }
  18142. this.closed = source.closed;
  18143. this.curveType = source.curveType;
  18144. this.tension = source.tension;
  18145. return this;
  18146. }
  18147. toJSON() {
  18148. const data = super.toJSON();
  18149. data.points = [];
  18150. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18151. const point = this.points[ i ];
  18152. data.points.push( point.toArray() );
  18153. }
  18154. data.closed = this.closed;
  18155. data.curveType = this.curveType;
  18156. data.tension = this.tension;
  18157. return data;
  18158. }
  18159. fromJSON( json ) {
  18160. super.fromJSON( json );
  18161. this.points = [];
  18162. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18163. const point = json.points[ i ];
  18164. this.points.push( new Vector3().fromArray( point ) );
  18165. }
  18166. this.closed = json.closed;
  18167. this.curveType = json.curveType;
  18168. this.tension = json.tension;
  18169. return this;
  18170. }
  18171. }
  18172. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18173. /**
  18174. * Computes a point on a Catmull-Rom spline.
  18175. *
  18176. * @param {number} t - The interpolation factor.
  18177. * @param {number} p0 - The first control point.
  18178. * @param {number} p1 - The second control point.
  18179. * @param {number} p2 - The third control point.
  18180. * @param {number} p3 - The fourth control point.
  18181. * @return {number} The calculated point on a Catmull-Rom spline.
  18182. */
  18183. function CatmullRom( t, p0, p1, p2, p3 ) {
  18184. const v0 = ( p2 - p0 ) * 0.5;
  18185. const v1 = ( p3 - p1 ) * 0.5;
  18186. const t2 = t * t;
  18187. const t3 = t * t2;
  18188. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18189. }
  18190. //
  18191. function QuadraticBezierP0( t, p ) {
  18192. const k = 1 - t;
  18193. return k * k * p;
  18194. }
  18195. function QuadraticBezierP1( t, p ) {
  18196. return 2 * ( 1 - t ) * t * p;
  18197. }
  18198. function QuadraticBezierP2( t, p ) {
  18199. return t * t * p;
  18200. }
  18201. /**
  18202. * Computes a point on a Quadratic Bezier curve.
  18203. *
  18204. * @param {number} t - The interpolation factor.
  18205. * @param {number} p0 - The first control point.
  18206. * @param {number} p1 - The second control point.
  18207. * @param {number} p2 - The third control point.
  18208. * @return {number} The calculated point on a Quadratic Bezier curve.
  18209. */
  18210. function QuadraticBezier( t, p0, p1, p2 ) {
  18211. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18212. QuadraticBezierP2( t, p2 );
  18213. }
  18214. //
  18215. function CubicBezierP0( t, p ) {
  18216. const k = 1 - t;
  18217. return k * k * k * p;
  18218. }
  18219. function CubicBezierP1( t, p ) {
  18220. const k = 1 - t;
  18221. return 3 * k * k * t * p;
  18222. }
  18223. function CubicBezierP2( t, p ) {
  18224. return 3 * ( 1 - t ) * t * t * p;
  18225. }
  18226. function CubicBezierP3( t, p ) {
  18227. return t * t * t * p;
  18228. }
  18229. /**
  18230. * Computes a point on a Cubic Bezier curve.
  18231. *
  18232. * @param {number} t - The interpolation factor.
  18233. * @param {number} p0 - The first control point.
  18234. * @param {number} p1 - The second control point.
  18235. * @param {number} p2 - The third control point.
  18236. * @param {number} p3 - The fourth control point.
  18237. * @return {number} The calculated point on a Cubic Bezier curve.
  18238. */
  18239. function CubicBezier( t, p0, p1, p2, p3 ) {
  18240. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18241. CubicBezierP3( t, p3 );
  18242. }
  18243. /**
  18244. * A curve representing a 2D Cubic Bezier curve.
  18245. *
  18246. * ```js
  18247. * const curve = new THREE.CubicBezierCurve(
  18248. * new THREE.Vector2( - 0, 0 ),
  18249. * new THREE.Vector2( - 5, 15 ),
  18250. * new THREE.Vector2( 20, 15 ),
  18251. * new THREE.Vector2( 10, 0 )
  18252. * );
  18253. *
  18254. * const points = curve.getPoints( 50 );
  18255. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18256. *
  18257. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18258. *
  18259. * // Create the final object to add to the scene
  18260. * const curveObject = new THREE.Line( geometry, material );
  18261. * ```
  18262. *
  18263. * @augments Curve
  18264. */
  18265. class CubicBezierCurve extends Curve {
  18266. /**
  18267. * Constructs a new Cubic Bezier curve.
  18268. *
  18269. * @param {Vector2} [v0] - The start point.
  18270. * @param {Vector2} [v1] - The first control point.
  18271. * @param {Vector2} [v2] - The second control point.
  18272. * @param {Vector2} [v3] - The end point.
  18273. */
  18274. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18275. super();
  18276. /**
  18277. * This flag can be used for type testing.
  18278. *
  18279. * @type {boolean}
  18280. * @readonly
  18281. * @default true
  18282. */
  18283. this.isCubicBezierCurve = true;
  18284. this.type = 'CubicBezierCurve';
  18285. /**
  18286. * The start point.
  18287. *
  18288. * @type {Vector2}
  18289. */
  18290. this.v0 = v0;
  18291. /**
  18292. * The first control point.
  18293. *
  18294. * @type {Vector2}
  18295. */
  18296. this.v1 = v1;
  18297. /**
  18298. * The second control point.
  18299. *
  18300. * @type {Vector2}
  18301. */
  18302. this.v2 = v2;
  18303. /**
  18304. * The end point.
  18305. *
  18306. * @type {Vector2}
  18307. */
  18308. this.v3 = v3;
  18309. }
  18310. /**
  18311. * Returns a point on the curve.
  18312. *
  18313. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18314. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18315. * @return {Vector2} The position on the curve.
  18316. */
  18317. getPoint( t, optionalTarget = new Vector2() ) {
  18318. const point = optionalTarget;
  18319. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18320. point.set(
  18321. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18322. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18323. );
  18324. return point;
  18325. }
  18326. copy( source ) {
  18327. super.copy( source );
  18328. this.v0.copy( source.v0 );
  18329. this.v1.copy( source.v1 );
  18330. this.v2.copy( source.v2 );
  18331. this.v3.copy( source.v3 );
  18332. return this;
  18333. }
  18334. toJSON() {
  18335. const data = super.toJSON();
  18336. data.v0 = this.v0.toArray();
  18337. data.v1 = this.v1.toArray();
  18338. data.v2 = this.v2.toArray();
  18339. data.v3 = this.v3.toArray();
  18340. return data;
  18341. }
  18342. fromJSON( json ) {
  18343. super.fromJSON( json );
  18344. this.v0.fromArray( json.v0 );
  18345. this.v1.fromArray( json.v1 );
  18346. this.v2.fromArray( json.v2 );
  18347. this.v3.fromArray( json.v3 );
  18348. return this;
  18349. }
  18350. }
  18351. /**
  18352. * A curve representing a 3D Cubic Bezier curve.
  18353. *
  18354. * @augments Curve
  18355. */
  18356. class CubicBezierCurve3 extends Curve {
  18357. /**
  18358. * Constructs a new Cubic Bezier curve.
  18359. *
  18360. * @param {Vector3} [v0] - The start point.
  18361. * @param {Vector3} [v1] - The first control point.
  18362. * @param {Vector3} [v2] - The second control point.
  18363. * @param {Vector3} [v3] - The end point.
  18364. */
  18365. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18366. super();
  18367. /**
  18368. * This flag can be used for type testing.
  18369. *
  18370. * @type {boolean}
  18371. * @readonly
  18372. * @default true
  18373. */
  18374. this.isCubicBezierCurve3 = true;
  18375. this.type = 'CubicBezierCurve3';
  18376. /**
  18377. * The start point.
  18378. *
  18379. * @type {Vector3}
  18380. */
  18381. this.v0 = v0;
  18382. /**
  18383. * The first control point.
  18384. *
  18385. * @type {Vector3}
  18386. */
  18387. this.v1 = v1;
  18388. /**
  18389. * The second control point.
  18390. *
  18391. * @type {Vector3}
  18392. */
  18393. this.v2 = v2;
  18394. /**
  18395. * The end point.
  18396. *
  18397. * @type {Vector3}
  18398. */
  18399. this.v3 = v3;
  18400. }
  18401. /**
  18402. * Returns a point on the curve.
  18403. *
  18404. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18405. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18406. * @return {Vector3} The position on the curve.
  18407. */
  18408. getPoint( t, optionalTarget = new Vector3() ) {
  18409. const point = optionalTarget;
  18410. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18411. point.set(
  18412. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18413. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18414. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18415. );
  18416. return point;
  18417. }
  18418. copy( source ) {
  18419. super.copy( source );
  18420. this.v0.copy( source.v0 );
  18421. this.v1.copy( source.v1 );
  18422. this.v2.copy( source.v2 );
  18423. this.v3.copy( source.v3 );
  18424. return this;
  18425. }
  18426. toJSON() {
  18427. const data = super.toJSON();
  18428. data.v0 = this.v0.toArray();
  18429. data.v1 = this.v1.toArray();
  18430. data.v2 = this.v2.toArray();
  18431. data.v3 = this.v3.toArray();
  18432. return data;
  18433. }
  18434. fromJSON( json ) {
  18435. super.fromJSON( json );
  18436. this.v0.fromArray( json.v0 );
  18437. this.v1.fromArray( json.v1 );
  18438. this.v2.fromArray( json.v2 );
  18439. this.v3.fromArray( json.v3 );
  18440. return this;
  18441. }
  18442. }
  18443. /**
  18444. * A curve representing a 2D line segment.
  18445. *
  18446. * @augments Curve
  18447. */
  18448. class LineCurve extends Curve {
  18449. /**
  18450. * Constructs a new line curve.
  18451. *
  18452. * @param {Vector2} [v1] - The start point.
  18453. * @param {Vector2} [v2] - The end point.
  18454. */
  18455. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18456. super();
  18457. /**
  18458. * This flag can be used for type testing.
  18459. *
  18460. * @type {boolean}
  18461. * @readonly
  18462. * @default true
  18463. */
  18464. this.isLineCurve = true;
  18465. this.type = 'LineCurve';
  18466. /**
  18467. * The start point.
  18468. *
  18469. * @type {Vector2}
  18470. */
  18471. this.v1 = v1;
  18472. /**
  18473. * The end point.
  18474. *
  18475. * @type {Vector2}
  18476. */
  18477. this.v2 = v2;
  18478. }
  18479. /**
  18480. * Returns a point on the line.
  18481. *
  18482. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  18483. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18484. * @return {Vector2} The position on the line.
  18485. */
  18486. getPoint( t, optionalTarget = new Vector2() ) {
  18487. const point = optionalTarget;
  18488. if ( t === 1 ) {
  18489. point.copy( this.v2 );
  18490. } else {
  18491. point.copy( this.v2 ).sub( this.v1 );
  18492. point.multiplyScalar( t ).add( this.v1 );
  18493. }
  18494. return point;
  18495. }
  18496. // Line curve is linear, so we can overwrite default getPointAt
  18497. getPointAt( u, optionalTarget ) {
  18498. return this.getPoint( u, optionalTarget );
  18499. }
  18500. getTangent( t, optionalTarget = new Vector2() ) {
  18501. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  18502. }
  18503. getTangentAt( u, optionalTarget ) {
  18504. return this.getTangent( u, optionalTarget );
  18505. }
  18506. copy( source ) {
  18507. super.copy( source );
  18508. this.v1.copy( source.v1 );
  18509. this.v2.copy( source.v2 );
  18510. return this;
  18511. }
  18512. toJSON() {
  18513. const data = super.toJSON();
  18514. data.v1 = this.v1.toArray();
  18515. data.v2 = this.v2.toArray();
  18516. return data;
  18517. }
  18518. fromJSON( json ) {
  18519. super.fromJSON( json );
  18520. this.v1.fromArray( json.v1 );
  18521. this.v2.fromArray( json.v2 );
  18522. return this;
  18523. }
  18524. }
  18525. /**
  18526. * A curve representing a 3D line segment.
  18527. *
  18528. * @augments Curve
  18529. */
  18530. class LineCurve3 extends Curve {
  18531. /**
  18532. * Constructs a new line curve.
  18533. *
  18534. * @param {Vector3} [v1] - The start point.
  18535. * @param {Vector3} [v2] - The end point.
  18536. */
  18537. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18538. super();
  18539. /**
  18540. * This flag can be used for type testing.
  18541. *
  18542. * @type {boolean}
  18543. * @readonly
  18544. * @default true
  18545. */
  18546. this.isLineCurve3 = true;
  18547. this.type = 'LineCurve3';
  18548. /**
  18549. * The start point.
  18550. *
  18551. * @type {Vector3}
  18552. */
  18553. this.v1 = v1;
  18554. /**
  18555. * The end point.
  18556. *
  18557. * @type {Vector2}
  18558. */
  18559. this.v2 = v2;
  18560. }
  18561. /**
  18562. * Returns a point on the line.
  18563. *
  18564. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  18565. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18566. * @return {Vector3} The position on the line.
  18567. */
  18568. getPoint( t, optionalTarget = new Vector3() ) {
  18569. const point = optionalTarget;
  18570. if ( t === 1 ) {
  18571. point.copy( this.v2 );
  18572. } else {
  18573. point.copy( this.v2 ).sub( this.v1 );
  18574. point.multiplyScalar( t ).add( this.v1 );
  18575. }
  18576. return point;
  18577. }
  18578. // Line curve is linear, so we can overwrite default getPointAt
  18579. getPointAt( u, optionalTarget ) {
  18580. return this.getPoint( u, optionalTarget );
  18581. }
  18582. getTangent( t, optionalTarget = new Vector3() ) {
  18583. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  18584. }
  18585. getTangentAt( u, optionalTarget ) {
  18586. return this.getTangent( u, optionalTarget );
  18587. }
  18588. copy( source ) {
  18589. super.copy( source );
  18590. this.v1.copy( source.v1 );
  18591. this.v2.copy( source.v2 );
  18592. return this;
  18593. }
  18594. toJSON() {
  18595. const data = super.toJSON();
  18596. data.v1 = this.v1.toArray();
  18597. data.v2 = this.v2.toArray();
  18598. return data;
  18599. }
  18600. fromJSON( json ) {
  18601. super.fromJSON( json );
  18602. this.v1.fromArray( json.v1 );
  18603. this.v2.fromArray( json.v2 );
  18604. return this;
  18605. }
  18606. }
  18607. /**
  18608. * A curve representing a 2D Quadratic Bezier curve.
  18609. *
  18610. * ```js
  18611. * const curve = new THREE.QuadraticBezierCurve(
  18612. * new THREE.Vector2( - 10, 0 ),
  18613. * new THREE.Vector2( 20, 15 ),
  18614. * new THREE.Vector2( 10, 0 )
  18615. * )
  18616. *
  18617. * const points = curve.getPoints( 50 );
  18618. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18619. *
  18620. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18621. *
  18622. * // Create the final object to add to the scene
  18623. * const curveObject = new THREE.Line( geometry, material );
  18624. * ```
  18625. *
  18626. * @augments Curve
  18627. */
  18628. class QuadraticBezierCurve extends Curve {
  18629. /**
  18630. * Constructs a new Quadratic Bezier curve.
  18631. *
  18632. * @param {Vector2} [v0] - The start point.
  18633. * @param {Vector2} [v1] - The control point.
  18634. * @param {Vector2} [v2] - The end point.
  18635. */
  18636. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  18637. super();
  18638. /**
  18639. * This flag can be used for type testing.
  18640. *
  18641. * @type {boolean}
  18642. * @readonly
  18643. * @default true
  18644. */
  18645. this.isQuadraticBezierCurve = true;
  18646. this.type = 'QuadraticBezierCurve';
  18647. /**
  18648. * The start point.
  18649. *
  18650. * @type {Vector2}
  18651. */
  18652. this.v0 = v0;
  18653. /**
  18654. * The control point.
  18655. *
  18656. * @type {Vector2}
  18657. */
  18658. this.v1 = v1;
  18659. /**
  18660. * The end point.
  18661. *
  18662. * @type {Vector2}
  18663. */
  18664. this.v2 = v2;
  18665. }
  18666. /**
  18667. * Returns a point on the curve.
  18668. *
  18669. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18670. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18671. * @return {Vector2} The position on the curve.
  18672. */
  18673. getPoint( t, optionalTarget = new Vector2() ) {
  18674. const point = optionalTarget;
  18675. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18676. point.set(
  18677. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18678. QuadraticBezier( t, v0.y, v1.y, v2.y )
  18679. );
  18680. return point;
  18681. }
  18682. copy( source ) {
  18683. super.copy( source );
  18684. this.v0.copy( source.v0 );
  18685. this.v1.copy( source.v1 );
  18686. this.v2.copy( source.v2 );
  18687. return this;
  18688. }
  18689. toJSON() {
  18690. const data = super.toJSON();
  18691. data.v0 = this.v0.toArray();
  18692. data.v1 = this.v1.toArray();
  18693. data.v2 = this.v2.toArray();
  18694. return data;
  18695. }
  18696. fromJSON( json ) {
  18697. super.fromJSON( json );
  18698. this.v0.fromArray( json.v0 );
  18699. this.v1.fromArray( json.v1 );
  18700. this.v2.fromArray( json.v2 );
  18701. return this;
  18702. }
  18703. }
  18704. /**
  18705. * A curve representing a 3D Quadratic Bezier curve.
  18706. *
  18707. * @augments Curve
  18708. */
  18709. class QuadraticBezierCurve3 extends Curve {
  18710. /**
  18711. * Constructs a new Quadratic Bezier curve.
  18712. *
  18713. * @param {Vector3} [v0] - The start point.
  18714. * @param {Vector3} [v1] - The control point.
  18715. * @param {Vector3} [v2] - The end point.
  18716. */
  18717. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  18718. super();
  18719. /**
  18720. * This flag can be used for type testing.
  18721. *
  18722. * @type {boolean}
  18723. * @readonly
  18724. * @default true
  18725. */
  18726. this.isQuadraticBezierCurve3 = true;
  18727. this.type = 'QuadraticBezierCurve3';
  18728. /**
  18729. * The start point.
  18730. *
  18731. * @type {Vector3}
  18732. */
  18733. this.v0 = v0;
  18734. /**
  18735. * The control point.
  18736. *
  18737. * @type {Vector3}
  18738. */
  18739. this.v1 = v1;
  18740. /**
  18741. * The end point.
  18742. *
  18743. * @type {Vector3}
  18744. */
  18745. this.v2 = v2;
  18746. }
  18747. /**
  18748. * Returns a point on the curve.
  18749. *
  18750. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18751. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  18752. * @return {Vector3} The position on the curve.
  18753. */
  18754. getPoint( t, optionalTarget = new Vector3() ) {
  18755. const point = optionalTarget;
  18756. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  18757. point.set(
  18758. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  18759. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  18760. QuadraticBezier( t, v0.z, v1.z, v2.z )
  18761. );
  18762. return point;
  18763. }
  18764. copy( source ) {
  18765. super.copy( source );
  18766. this.v0.copy( source.v0 );
  18767. this.v1.copy( source.v1 );
  18768. this.v2.copy( source.v2 );
  18769. return this;
  18770. }
  18771. toJSON() {
  18772. const data = super.toJSON();
  18773. data.v0 = this.v0.toArray();
  18774. data.v1 = this.v1.toArray();
  18775. data.v2 = this.v2.toArray();
  18776. return data;
  18777. }
  18778. fromJSON( json ) {
  18779. super.fromJSON( json );
  18780. this.v0.fromArray( json.v0 );
  18781. this.v1.fromArray( json.v1 );
  18782. this.v2.fromArray( json.v2 );
  18783. return this;
  18784. }
  18785. }
  18786. /**
  18787. * A curve representing a 2D spline curve.
  18788. *
  18789. * ```js
  18790. * // Create a sine-like wave
  18791. * const curve = new THREE.SplineCurve( [
  18792. * new THREE.Vector2( -10, 0 ),
  18793. * new THREE.Vector2( -5, 5 ),
  18794. * new THREE.Vector2( 0, 0 ),
  18795. * new THREE.Vector2( 5, -5 ),
  18796. * new THREE.Vector2( 10, 0 )
  18797. * ] );
  18798. *
  18799. * const points = curve.getPoints( 50 );
  18800. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  18801. *
  18802. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  18803. *
  18804. * // Create the final object to add to the scene
  18805. * const splineObject = new THREE.Line( geometry, material );
  18806. * ```
  18807. *
  18808. * @augments Curve
  18809. */
  18810. class SplineCurve extends Curve {
  18811. /**
  18812. * Constructs a new 2D spline curve.
  18813. *
  18814. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  18815. */
  18816. constructor( points = [] ) {
  18817. super();
  18818. /**
  18819. * This flag can be used for type testing.
  18820. *
  18821. * @type {boolean}
  18822. * @readonly
  18823. * @default true
  18824. */
  18825. this.isSplineCurve = true;
  18826. this.type = 'SplineCurve';
  18827. /**
  18828. * An array of 2D points defining the curve.
  18829. *
  18830. * @type {Array<Vector2>}
  18831. */
  18832. this.points = points;
  18833. }
  18834. /**
  18835. * Returns a point on the curve.
  18836. *
  18837. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18838. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  18839. * @return {Vector2} The position on the curve.
  18840. */
  18841. getPoint( t, optionalTarget = new Vector2() ) {
  18842. const point = optionalTarget;
  18843. const points = this.points;
  18844. const p = ( points.length - 1 ) * t;
  18845. const intPoint = Math.floor( p );
  18846. const weight = p - intPoint;
  18847. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  18848. const p1 = points[ intPoint ];
  18849. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  18850. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  18851. point.set(
  18852. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  18853. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  18854. );
  18855. return point;
  18856. }
  18857. copy( source ) {
  18858. super.copy( source );
  18859. this.points = [];
  18860. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18861. const point = source.points[ i ];
  18862. this.points.push( point.clone() );
  18863. }
  18864. return this;
  18865. }
  18866. toJSON() {
  18867. const data = super.toJSON();
  18868. data.points = [];
  18869. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18870. const point = this.points[ i ];
  18871. data.points.push( point.toArray() );
  18872. }
  18873. return data;
  18874. }
  18875. fromJSON( json ) {
  18876. super.fromJSON( json );
  18877. this.points = [];
  18878. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18879. const point = json.points[ i ];
  18880. this.points.push( new Vector2().fromArray( point ) );
  18881. }
  18882. return this;
  18883. }
  18884. }
  18885. var Curves = /*#__PURE__*/Object.freeze({
  18886. __proto__: null,
  18887. ArcCurve: ArcCurve,
  18888. CatmullRomCurve3: CatmullRomCurve3,
  18889. CubicBezierCurve: CubicBezierCurve,
  18890. CubicBezierCurve3: CubicBezierCurve3,
  18891. EllipseCurve: EllipseCurve,
  18892. LineCurve: LineCurve,
  18893. LineCurve3: LineCurve3,
  18894. QuadraticBezierCurve: QuadraticBezierCurve,
  18895. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18896. SplineCurve: SplineCurve
  18897. });
  18898. /**
  18899. * A base class extending {@link Curve}. `CurvePath` is simply an
  18900. * array of connected curves, but retains the API of a curve.
  18901. *
  18902. * @augments Curve
  18903. */
  18904. class CurvePath extends Curve {
  18905. /**
  18906. * Constructs a new curve path.
  18907. */
  18908. constructor() {
  18909. super();
  18910. this.type = 'CurvePath';
  18911. /**
  18912. * An array of curves defining the
  18913. * path.
  18914. *
  18915. * @type {Array<Curve>}
  18916. */
  18917. this.curves = [];
  18918. /**
  18919. * Whether the path should automatically be closed
  18920. * by a line curve.
  18921. *
  18922. * @type {boolean}
  18923. * @default false
  18924. */
  18925. this.autoClose = false;
  18926. }
  18927. /**
  18928. * Adds a curve to this curve path.
  18929. *
  18930. * @param {Curve} curve - The curve to add.
  18931. */
  18932. add( curve ) {
  18933. this.curves.push( curve );
  18934. }
  18935. /**
  18936. * Adds a line curve to close the path.
  18937. *
  18938. * @return {CurvePath} A reference to this curve path.
  18939. */
  18940. closePath() {
  18941. // Add a line curve if start and end of lines are not connected
  18942. const startPoint = this.curves[ 0 ].getPoint( 0 );
  18943. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  18944. if ( ! startPoint.equals( endPoint ) ) {
  18945. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  18946. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  18947. }
  18948. return this;
  18949. }
  18950. /**
  18951. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  18952. * for the given interpolation factor.
  18953. *
  18954. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  18955. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  18956. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  18957. */
  18958. getPoint( t, optionalTarget ) {
  18959. // To get accurate point with reference to
  18960. // entire path distance at time t,
  18961. // following has to be done:
  18962. // 1. Length of each sub path have to be known
  18963. // 2. Locate and identify type of curve
  18964. // 3. Get t for the curve
  18965. // 4. Return curve.getPointAt(t')
  18966. const d = t * this.getLength();
  18967. const curveLengths = this.getCurveLengths();
  18968. let i = 0;
  18969. // To think about boundaries points.
  18970. while ( i < curveLengths.length ) {
  18971. if ( curveLengths[ i ] >= d ) {
  18972. const diff = curveLengths[ i ] - d;
  18973. const curve = this.curves[ i ];
  18974. const segmentLength = curve.getLength();
  18975. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  18976. return curve.getPointAt( u, optionalTarget );
  18977. }
  18978. i ++;
  18979. }
  18980. return null;
  18981. // loop where sum != 0, sum > d , sum+1 <d
  18982. }
  18983. getLength() {
  18984. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  18985. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  18986. // getPoint() depends on getLength
  18987. const lens = this.getCurveLengths();
  18988. return lens[ lens.length - 1 ];
  18989. }
  18990. updateArcLengths() {
  18991. // cacheLengths must be recalculated.
  18992. this.needsUpdate = true;
  18993. this.cacheLengths = null;
  18994. this.getCurveLengths();
  18995. }
  18996. /**
  18997. * Returns list of cumulative curve lengths of the defined curves.
  18998. *
  18999. * @return {Array<number>} The curve lengths.
  19000. */
  19001. getCurveLengths() {
  19002. // Compute lengths and cache them
  19003. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19004. // We use cache values if curves and cache array are same length
  19005. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19006. return this.cacheLengths;
  19007. }
  19008. // Get length of sub-curve
  19009. // Push sums into cached array
  19010. const lengths = [];
  19011. let sums = 0;
  19012. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19013. sums += this.curves[ i ].getLength();
  19014. lengths.push( sums );
  19015. }
  19016. this.cacheLengths = lengths;
  19017. return lengths;
  19018. }
  19019. getSpacedPoints( divisions = 40 ) {
  19020. const points = [];
  19021. for ( let i = 0; i <= divisions; i ++ ) {
  19022. points.push( this.getPoint( i / divisions ) );
  19023. }
  19024. if ( this.autoClose ) {
  19025. points.push( points[ 0 ] );
  19026. }
  19027. return points;
  19028. }
  19029. getPoints( divisions = 12 ) {
  19030. const points = [];
  19031. let last;
  19032. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19033. const curve = curves[ i ];
  19034. const resolution = curve.isEllipseCurve ? divisions * 2
  19035. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19036. : curve.isSplineCurve ? divisions * curve.points.length
  19037. : divisions;
  19038. const pts = curve.getPoints( resolution );
  19039. for ( let j = 0; j < pts.length; j ++ ) {
  19040. const point = pts[ j ];
  19041. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19042. points.push( point );
  19043. last = point;
  19044. }
  19045. }
  19046. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19047. points.push( points[ 0 ] );
  19048. }
  19049. return points;
  19050. }
  19051. copy( source ) {
  19052. super.copy( source );
  19053. this.curves = [];
  19054. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19055. const curve = source.curves[ i ];
  19056. this.curves.push( curve.clone() );
  19057. }
  19058. this.autoClose = source.autoClose;
  19059. return this;
  19060. }
  19061. toJSON() {
  19062. const data = super.toJSON();
  19063. data.autoClose = this.autoClose;
  19064. data.curves = [];
  19065. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19066. const curve = this.curves[ i ];
  19067. data.curves.push( curve.toJSON() );
  19068. }
  19069. return data;
  19070. }
  19071. fromJSON( json ) {
  19072. super.fromJSON( json );
  19073. this.autoClose = json.autoClose;
  19074. this.curves = [];
  19075. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19076. const curve = json.curves[ i ];
  19077. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19078. }
  19079. return this;
  19080. }
  19081. }
  19082. /**
  19083. * A 2D path representation. The class provides methods for creating paths
  19084. * and contours of 2D shapes similar to the 2D Canvas API.
  19085. *
  19086. * ```js
  19087. * const path = new THREE.Path();
  19088. *
  19089. * path.lineTo( 0, 0.8 );
  19090. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  19091. * path.lineTo( 1, 1 );
  19092. *
  19093. * const points = path.getPoints();
  19094. *
  19095. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  19096. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  19097. *
  19098. * const line = new THREE.Line( geometry, material );
  19099. * scene.add( line );
  19100. * ```
  19101. *
  19102. * @augments CurvePath
  19103. */
  19104. class Path extends CurvePath {
  19105. /**
  19106. * Constructs a new path.
  19107. *
  19108. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  19109. */
  19110. constructor( points ) {
  19111. super();
  19112. this.type = 'Path';
  19113. /**
  19114. * The current offset of the path. Any new curve added will start here.
  19115. *
  19116. * @type {Vector2}
  19117. */
  19118. this.currentPoint = new Vector2();
  19119. if ( points ) {
  19120. this.setFromPoints( points );
  19121. }
  19122. }
  19123. /**
  19124. * Creates a path from the given list of points. The points are added
  19125. * to the path as instances of {@link LineCurve}.
  19126. *
  19127. * @param {Array<Vector2>} points - An array of 2D points.
  19128. * @return {Path} A reference to this path.
  19129. */
  19130. setFromPoints( points ) {
  19131. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19132. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19133. this.lineTo( points[ i ].x, points[ i ].y );
  19134. }
  19135. return this;
  19136. }
  19137. /**
  19138. * Moves {@link Path#currentPoint} to the given point.
  19139. *
  19140. * @param {number} x - The x coordinate.
  19141. * @param {number} y - The y coordinate.
  19142. * @return {Path} A reference to this path.
  19143. */
  19144. moveTo( x, y ) {
  19145. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19146. return this;
  19147. }
  19148. /**
  19149. * Adds an instance of {@link LineCurve} to the path by connecting
  19150. * the current point with the given one.
  19151. *
  19152. * @param {number} x - The x coordinate of the end point.
  19153. * @param {number} y - The y coordinate of the end point.
  19154. * @return {Path} A reference to this path.
  19155. */
  19156. lineTo( x, y ) {
  19157. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19158. this.curves.push( curve );
  19159. this.currentPoint.set( x, y );
  19160. return this;
  19161. }
  19162. /**
  19163. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  19164. * the current point with the given one.
  19165. *
  19166. * @param {number} aCPx - The x coordinate of the control point.
  19167. * @param {number} aCPy - The y coordinate of the control point.
  19168. * @param {number} aX - The x coordinate of the end point.
  19169. * @param {number} aY - The y coordinate of the end point.
  19170. * @return {Path} A reference to this path.
  19171. */
  19172. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19173. const curve = new QuadraticBezierCurve(
  19174. this.currentPoint.clone(),
  19175. new Vector2( aCPx, aCPy ),
  19176. new Vector2( aX, aY )
  19177. );
  19178. this.curves.push( curve );
  19179. this.currentPoint.set( aX, aY );
  19180. return this;
  19181. }
  19182. /**
  19183. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  19184. * the current point with the given one.
  19185. *
  19186. * @param {number} aCP1x - The x coordinate of the first control point.
  19187. * @param {number} aCP1y - The y coordinate of the first control point.
  19188. * @param {number} aCP2x - The x coordinate of the second control point.
  19189. * @param {number} aCP2y - The y coordinate of the second control point.
  19190. * @param {number} aX - The x coordinate of the end point.
  19191. * @param {number} aY - The y coordinate of the end point.
  19192. * @return {Path} A reference to this path.
  19193. */
  19194. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19195. const curve = new CubicBezierCurve(
  19196. this.currentPoint.clone(),
  19197. new Vector2( aCP1x, aCP1y ),
  19198. new Vector2( aCP2x, aCP2y ),
  19199. new Vector2( aX, aY )
  19200. );
  19201. this.curves.push( curve );
  19202. this.currentPoint.set( aX, aY );
  19203. return this;
  19204. }
  19205. /**
  19206. * Adds an instance of {@link SplineCurve} to the path by connecting
  19207. * the current point with the given list of points.
  19208. *
  19209. * @param {Array<Vector2>} pts - An array of points in 2D space.
  19210. * @return {Path} A reference to this path.
  19211. */
  19212. splineThru( pts ) {
  19213. const npts = [ this.currentPoint.clone() ].concat( pts );
  19214. const curve = new SplineCurve( npts );
  19215. this.curves.push( curve );
  19216. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19217. return this;
  19218. }
  19219. /**
  19220. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  19221. * to the current point.
  19222. *
  19223. * @param {number} aX - The x coordinate of the center of the arc offsetted from the previous curve.
  19224. * @param {number} aY - The y coordinate of the center of the arc offsetted from the previous curve.
  19225. * @param {number} aRadius - The radius of the arc.
  19226. * @param {number} aStartAngle - The start angle in radians.
  19227. * @param {number} aEndAngle - The end angle in radians.
  19228. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  19229. * @return {Path} A reference to this path.
  19230. */
  19231. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19232. const x0 = this.currentPoint.x;
  19233. const y0 = this.currentPoint.y;
  19234. this.absarc( aX + x0, aY + y0, aRadius,
  19235. aStartAngle, aEndAngle, aClockwise );
  19236. return this;
  19237. }
  19238. /**
  19239. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  19240. *
  19241. * @param {number} aX - The x coordinate of the center of the arc.
  19242. * @param {number} aY - The y coordinate of the center of the arc.
  19243. * @param {number} aRadius - The radius of the arc.
  19244. * @param {number} aStartAngle - The start angle in radians.
  19245. * @param {number} aEndAngle - The end angle in radians.
  19246. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  19247. * @return {Path} A reference to this path.
  19248. */
  19249. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19250. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19251. return this;
  19252. }
  19253. /**
  19254. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  19255. * to the current point
  19256. *
  19257. * @param {number} aX - The x coordinate of the center of the ellipse offsetted from the previous curve.
  19258. * @param {number} aY - The y coordinate of the center of the ellipse offsetted from the previous curve.
  19259. * @param {number} xRadius - The radius of the ellipse in the x axis.
  19260. * @param {number} yRadius - The radius of the ellipse in the y axis.
  19261. * @param {number} aStartAngle - The start angle in radians.
  19262. * @param {number} aEndAngle - The end angle in radians.
  19263. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  19264. * @param {boolean} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  19265. * @return {Path} A reference to this path.
  19266. */
  19267. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19268. const x0 = this.currentPoint.x;
  19269. const y0 = this.currentPoint.y;
  19270. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19271. return this;
  19272. }
  19273. /**
  19274. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  19275. *
  19276. * @param {number} aX - The x coordinate of the absolute center of the ellipse.
  19277. * @param {number} aY - The y coordinate of the absolute center of the ellipse.
  19278. * @param {number} xRadius - The radius of the ellipse in the x axis.
  19279. * @param {number} yRadius - The radius of the ellipse in the y axis.
  19280. * @param {number} aStartAngle - The start angle in radians.
  19281. * @param {number} aEndAngle - The end angle in radians.
  19282. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  19283. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  19284. * @return {Path} A reference to this path.
  19285. */
  19286. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19287. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19288. if ( this.curves.length > 0 ) {
  19289. // if a previous curve is present, attempt to join
  19290. const firstPoint = curve.getPoint( 0 );
  19291. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19292. this.lineTo( firstPoint.x, firstPoint.y );
  19293. }
  19294. }
  19295. this.curves.push( curve );
  19296. const lastPoint = curve.getPoint( 1 );
  19297. this.currentPoint.copy( lastPoint );
  19298. return this;
  19299. }
  19300. copy( source ) {
  19301. super.copy( source );
  19302. this.currentPoint.copy( source.currentPoint );
  19303. return this;
  19304. }
  19305. toJSON() {
  19306. const data = super.toJSON();
  19307. data.currentPoint = this.currentPoint.toArray();
  19308. return data;
  19309. }
  19310. fromJSON( json ) {
  19311. super.fromJSON( json );
  19312. this.currentPoint.fromArray( json.currentPoint );
  19313. return this;
  19314. }
  19315. }
  19316. /**
  19317. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  19318. *
  19319. * ```js
  19320. * const points = [];
  19321. * for ( let i = 0; i < 10; i ++ ) {
  19322. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  19323. * }
  19324. * const geometry = new THREE.LatheGeometry( points );
  19325. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19326. * const lathe = new THREE.Mesh( geometry, material );
  19327. * scene.add( lathe );
  19328. * ```
  19329. *
  19330. * @augments BufferGeometry
  19331. */
  19332. class LatheGeometry extends BufferGeometry {
  19333. /**
  19334. * Constructs a new lathe geometry.
  19335. *
  19336. * @param {Array<Vector2>} [points] - An array of points in 2D space. The x-coordinate of each point
  19337. * must be greater than zero.
  19338. * @param {number} [segments=12] - The number of circumference segments to generate.
  19339. * @param {number} [phiStart=0] - The starting angle in radians.
  19340. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  19341. * closed lathe, less than 2PI is a portion.
  19342. */
  19343. 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 ) {
  19344. super();
  19345. this.type = 'LatheGeometry';
  19346. /**
  19347. * Holds the constructor parameters that have been
  19348. * used to generate the geometry. Any modification
  19349. * after instantiation does not change the geometry.
  19350. *
  19351. * @type {Object}
  19352. */
  19353. this.parameters = {
  19354. points: points,
  19355. segments: segments,
  19356. phiStart: phiStart,
  19357. phiLength: phiLength
  19358. };
  19359. segments = Math.floor( segments );
  19360. // clamp phiLength so it's in range of [ 0, 2PI ]
  19361. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19362. // buffers
  19363. const indices = [];
  19364. const vertices = [];
  19365. const uvs = [];
  19366. const initNormals = [];
  19367. const normals = [];
  19368. // helper variables
  19369. const inverseSegments = 1.0 / segments;
  19370. const vertex = new Vector3();
  19371. const uv = new Vector2();
  19372. const normal = new Vector3();
  19373. const curNormal = new Vector3();
  19374. const prevNormal = new Vector3();
  19375. let dx = 0;
  19376. let dy = 0;
  19377. // pre-compute normals for initial "meridian"
  19378. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19379. switch ( j ) {
  19380. case 0: // special handling for 1st vertex on path
  19381. dx = points[ j + 1 ].x - points[ j ].x;
  19382. dy = points[ j + 1 ].y - points[ j ].y;
  19383. normal.x = dy * 1.0;
  19384. normal.y = - dx;
  19385. normal.z = dy * 0.0;
  19386. prevNormal.copy( normal );
  19387. normal.normalize();
  19388. initNormals.push( normal.x, normal.y, normal.z );
  19389. break;
  19390. case ( points.length - 1 ): // special handling for last Vertex on path
  19391. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19392. break;
  19393. default: // default handling for all vertices in between
  19394. dx = points[ j + 1 ].x - points[ j ].x;
  19395. dy = points[ j + 1 ].y - points[ j ].y;
  19396. normal.x = dy * 1.0;
  19397. normal.y = - dx;
  19398. normal.z = dy * 0.0;
  19399. curNormal.copy( normal );
  19400. normal.x += prevNormal.x;
  19401. normal.y += prevNormal.y;
  19402. normal.z += prevNormal.z;
  19403. normal.normalize();
  19404. initNormals.push( normal.x, normal.y, normal.z );
  19405. prevNormal.copy( curNormal );
  19406. }
  19407. }
  19408. // generate vertices, uvs and normals
  19409. for ( let i = 0; i <= segments; i ++ ) {
  19410. const phi = phiStart + i * inverseSegments * phiLength;
  19411. const sin = Math.sin( phi );
  19412. const cos = Math.cos( phi );
  19413. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19414. // vertex
  19415. vertex.x = points[ j ].x * sin;
  19416. vertex.y = points[ j ].y;
  19417. vertex.z = points[ j ].x * cos;
  19418. vertices.push( vertex.x, vertex.y, vertex.z );
  19419. // uv
  19420. uv.x = i / segments;
  19421. uv.y = j / ( points.length - 1 );
  19422. uvs.push( uv.x, uv.y );
  19423. // normal
  19424. const x = initNormals[ 3 * j + 0 ] * sin;
  19425. const y = initNormals[ 3 * j + 1 ];
  19426. const z = initNormals[ 3 * j + 0 ] * cos;
  19427. normals.push( x, y, z );
  19428. }
  19429. }
  19430. // indices
  19431. for ( let i = 0; i < segments; i ++ ) {
  19432. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19433. const base = j + i * points.length;
  19434. const a = base;
  19435. const b = base + points.length;
  19436. const c = base + points.length + 1;
  19437. const d = base + 1;
  19438. // faces
  19439. indices.push( a, b, d );
  19440. indices.push( c, d, b );
  19441. }
  19442. }
  19443. // build geometry
  19444. this.setIndex( indices );
  19445. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19446. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19447. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19448. }
  19449. copy( source ) {
  19450. super.copy( source );
  19451. this.parameters = Object.assign( {}, source.parameters );
  19452. return this;
  19453. }
  19454. /**
  19455. * Factory method for creating an instance of this class from the given
  19456. * JSON object.
  19457. *
  19458. * @param {Object} data - A JSON object representing the serialized geometry.
  19459. * @return {LatheGeometry} A new instance.
  19460. */
  19461. static fromJSON( data ) {
  19462. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19463. }
  19464. }
  19465. /**
  19466. * A geometry class for a capsule with given radii and height. It is constructed using a lathe.
  19467. *
  19468. * ```js
  19469. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8 );
  19470. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19471. * const capsule = new THREE.Mesh( geometry, material );
  19472. * scene.add( capsule );
  19473. * ```
  19474. *
  19475. * @augments LatheGeometry
  19476. */
  19477. class CapsuleGeometry extends LatheGeometry {
  19478. /**
  19479. * Constructs a new capsule geometry.
  19480. *
  19481. * @param {number} [radius=1] - Radius of the capsule.
  19482. * @param {number} [length=1] - Length of the middle section.
  19483. * @param {number} [capSegments=4] - Number of curve segments used to build the caps.
  19484. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule.
  19485. */
  19486. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19487. const path = new Path();
  19488. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19489. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19490. super( path.getPoints( capSegments ), radialSegments );
  19491. this.type = 'CapsuleGeometry';
  19492. /**
  19493. * Holds the constructor parameters that have been
  19494. * used to generate the geometry. Any modification
  19495. * after instantiation does not change the geometry.
  19496. *
  19497. * @type {Object}
  19498. */
  19499. this.parameters = {
  19500. radius: radius,
  19501. length: length,
  19502. capSegments: capSegments,
  19503. radialSegments: radialSegments,
  19504. };
  19505. }
  19506. /**
  19507. * Factory method for creating an instance of this class from the given
  19508. * JSON object.
  19509. *
  19510. * @param {Object} data - A JSON object representing the serialized geometry.
  19511. * @return {CapsuleGeometry} A new instance.
  19512. */
  19513. static fromJSON( data ) {
  19514. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19515. }
  19516. }
  19517. /**
  19518. * A simple shape of Euclidean geometry. It is constructed from a
  19519. * number of triangular segments that are oriented around a central point and
  19520. * extend as far out as a given radius. It is built counter-clockwise from a
  19521. * start angle and a given central angle. It can also be used to create
  19522. * regular polygons, where the number of segments determines the number of
  19523. * sides.
  19524. *
  19525. * ```js
  19526. * const geometry = new THREE.CircleGeometry( 5, 32 );
  19527. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19528. * const circle = new THREE.Mesh( geometry, material );
  19529. * scene.add( circle )
  19530. * ```
  19531. *
  19532. * @augments BufferGeometry
  19533. */
  19534. class CircleGeometry extends BufferGeometry {
  19535. /**
  19536. * Constructs a new circle geometry.
  19537. *
  19538. * @param {number} [radius=1] - Radius of the circle.
  19539. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  19540. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  19541. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  19542. * of the circular sector in radians. The default value results in a complete circle.
  19543. */
  19544. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19545. super();
  19546. this.type = 'CircleGeometry';
  19547. /**
  19548. * Holds the constructor parameters that have been
  19549. * used to generate the geometry. Any modification
  19550. * after instantiation does not change the geometry.
  19551. *
  19552. * @type {Object}
  19553. */
  19554. this.parameters = {
  19555. radius: radius,
  19556. segments: segments,
  19557. thetaStart: thetaStart,
  19558. thetaLength: thetaLength
  19559. };
  19560. segments = Math.max( 3, segments );
  19561. // buffers
  19562. const indices = [];
  19563. const vertices = [];
  19564. const normals = [];
  19565. const uvs = [];
  19566. // helper variables
  19567. const vertex = new Vector3();
  19568. const uv = new Vector2();
  19569. // center point
  19570. vertices.push( 0, 0, 0 );
  19571. normals.push( 0, 0, 1 );
  19572. uvs.push( 0.5, 0.5 );
  19573. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19574. const segment = thetaStart + s / segments * thetaLength;
  19575. // vertex
  19576. vertex.x = radius * Math.cos( segment );
  19577. vertex.y = radius * Math.sin( segment );
  19578. vertices.push( vertex.x, vertex.y, vertex.z );
  19579. // normal
  19580. normals.push( 0, 0, 1 );
  19581. // uvs
  19582. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19583. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19584. uvs.push( uv.x, uv.y );
  19585. }
  19586. // indices
  19587. for ( let i = 1; i <= segments; i ++ ) {
  19588. indices.push( i, i + 1, 0 );
  19589. }
  19590. // build geometry
  19591. this.setIndex( indices );
  19592. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19593. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19594. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19595. }
  19596. copy( source ) {
  19597. super.copy( source );
  19598. this.parameters = Object.assign( {}, source.parameters );
  19599. return this;
  19600. }
  19601. /**
  19602. * Factory method for creating an instance of this class from the given
  19603. * JSON object.
  19604. *
  19605. * @param {Object} data - A JSON object representing the serialized geometry.
  19606. * @return {CircleGeometry} A new instance.
  19607. */
  19608. static fromJSON( data ) {
  19609. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19610. }
  19611. }
  19612. /**
  19613. * A geometry class for representing a cylinder.
  19614. *
  19615. * ```js
  19616. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  19617. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19618. * const cylinder = new THREE.Mesh( geometry, material );
  19619. * scene.add( cylinder );
  19620. * ```
  19621. *
  19622. * @augments BufferGeometry
  19623. */
  19624. class CylinderGeometry extends BufferGeometry {
  19625. /**
  19626. * Constructs a new cylinder geometry.
  19627. *
  19628. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  19629. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  19630. * @param {number} [height=1] - Height of the cylinder.
  19631. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  19632. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  19633. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  19634. * @param {boolean} [thetaStart=0] - Start angle for first segment, in radians.
  19635. * @param {boolean} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  19636. * The default value results in a complete cylinder.
  19637. */
  19638. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19639. super();
  19640. this.type = 'CylinderGeometry';
  19641. /**
  19642. * Holds the constructor parameters that have been
  19643. * used to generate the geometry. Any modification
  19644. * after instantiation does not change the geometry.
  19645. *
  19646. * @type {Object}
  19647. */
  19648. this.parameters = {
  19649. radiusTop: radiusTop,
  19650. radiusBottom: radiusBottom,
  19651. height: height,
  19652. radialSegments: radialSegments,
  19653. heightSegments: heightSegments,
  19654. openEnded: openEnded,
  19655. thetaStart: thetaStart,
  19656. thetaLength: thetaLength
  19657. };
  19658. const scope = this;
  19659. radialSegments = Math.floor( radialSegments );
  19660. heightSegments = Math.floor( heightSegments );
  19661. // buffers
  19662. const indices = [];
  19663. const vertices = [];
  19664. const normals = [];
  19665. const uvs = [];
  19666. // helper variables
  19667. let index = 0;
  19668. const indexArray = [];
  19669. const halfHeight = height / 2;
  19670. let groupStart = 0;
  19671. // generate geometry
  19672. generateTorso();
  19673. if ( openEnded === false ) {
  19674. if ( radiusTop > 0 ) generateCap( true );
  19675. if ( radiusBottom > 0 ) generateCap( false );
  19676. }
  19677. // build geometry
  19678. this.setIndex( indices );
  19679. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19680. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19681. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19682. function generateTorso() {
  19683. const normal = new Vector3();
  19684. const vertex = new Vector3();
  19685. let groupCount = 0;
  19686. // this will be used to calculate the normal
  19687. const slope = ( radiusBottom - radiusTop ) / height;
  19688. // generate vertices, normals and uvs
  19689. for ( let y = 0; y <= heightSegments; y ++ ) {
  19690. const indexRow = [];
  19691. const v = y / heightSegments;
  19692. // calculate the radius of the current row
  19693. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19694. for ( let x = 0; x <= radialSegments; x ++ ) {
  19695. const u = x / radialSegments;
  19696. const theta = u * thetaLength + thetaStart;
  19697. const sinTheta = Math.sin( theta );
  19698. const cosTheta = Math.cos( theta );
  19699. // vertex
  19700. vertex.x = radius * sinTheta;
  19701. vertex.y = - v * height + halfHeight;
  19702. vertex.z = radius * cosTheta;
  19703. vertices.push( vertex.x, vertex.y, vertex.z );
  19704. // normal
  19705. normal.set( sinTheta, slope, cosTheta ).normalize();
  19706. normals.push( normal.x, normal.y, normal.z );
  19707. // uv
  19708. uvs.push( u, 1 - v );
  19709. // save index of vertex in respective row
  19710. indexRow.push( index ++ );
  19711. }
  19712. // now save vertices of the row in our index array
  19713. indexArray.push( indexRow );
  19714. }
  19715. // generate indices
  19716. for ( let x = 0; x < radialSegments; x ++ ) {
  19717. for ( let y = 0; y < heightSegments; y ++ ) {
  19718. // we use the index array to access the correct indices
  19719. const a = indexArray[ y ][ x ];
  19720. const b = indexArray[ y + 1 ][ x ];
  19721. const c = indexArray[ y + 1 ][ x + 1 ];
  19722. const d = indexArray[ y ][ x + 1 ];
  19723. // faces
  19724. if ( radiusTop > 0 || y !== 0 ) {
  19725. indices.push( a, b, d );
  19726. groupCount += 3;
  19727. }
  19728. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  19729. indices.push( b, c, d );
  19730. groupCount += 3;
  19731. }
  19732. }
  19733. }
  19734. // add a group to the geometry. this will ensure multi material support
  19735. scope.addGroup( groupStart, groupCount, 0 );
  19736. // calculate new start value for groups
  19737. groupStart += groupCount;
  19738. }
  19739. function generateCap( top ) {
  19740. // save the index of the first center vertex
  19741. const centerIndexStart = index;
  19742. const uv = new Vector2();
  19743. const vertex = new Vector3();
  19744. let groupCount = 0;
  19745. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19746. const sign = ( top === true ) ? 1 : -1;
  19747. // first we generate the center vertex data of the cap.
  19748. // because the geometry needs one set of uvs per face,
  19749. // we must generate a center vertex per face/segment
  19750. for ( let x = 1; x <= radialSegments; x ++ ) {
  19751. // vertex
  19752. vertices.push( 0, halfHeight * sign, 0 );
  19753. // normal
  19754. normals.push( 0, sign, 0 );
  19755. // uv
  19756. uvs.push( 0.5, 0.5 );
  19757. // increase index
  19758. index ++;
  19759. }
  19760. // save the index of the last center vertex
  19761. const centerIndexEnd = index;
  19762. // now we generate the surrounding vertices, normals and uvs
  19763. for ( let x = 0; x <= radialSegments; x ++ ) {
  19764. const u = x / radialSegments;
  19765. const theta = u * thetaLength + thetaStart;
  19766. const cosTheta = Math.cos( theta );
  19767. const sinTheta = Math.sin( theta );
  19768. // vertex
  19769. vertex.x = radius * sinTheta;
  19770. vertex.y = halfHeight * sign;
  19771. vertex.z = radius * cosTheta;
  19772. vertices.push( vertex.x, vertex.y, vertex.z );
  19773. // normal
  19774. normals.push( 0, sign, 0 );
  19775. // uv
  19776. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19777. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19778. uvs.push( uv.x, uv.y );
  19779. // increase index
  19780. index ++;
  19781. }
  19782. // generate indices
  19783. for ( let x = 0; x < radialSegments; x ++ ) {
  19784. const c = centerIndexStart + x;
  19785. const i = centerIndexEnd + x;
  19786. if ( top === true ) {
  19787. // face top
  19788. indices.push( i, i + 1, c );
  19789. } else {
  19790. // face bottom
  19791. indices.push( i + 1, i, c );
  19792. }
  19793. groupCount += 3;
  19794. }
  19795. // add a group to the geometry. this will ensure multi material support
  19796. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19797. // calculate new start value for groups
  19798. groupStart += groupCount;
  19799. }
  19800. }
  19801. copy( source ) {
  19802. super.copy( source );
  19803. this.parameters = Object.assign( {}, source.parameters );
  19804. return this;
  19805. }
  19806. /**
  19807. * Factory method for creating an instance of this class from the given
  19808. * JSON object.
  19809. *
  19810. * @param {Object} data - A JSON object representing the serialized geometry.
  19811. * @return {CylinderGeometry} A new instance.
  19812. */
  19813. static fromJSON( data ) {
  19814. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19815. }
  19816. }
  19817. /**
  19818. * A geometry class for representing a cone.
  19819. *
  19820. * ```js
  19821. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  19822. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  19823. * const cone = new THREE.Mesh(geometry, material );
  19824. * scene.add( cone );
  19825. * ```
  19826. *
  19827. * @augments CylinderGeometry
  19828. */
  19829. class ConeGeometry extends CylinderGeometry {
  19830. /**
  19831. * Constructs a new cone geometry.
  19832. *
  19833. * @param {number} [radius=1] - Radius of the cone base.
  19834. * @param {number} [height=1] - Height of the cone.
  19835. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  19836. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  19837. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  19838. * @param {boolean} [thetaStart=0] - Start angle for first segment, in radians.
  19839. * @param {boolean} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  19840. * The default value results in a complete cone.
  19841. */
  19842. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19843. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19844. this.type = 'ConeGeometry';
  19845. /**
  19846. * Holds the constructor parameters that have been
  19847. * used to generate the geometry. Any modification
  19848. * after instantiation does not change the geometry.
  19849. *
  19850. * @type {Object}
  19851. */
  19852. this.parameters = {
  19853. radius: radius,
  19854. height: height,
  19855. radialSegments: radialSegments,
  19856. heightSegments: heightSegments,
  19857. openEnded: openEnded,
  19858. thetaStart: thetaStart,
  19859. thetaLength: thetaLength
  19860. };
  19861. }
  19862. /**
  19863. * Factory method for creating an instance of this class from the given
  19864. * JSON object.
  19865. *
  19866. * @param {Object} data - A JSON object representing the serialized geometry.
  19867. * @return {ConeGeometry} A new instance.
  19868. */
  19869. static fromJSON( data ) {
  19870. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19871. }
  19872. }
  19873. /**
  19874. * A polyhedron is a solid in three dimensions with flat faces. This class
  19875. * will take an array of vertices, project them onto a sphere, and then
  19876. * divide them up to the desired level of detail.
  19877. *
  19878. * @augments BufferGeometry
  19879. */
  19880. class PolyhedronGeometry extends BufferGeometry {
  19881. /**
  19882. * Constructs a new polyhedron geometry.
  19883. *
  19884. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  19885. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  19886. * @param {number} [radius=1] - The radius of the shape.
  19887. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  19888. */
  19889. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  19890. super();
  19891. this.type = 'PolyhedronGeometry';
  19892. /**
  19893. * Holds the constructor parameters that have been
  19894. * used to generate the geometry. Any modification
  19895. * after instantiation does not change the geometry.
  19896. *
  19897. * @type {Object}
  19898. */
  19899. this.parameters = {
  19900. vertices: vertices,
  19901. indices: indices,
  19902. radius: radius,
  19903. detail: detail
  19904. };
  19905. // default buffer data
  19906. const vertexBuffer = [];
  19907. const uvBuffer = [];
  19908. // the subdivision creates the vertex buffer data
  19909. subdivide( detail );
  19910. // all vertices should lie on a conceptual sphere with a given radius
  19911. applyRadius( radius );
  19912. // finally, create the uv data
  19913. generateUVs();
  19914. // build non-indexed geometry
  19915. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19916. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19917. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19918. if ( detail === 0 ) {
  19919. this.computeVertexNormals(); // flat normals
  19920. } else {
  19921. this.normalizeNormals(); // smooth normals
  19922. }
  19923. // helper functions
  19924. function subdivide( detail ) {
  19925. const a = new Vector3();
  19926. const b = new Vector3();
  19927. const c = new Vector3();
  19928. // iterate over all faces and apply a subdivision with the given detail value
  19929. for ( let i = 0; i < indices.length; i += 3 ) {
  19930. // get the vertices of the face
  19931. getVertexByIndex( indices[ i + 0 ], a );
  19932. getVertexByIndex( indices[ i + 1 ], b );
  19933. getVertexByIndex( indices[ i + 2 ], c );
  19934. // perform subdivision
  19935. subdivideFace( a, b, c, detail );
  19936. }
  19937. }
  19938. function subdivideFace( a, b, c, detail ) {
  19939. const cols = detail + 1;
  19940. // we use this multidimensional array as a data structure for creating the subdivision
  19941. const v = [];
  19942. // construct all of the vertices for this subdivision
  19943. for ( let i = 0; i <= cols; i ++ ) {
  19944. v[ i ] = [];
  19945. const aj = a.clone().lerp( c, i / cols );
  19946. const bj = b.clone().lerp( c, i / cols );
  19947. const rows = cols - i;
  19948. for ( let j = 0; j <= rows; j ++ ) {
  19949. if ( j === 0 && i === cols ) {
  19950. v[ i ][ j ] = aj;
  19951. } else {
  19952. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19953. }
  19954. }
  19955. }
  19956. // construct all of the faces
  19957. for ( let i = 0; i < cols; i ++ ) {
  19958. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19959. const k = Math.floor( j / 2 );
  19960. if ( j % 2 === 0 ) {
  19961. pushVertex( v[ i ][ k + 1 ] );
  19962. pushVertex( v[ i + 1 ][ k ] );
  19963. pushVertex( v[ i ][ k ] );
  19964. } else {
  19965. pushVertex( v[ i ][ k + 1 ] );
  19966. pushVertex( v[ i + 1 ][ k + 1 ] );
  19967. pushVertex( v[ i + 1 ][ k ] );
  19968. }
  19969. }
  19970. }
  19971. }
  19972. function applyRadius( radius ) {
  19973. const vertex = new Vector3();
  19974. // iterate over the entire buffer and apply the radius to each vertex
  19975. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19976. vertex.x = vertexBuffer[ i + 0 ];
  19977. vertex.y = vertexBuffer[ i + 1 ];
  19978. vertex.z = vertexBuffer[ i + 2 ];
  19979. vertex.normalize().multiplyScalar( radius );
  19980. vertexBuffer[ i + 0 ] = vertex.x;
  19981. vertexBuffer[ i + 1 ] = vertex.y;
  19982. vertexBuffer[ i + 2 ] = vertex.z;
  19983. }
  19984. }
  19985. function generateUVs() {
  19986. const vertex = new Vector3();
  19987. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19988. vertex.x = vertexBuffer[ i + 0 ];
  19989. vertex.y = vertexBuffer[ i + 1 ];
  19990. vertex.z = vertexBuffer[ i + 2 ];
  19991. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19992. const v = inclination( vertex ) / Math.PI + 0.5;
  19993. uvBuffer.push( u, 1 - v );
  19994. }
  19995. correctUVs();
  19996. correctSeam();
  19997. }
  19998. function correctSeam() {
  19999. // handle case when face straddles the seam, see #3269
  20000. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20001. // uv data of a single face
  20002. const x0 = uvBuffer[ i + 0 ];
  20003. const x1 = uvBuffer[ i + 2 ];
  20004. const x2 = uvBuffer[ i + 4 ];
  20005. const max = Math.max( x0, x1, x2 );
  20006. const min = Math.min( x0, x1, x2 );
  20007. // 0.9 is somewhat arbitrary
  20008. if ( max > 0.9 && min < 0.1 ) {
  20009. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20010. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20011. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20012. }
  20013. }
  20014. }
  20015. function pushVertex( vertex ) {
  20016. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20017. }
  20018. function getVertexByIndex( index, vertex ) {
  20019. const stride = index * 3;
  20020. vertex.x = vertices[ stride + 0 ];
  20021. vertex.y = vertices[ stride + 1 ];
  20022. vertex.z = vertices[ stride + 2 ];
  20023. }
  20024. function correctUVs() {
  20025. const a = new Vector3();
  20026. const b = new Vector3();
  20027. const c = new Vector3();
  20028. const centroid = new Vector3();
  20029. const uvA = new Vector2();
  20030. const uvB = new Vector2();
  20031. const uvC = new Vector2();
  20032. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20033. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20034. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20035. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20036. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20037. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20038. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20039. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20040. const azi = azimuth( centroid );
  20041. correctUV( uvA, j + 0, a, azi );
  20042. correctUV( uvB, j + 2, b, azi );
  20043. correctUV( uvC, j + 4, c, azi );
  20044. }
  20045. }
  20046. function correctUV( uv, stride, vector, azimuth ) {
  20047. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20048. uvBuffer[ stride ] = uv.x - 1;
  20049. }
  20050. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20051. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20052. }
  20053. }
  20054. // Angle around the Y axis, counter-clockwise when looking from above.
  20055. function azimuth( vector ) {
  20056. return Math.atan2( vector.z, - vector.x );
  20057. }
  20058. // Angle above the XZ plane.
  20059. function inclination( vector ) {
  20060. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20061. }
  20062. }
  20063. copy( source ) {
  20064. super.copy( source );
  20065. this.parameters = Object.assign( {}, source.parameters );
  20066. return this;
  20067. }
  20068. /**
  20069. * Factory method for creating an instance of this class from the given
  20070. * JSON object.
  20071. *
  20072. * @param {Object} data - A JSON object representing the serialized geometry.
  20073. * @return {PolyhedronGeometry} A new instance.
  20074. */
  20075. static fromJSON( data ) {
  20076. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20077. }
  20078. }
  20079. /**
  20080. * A geometry class for representing a dodecahedron.
  20081. *
  20082. * ```js
  20083. * const geometry = new THREE.DodecahedronGeometry();
  20084. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  20085. * const dodecahedron = new THREE.Mesh( geometry, material );
  20086. * scene.add( dodecahedron );
  20087. * ```
  20088. *
  20089. * @augments PolyhedronGeometry
  20090. */
  20091. class DodecahedronGeometry extends PolyhedronGeometry {
  20092. /**
  20093. * Constructs a new dodecahedron geometry.
  20094. *
  20095. * @param {number} [radius=1] - Radius of the dodecahedron.
  20096. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  20097. */
  20098. constructor( radius = 1, detail = 0 ) {
  20099. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20100. const r = 1 / t;
  20101. const vertices = [
  20102. // (±1, ±1, ±1)
  20103. -1, -1, -1, -1, -1, 1,
  20104. -1, 1, -1, -1, 1, 1,
  20105. 1, -1, -1, 1, -1, 1,
  20106. 1, 1, -1, 1, 1, 1,
  20107. // (0, ±1/φ, ±φ)
  20108. 0, - r, - t, 0, - r, t,
  20109. 0, r, - t, 0, r, t,
  20110. // (±1/φ, ±φ, 0)
  20111. - r, - t, 0, - r, t, 0,
  20112. r, - t, 0, r, t, 0,
  20113. // (±φ, 0, ±1/φ)
  20114. - t, 0, - r, t, 0, - r,
  20115. - t, 0, r, t, 0, r
  20116. ];
  20117. const indices = [
  20118. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20119. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20120. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20121. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20122. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20123. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20124. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20125. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20126. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20127. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20128. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20129. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20130. ];
  20131. super( vertices, indices, radius, detail );
  20132. this.type = 'DodecahedronGeometry';
  20133. /**
  20134. * Holds the constructor parameters that have been
  20135. * used to generate the geometry. Any modification
  20136. * after instantiation does not change the geometry.
  20137. *
  20138. * @type {Object}
  20139. */
  20140. this.parameters = {
  20141. radius: radius,
  20142. detail: detail
  20143. };
  20144. }
  20145. /**
  20146. * Factory method for creating an instance of this class from the given
  20147. * JSON object.
  20148. *
  20149. * @param {Object} data - A JSON object representing the serialized geometry.
  20150. * @return {DodecahedronGeometry} A new instance.
  20151. */
  20152. static fromJSON( data ) {
  20153. return new DodecahedronGeometry( data.radius, data.detail );
  20154. }
  20155. }
  20156. const _v0 = /*@__PURE__*/ new Vector3();
  20157. const _v1$1 = /*@__PURE__*/ new Vector3();
  20158. const _normal = /*@__PURE__*/ new Vector3();
  20159. const _triangle = /*@__PURE__*/ new Triangle();
  20160. /**
  20161. * Can be used as a helper object to view the edges of a geometry.
  20162. *
  20163. * ```js
  20164. * const geometry = new THREE.BoxGeometry();
  20165. * const edges = new THREE.EdgesGeometry( geometry );
  20166. * const line = new THREE.LineSegments( edges );
  20167. * scene.add( line );
  20168. * ```
  20169. *
  20170. * Note: It is not yet possible to serialize/deserialize instances of this class.
  20171. *
  20172. * @augments BufferGeometry
  20173. */
  20174. class EdgesGeometry extends BufferGeometry {
  20175. /**
  20176. * Constructs a new edges geometry.
  20177. *
  20178. * @param {?BufferGeometry} [geometry=null] - The geometry.
  20179. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  20180. * between the face normals of the adjoining faces exceeds this value.
  20181. */
  20182. constructor( geometry = null, thresholdAngle = 1 ) {
  20183. super();
  20184. this.type = 'EdgesGeometry';
  20185. /**
  20186. * Holds the constructor parameters that have been
  20187. * used to generate the geometry. Any modification
  20188. * after instantiation does not change the geometry.
  20189. *
  20190. * @type {Object}
  20191. */
  20192. this.parameters = {
  20193. geometry: geometry,
  20194. thresholdAngle: thresholdAngle
  20195. };
  20196. if ( geometry !== null ) {
  20197. const precisionPoints = 4;
  20198. const precision = Math.pow( 10, precisionPoints );
  20199. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20200. const indexAttr = geometry.getIndex();
  20201. const positionAttr = geometry.getAttribute( 'position' );
  20202. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20203. const indexArr = [ 0, 0, 0 ];
  20204. const vertKeys = [ 'a', 'b', 'c' ];
  20205. const hashes = new Array( 3 );
  20206. const edgeData = {};
  20207. const vertices = [];
  20208. for ( let i = 0; i < indexCount; i += 3 ) {
  20209. if ( indexAttr ) {
  20210. indexArr[ 0 ] = indexAttr.getX( i );
  20211. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20212. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20213. } else {
  20214. indexArr[ 0 ] = i;
  20215. indexArr[ 1 ] = i + 1;
  20216. indexArr[ 2 ] = i + 2;
  20217. }
  20218. const { a, b, c } = _triangle;
  20219. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20220. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20221. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20222. _triangle.getNormal( _normal );
  20223. // create hashes for the edge from the vertices
  20224. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20225. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20226. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20227. // skip degenerate triangles
  20228. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20229. continue;
  20230. }
  20231. // iterate over every edge
  20232. for ( let j = 0; j < 3; j ++ ) {
  20233. // get the first and next vertex making up the edge
  20234. const jNext = ( j + 1 ) % 3;
  20235. const vecHash0 = hashes[ j ];
  20236. const vecHash1 = hashes[ jNext ];
  20237. const v0 = _triangle[ vertKeys[ j ] ];
  20238. const v1 = _triangle[ vertKeys[ jNext ] ];
  20239. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20240. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20241. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20242. // if we found a sibling edge add it into the vertex array if
  20243. // it meets the angle threshold and delete the edge from the map.
  20244. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20245. vertices.push( v0.x, v0.y, v0.z );
  20246. vertices.push( v1.x, v1.y, v1.z );
  20247. }
  20248. edgeData[ reverseHash ] = null;
  20249. } else if ( ! ( hash in edgeData ) ) {
  20250. // if we've already got an edge here then skip adding a new one
  20251. edgeData[ hash ] = {
  20252. index0: indexArr[ j ],
  20253. index1: indexArr[ jNext ],
  20254. normal: _normal.clone(),
  20255. };
  20256. }
  20257. }
  20258. }
  20259. // iterate over all remaining, unmatched edges and add them to the vertex array
  20260. for ( const key in edgeData ) {
  20261. if ( edgeData[ key ] ) {
  20262. const { index0, index1 } = edgeData[ key ];
  20263. _v0.fromBufferAttribute( positionAttr, index0 );
  20264. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20265. vertices.push( _v0.x, _v0.y, _v0.z );
  20266. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20267. }
  20268. }
  20269. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20270. }
  20271. }
  20272. copy( source ) {
  20273. super.copy( source );
  20274. this.parameters = Object.assign( {}, source.parameters );
  20275. return this;
  20276. }
  20277. }
  20278. /**
  20279. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  20280. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  20281. * points, or to get triangulated faces.
  20282. *
  20283. * ```js
  20284. * const heartShape = new THREE.Shape();
  20285. *
  20286. * heartShape.moveTo( 25, 25 );
  20287. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  20288. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  20289. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  20290. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  20291. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  20292. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  20293. *
  20294. * const extrudeSettings = {
  20295. * depth: 8,
  20296. * bevelEnabled: true,
  20297. * bevelSegments: 2,
  20298. * steps: 2,
  20299. * bevelSize: 1,
  20300. * bevelThickness: 1
  20301. * };
  20302. *
  20303. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  20304. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  20305. * ```
  20306. *
  20307. * @augments Path
  20308. */
  20309. class Shape extends Path {
  20310. /**
  20311. * Constructs a new shape.
  20312. *
  20313. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  20314. */
  20315. constructor( points ) {
  20316. super( points );
  20317. /**
  20318. * The UUID of the shape.
  20319. *
  20320. * @type {string}
  20321. * @readonly
  20322. */
  20323. this.uuid = generateUUID();
  20324. this.type = 'Shape';
  20325. /**
  20326. * Defines the holes in the shape. Hole definitions must use the
  20327. * opposite winding order (CW/CCW) than the outer shape.
  20328. *
  20329. * @type {Array<Path>}
  20330. * @readonly
  20331. */
  20332. this.holes = [];
  20333. }
  20334. /**
  20335. * Returns an array representing each contour of the holes
  20336. * as a list of 2D points.
  20337. *
  20338. * @param {number} divisions - The fineness of the result.
  20339. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  20340. */
  20341. getPointsHoles( divisions ) {
  20342. const holesPts = [];
  20343. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20344. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20345. }
  20346. return holesPts;
  20347. }
  20348. // get points of shape and holes (keypoints based on segments parameter)
  20349. /**
  20350. * Returns an object that holds contour data for the shape and its holes as
  20351. * arrays of 2D points.
  20352. *
  20353. * @param {number} divisions - The fineness of the result.
  20354. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  20355. */
  20356. extractPoints( divisions ) {
  20357. return {
  20358. shape: this.getPoints( divisions ),
  20359. holes: this.getPointsHoles( divisions )
  20360. };
  20361. }
  20362. copy( source ) {
  20363. super.copy( source );
  20364. this.holes = [];
  20365. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20366. const hole = source.holes[ i ];
  20367. this.holes.push( hole.clone() );
  20368. }
  20369. return this;
  20370. }
  20371. toJSON() {
  20372. const data = super.toJSON();
  20373. data.uuid = this.uuid;
  20374. data.holes = [];
  20375. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20376. const hole = this.holes[ i ];
  20377. data.holes.push( hole.toJSON() );
  20378. }
  20379. return data;
  20380. }
  20381. fromJSON( json ) {
  20382. super.fromJSON( json );
  20383. this.uuid = json.uuid;
  20384. this.holes = [];
  20385. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20386. const hole = json.holes[ i ];
  20387. this.holes.push( new Path().fromJSON( hole ) );
  20388. }
  20389. return this;
  20390. }
  20391. }
  20392. /**
  20393. * An implementation of the earcut polygon triangulation algorithm. The code
  20394. * is a port of [mapbox/earcut]{@link https://github.com/mapbox/earcut mapbox/earcut} (v2.2.4).
  20395. *
  20396. * @hideconstructor
  20397. */
  20398. class Earcut {
  20399. /**
  20400. * Triangulates the given shape definition by returning an array of triangles.
  20401. *
  20402. * @param {Array<number>} data - An array with 2D points.
  20403. * @param {Array<number>} holeIndices - An array with indices defining holes.
  20404. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  20405. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  20406. * representing vertex indices.
  20407. */
  20408. static triangulate( data, holeIndices, dim = 2 ) {
  20409. const hasHoles = holeIndices && holeIndices.length;
  20410. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20411. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20412. const triangles = [];
  20413. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20414. let minX, minY, maxX, maxY, x, y, invSize;
  20415. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20416. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20417. if ( data.length > 80 * dim ) {
  20418. minX = maxX = data[ 0 ];
  20419. minY = maxY = data[ 1 ];
  20420. for ( let i = dim; i < outerLen; i += dim ) {
  20421. x = data[ i ];
  20422. y = data[ i + 1 ];
  20423. if ( x < minX ) minX = x;
  20424. if ( y < minY ) minY = y;
  20425. if ( x > maxX ) maxX = x;
  20426. if ( y > maxY ) maxY = y;
  20427. }
  20428. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20429. invSize = Math.max( maxX - minX, maxY - minY );
  20430. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20431. }
  20432. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20433. return triangles;
  20434. }
  20435. }
  20436. // create a circular doubly linked list from polygon points in the specified winding order
  20437. function linkedList( data, start, end, dim, clockwise ) {
  20438. let i, last;
  20439. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20440. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20441. } else {
  20442. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20443. }
  20444. if ( last && equals( last, last.next ) ) {
  20445. removeNode( last );
  20446. last = last.next;
  20447. }
  20448. return last;
  20449. }
  20450. // eliminate colinear or duplicate points
  20451. function filterPoints( start, end ) {
  20452. if ( ! start ) return start;
  20453. if ( ! end ) end = start;
  20454. let p = start,
  20455. again;
  20456. do {
  20457. again = false;
  20458. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20459. removeNode( p );
  20460. p = end = p.prev;
  20461. if ( p === p.next ) break;
  20462. again = true;
  20463. } else {
  20464. p = p.next;
  20465. }
  20466. } while ( again || p !== end );
  20467. return end;
  20468. }
  20469. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20470. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20471. if ( ! ear ) return;
  20472. // interlink polygon nodes in z-order
  20473. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20474. let stop = ear,
  20475. prev, next;
  20476. // iterate through ears, slicing them one by one
  20477. while ( ear.prev !== ear.next ) {
  20478. prev = ear.prev;
  20479. next = ear.next;
  20480. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20481. // cut off the triangle
  20482. triangles.push( prev.i / dim | 0 );
  20483. triangles.push( ear.i / dim | 0 );
  20484. triangles.push( next.i / dim | 0 );
  20485. removeNode( ear );
  20486. // skipping the next vertex leads to less sliver triangles
  20487. ear = next.next;
  20488. stop = next.next;
  20489. continue;
  20490. }
  20491. ear = next;
  20492. // if we looped through the whole remaining polygon and can't find any more ears
  20493. if ( ear === stop ) {
  20494. // try filtering points and slicing again
  20495. if ( ! pass ) {
  20496. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20497. // if this didn't work, try curing all small self-intersections locally
  20498. } else if ( pass === 1 ) {
  20499. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20500. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20501. // as a last resort, try splitting the remaining polygon into two
  20502. } else if ( pass === 2 ) {
  20503. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20504. }
  20505. break;
  20506. }
  20507. }
  20508. }
  20509. // check whether a polygon node forms a valid ear with adjacent nodes
  20510. function isEar( ear ) {
  20511. const a = ear.prev,
  20512. b = ear,
  20513. c = ear.next;
  20514. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20515. // now make sure we don't have other points inside the potential ear
  20516. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20517. // triangle bbox; min & max are calculated like this for speed
  20518. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20519. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20520. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20521. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20522. let p = c.next;
  20523. while ( p !== a ) {
  20524. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20525. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20526. area( p.prev, p, p.next ) >= 0 ) return false;
  20527. p = p.next;
  20528. }
  20529. return true;
  20530. }
  20531. function isEarHashed( ear, minX, minY, invSize ) {
  20532. const a = ear.prev,
  20533. b = ear,
  20534. c = ear.next;
  20535. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20536. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20537. // triangle bbox; min & max are calculated like this for speed
  20538. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20539. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20540. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20541. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20542. // z-order range for the current triangle bbox;
  20543. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20544. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20545. let p = ear.prevZ,
  20546. n = ear.nextZ;
  20547. // look for points inside the triangle in both directions
  20548. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20549. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20550. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20551. p = p.prevZ;
  20552. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20553. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20554. n = n.nextZ;
  20555. }
  20556. // look for remaining points in decreasing z-order
  20557. while ( p && p.z >= minZ ) {
  20558. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20559. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20560. p = p.prevZ;
  20561. }
  20562. // look for remaining points in increasing z-order
  20563. while ( n && n.z <= maxZ ) {
  20564. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20565. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20566. n = n.nextZ;
  20567. }
  20568. return true;
  20569. }
  20570. // go through all polygon nodes and cure small local self-intersections
  20571. function cureLocalIntersections( start, triangles, dim ) {
  20572. let p = start;
  20573. do {
  20574. const a = p.prev,
  20575. b = p.next.next;
  20576. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20577. triangles.push( a.i / dim | 0 );
  20578. triangles.push( p.i / dim | 0 );
  20579. triangles.push( b.i / dim | 0 );
  20580. // remove two nodes involved
  20581. removeNode( p );
  20582. removeNode( p.next );
  20583. p = start = b;
  20584. }
  20585. p = p.next;
  20586. } while ( p !== start );
  20587. return filterPoints( p );
  20588. }
  20589. // try splitting polygon into two and triangulate them independently
  20590. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20591. // look for a valid diagonal that divides the polygon into two
  20592. let a = start;
  20593. do {
  20594. let b = a.next.next;
  20595. while ( b !== a.prev ) {
  20596. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20597. // split the polygon in two by the diagonal
  20598. let c = splitPolygon( a, b );
  20599. // filter colinear points around the cuts
  20600. a = filterPoints( a, a.next );
  20601. c = filterPoints( c, c.next );
  20602. // run earcut on each half
  20603. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20604. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20605. return;
  20606. }
  20607. b = b.next;
  20608. }
  20609. a = a.next;
  20610. } while ( a !== start );
  20611. }
  20612. // link every hole into the outer loop, producing a single-ring polygon without holes
  20613. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20614. const queue = [];
  20615. let i, len, start, end, list;
  20616. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20617. start = holeIndices[ i ] * dim;
  20618. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20619. list = linkedList( data, start, end, dim, false );
  20620. if ( list === list.next ) list.steiner = true;
  20621. queue.push( getLeftmost( list ) );
  20622. }
  20623. queue.sort( compareX );
  20624. // process holes from left to right
  20625. for ( i = 0; i < queue.length; i ++ ) {
  20626. outerNode = eliminateHole( queue[ i ], outerNode );
  20627. }
  20628. return outerNode;
  20629. }
  20630. function compareX( a, b ) {
  20631. return a.x - b.x;
  20632. }
  20633. // find a bridge between vertices that connects hole with an outer ring and link it
  20634. function eliminateHole( hole, outerNode ) {
  20635. const bridge = findHoleBridge( hole, outerNode );
  20636. if ( ! bridge ) {
  20637. return outerNode;
  20638. }
  20639. const bridgeReverse = splitPolygon( bridge, hole );
  20640. // filter collinear points around the cuts
  20641. filterPoints( bridgeReverse, bridgeReverse.next );
  20642. return filterPoints( bridge, bridge.next );
  20643. }
  20644. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20645. function findHoleBridge( hole, outerNode ) {
  20646. let p = outerNode,
  20647. qx = - Infinity,
  20648. m;
  20649. const hx = hole.x, hy = hole.y;
  20650. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20651. // segment's endpoint with lesser x will be potential connection point
  20652. do {
  20653. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20654. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20655. if ( x <= hx && x > qx ) {
  20656. qx = x;
  20657. m = p.x < p.next.x ? p : p.next;
  20658. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20659. }
  20660. }
  20661. p = p.next;
  20662. } while ( p !== outerNode );
  20663. if ( ! m ) return null;
  20664. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20665. // if there are no points found, we have a valid connection;
  20666. // otherwise choose the point of the minimum angle with the ray as connection point
  20667. const stop = m,
  20668. mx = m.x,
  20669. my = m.y;
  20670. let tanMin = Infinity, tan;
  20671. p = m;
  20672. do {
  20673. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20674. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20675. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20676. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20677. m = p;
  20678. tanMin = tan;
  20679. }
  20680. }
  20681. p = p.next;
  20682. } while ( p !== stop );
  20683. return m;
  20684. }
  20685. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20686. function sectorContainsSector( m, p ) {
  20687. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20688. }
  20689. // interlink polygon nodes in z-order
  20690. function indexCurve( start, minX, minY, invSize ) {
  20691. let p = start;
  20692. do {
  20693. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20694. p.prevZ = p.prev;
  20695. p.nextZ = p.next;
  20696. p = p.next;
  20697. } while ( p !== start );
  20698. p.prevZ.nextZ = null;
  20699. p.prevZ = null;
  20700. sortLinked( p );
  20701. }
  20702. // Simon Tatham's linked list merge sort algorithm
  20703. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20704. function sortLinked( list ) {
  20705. let i, p, q, e, tail, numMerges, pSize, qSize,
  20706. inSize = 1;
  20707. do {
  20708. p = list;
  20709. list = null;
  20710. tail = null;
  20711. numMerges = 0;
  20712. while ( p ) {
  20713. numMerges ++;
  20714. q = p;
  20715. pSize = 0;
  20716. for ( i = 0; i < inSize; i ++ ) {
  20717. pSize ++;
  20718. q = q.nextZ;
  20719. if ( ! q ) break;
  20720. }
  20721. qSize = inSize;
  20722. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20723. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20724. e = p;
  20725. p = p.nextZ;
  20726. pSize --;
  20727. } else {
  20728. e = q;
  20729. q = q.nextZ;
  20730. qSize --;
  20731. }
  20732. if ( tail ) tail.nextZ = e;
  20733. else list = e;
  20734. e.prevZ = tail;
  20735. tail = e;
  20736. }
  20737. p = q;
  20738. }
  20739. tail.nextZ = null;
  20740. inSize *= 2;
  20741. } while ( numMerges > 1 );
  20742. return list;
  20743. }
  20744. // z-order of a point given coords and inverse of the longer side of data bbox
  20745. function zOrder( x, y, minX, minY, invSize ) {
  20746. // coords are transformed into non-negative 15-bit integer range
  20747. x = ( x - minX ) * invSize | 0;
  20748. y = ( y - minY ) * invSize | 0;
  20749. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20750. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20751. x = ( x | ( x << 2 ) ) & 0x33333333;
  20752. x = ( x | ( x << 1 ) ) & 0x55555555;
  20753. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20754. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20755. y = ( y | ( y << 2 ) ) & 0x33333333;
  20756. y = ( y | ( y << 1 ) ) & 0x55555555;
  20757. return x | ( y << 1 );
  20758. }
  20759. // find the leftmost node of a polygon ring
  20760. function getLeftmost( start ) {
  20761. let p = start,
  20762. leftmost = start;
  20763. do {
  20764. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20765. p = p.next;
  20766. } while ( p !== start );
  20767. return leftmost;
  20768. }
  20769. // check if a point lies within a convex triangle
  20770. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20771. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20772. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20773. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20774. }
  20775. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20776. function isValidDiagonal( a, b ) {
  20777. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  20778. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20779. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20780. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20781. }
  20782. // signed area of a triangle
  20783. function area( p, q, r ) {
  20784. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20785. }
  20786. // check if two points are equal
  20787. function equals( p1, p2 ) {
  20788. return p1.x === p2.x && p1.y === p2.y;
  20789. }
  20790. // check if two segments intersect
  20791. function intersects( p1, q1, p2, q2 ) {
  20792. const o1 = sign( area( p1, q1, p2 ) );
  20793. const o2 = sign( area( p1, q1, q2 ) );
  20794. const o3 = sign( area( p2, q2, p1 ) );
  20795. const o4 = sign( area( p2, q2, q1 ) );
  20796. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20797. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20798. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20799. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20800. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20801. return false;
  20802. }
  20803. // for collinear points p, q, r, check if point q lies on segment pr
  20804. function onSegment( p, q, r ) {
  20805. 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 );
  20806. }
  20807. function sign( num ) {
  20808. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20809. }
  20810. // check if a polygon diagonal intersects any polygon segments
  20811. function intersectsPolygon( a, b ) {
  20812. let p = a;
  20813. do {
  20814. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20815. intersects( p, p.next, a, b ) ) return true;
  20816. p = p.next;
  20817. } while ( p !== a );
  20818. return false;
  20819. }
  20820. // check if a polygon diagonal is locally inside the polygon
  20821. function locallyInside( a, b ) {
  20822. return area( a.prev, a, a.next ) < 0 ?
  20823. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20824. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20825. }
  20826. // check if the middle point of a polygon diagonal is inside the polygon
  20827. function middleInside( a, b ) {
  20828. let p = a,
  20829. inside = false;
  20830. const px = ( a.x + b.x ) / 2,
  20831. py = ( a.y + b.y ) / 2;
  20832. do {
  20833. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20834. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20835. inside = ! inside;
  20836. p = p.next;
  20837. } while ( p !== a );
  20838. return inside;
  20839. }
  20840. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20841. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20842. function splitPolygon( a, b ) {
  20843. const a2 = new Node( a.i, a.x, a.y ),
  20844. b2 = new Node( b.i, b.x, b.y ),
  20845. an = a.next,
  20846. bp = b.prev;
  20847. a.next = b;
  20848. b.prev = a;
  20849. a2.next = an;
  20850. an.prev = a2;
  20851. b2.next = a2;
  20852. a2.prev = b2;
  20853. bp.next = b2;
  20854. b2.prev = bp;
  20855. return b2;
  20856. }
  20857. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20858. function insertNode( i, x, y, last ) {
  20859. const p = new Node( i, x, y );
  20860. if ( ! last ) {
  20861. p.prev = p;
  20862. p.next = p;
  20863. } else {
  20864. p.next = last.next;
  20865. p.prev = last;
  20866. last.next.prev = p;
  20867. last.next = p;
  20868. }
  20869. return p;
  20870. }
  20871. function removeNode( p ) {
  20872. p.next.prev = p.prev;
  20873. p.prev.next = p.next;
  20874. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20875. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20876. }
  20877. function Node( i, x, y ) {
  20878. // vertex index in coordinates array
  20879. this.i = i;
  20880. // vertex coordinates
  20881. this.x = x;
  20882. this.y = y;
  20883. // previous and next vertex nodes in a polygon ring
  20884. this.prev = null;
  20885. this.next = null;
  20886. // z-order curve value
  20887. this.z = 0;
  20888. // previous and next nodes in z-order
  20889. this.prevZ = null;
  20890. this.nextZ = null;
  20891. // indicates whether this is a steiner point
  20892. this.steiner = false;
  20893. }
  20894. function signedArea( data, start, end, dim ) {
  20895. let sum = 0;
  20896. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20897. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20898. j = i;
  20899. }
  20900. return sum;
  20901. }
  20902. /**
  20903. * A class containing utility functions for shapes.
  20904. *
  20905. * @hideconstructor
  20906. */
  20907. class ShapeUtils {
  20908. /**
  20909. * Calculate area of a ( 2D ) contour polygon.
  20910. *
  20911. * @param {Array<Vector2>} contour - An array of 2D points.
  20912. * @return {number} The area.
  20913. */
  20914. static area( contour ) {
  20915. const n = contour.length;
  20916. let a = 0.0;
  20917. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20918. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20919. }
  20920. return a * 0.5;
  20921. }
  20922. /**
  20923. * Returns `true` if the given contour uses a clockwise winding order.
  20924. *
  20925. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  20926. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  20927. */
  20928. static isClockWise( pts ) {
  20929. return ShapeUtils.area( pts ) < 0;
  20930. }
  20931. /**
  20932. * Triangulates the given shape definition.
  20933. *
  20934. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  20935. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  20936. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  20937. */
  20938. static triangulateShape( contour, holes ) {
  20939. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20940. const holeIndices = []; // array of hole indices
  20941. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20942. removeDupEndPts( contour );
  20943. addContour( vertices, contour );
  20944. //
  20945. let holeIndex = contour.length;
  20946. holes.forEach( removeDupEndPts );
  20947. for ( let i = 0; i < holes.length; i ++ ) {
  20948. holeIndices.push( holeIndex );
  20949. holeIndex += holes[ i ].length;
  20950. addContour( vertices, holes[ i ] );
  20951. }
  20952. //
  20953. const triangles = Earcut.triangulate( vertices, holeIndices );
  20954. //
  20955. for ( let i = 0; i < triangles.length; i += 3 ) {
  20956. faces.push( triangles.slice( i, i + 3 ) );
  20957. }
  20958. return faces;
  20959. }
  20960. }
  20961. function removeDupEndPts( points ) {
  20962. const l = points.length;
  20963. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20964. points.pop();
  20965. }
  20966. }
  20967. function addContour( vertices, contour ) {
  20968. for ( let i = 0; i < contour.length; i ++ ) {
  20969. vertices.push( contour[ i ].x );
  20970. vertices.push( contour[ i ].y );
  20971. }
  20972. }
  20973. /**
  20974. * Creates extruded geometry from a path shape.
  20975. *
  20976. * parameters = {
  20977. *
  20978. * curveSegments: <int>, // number of points on the curves
  20979. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20980. * depth: <float>, // Depth to extrude the shape
  20981. *
  20982. * bevelEnabled: <bool>, // turn on bevel
  20983. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20984. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20985. * bevelOffset: <float>, // how far from shape outline does bevel start
  20986. * bevelSegments: <int>, // number of bevel layers
  20987. *
  20988. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20989. *
  20990. * UVGenerator: <Object> // object that provides UV generator functions
  20991. *
  20992. * }
  20993. */
  20994. /**
  20995. * Creates extruded geometry from a path shape.
  20996. *
  20997. * ```js
  20998. * const length = 12, width = 8;
  20999. *
  21000. * const shape = new THREE.Shape();
  21001. * shape.moveTo( 0,0 );
  21002. * shape.lineTo( 0, width );
  21003. * shape.lineTo( length, width );
  21004. * shape.lineTo( length, 0 );
  21005. * shape.lineTo( 0, 0 );
  21006. *
  21007. * const geometry = new THREE.ExtrudeGeometry( shape );
  21008. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  21009. * const mesh = new THREE.Mesh( geometry, material ) ;
  21010. * scene.add( mesh );
  21011. * ```
  21012. *
  21013. * @augments BufferGeometry
  21014. */
  21015. class ExtrudeGeometry extends BufferGeometry {
  21016. /**
  21017. * Constructs a new extrude geometry.
  21018. *
  21019. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  21020. * @param {Object} [options={}] - The extrude settings.
  21021. * @param {number} [options.curveSegments=12] - Number of points on the curves.
  21022. * @param {number} [options.steps=1] - Number of points used for subdividing segments along the depth of the extruded spline.
  21023. * @param {number} [options.depth=1] - Depth to extrude the shape.
  21024. * @param {boolean} [options.bevelEnabled=true] - Whether to beveling to the shape or not.
  21025. * @param {number} [options.bevelThickness=0.2] - How deep into the original shape the bevel goes.
  21026. * @param {number} [options.bevelSize=bevelThickness-0.1] - Distance from the shape outline that the bevel extends.
  21027. * @param {number} [options.bevelOffset=0] - Distance from the shape outline that the bevel starts.
  21028. * @param {number} [options.bevelSegments=3] - Number of bevel layers.
  21029. * @param {Curve} [options.extrudePath=3] - A 3D spline path along which the shape should be extruded. Bevels not supported for path extrusion.
  21030. * @param {Object} [options.UVGenerator] - An object that provides UV generator functions for custom UV generation.
  21031. */
  21032. 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 = {} ) {
  21033. super();
  21034. this.type = 'ExtrudeGeometry';
  21035. /**
  21036. * Holds the constructor parameters that have been
  21037. * used to generate the geometry. Any modification
  21038. * after instantiation does not change the geometry.
  21039. *
  21040. * @type {Object}
  21041. */
  21042. this.parameters = {
  21043. shapes: shapes,
  21044. options: options
  21045. };
  21046. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21047. const scope = this;
  21048. const verticesArray = [];
  21049. const uvArray = [];
  21050. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21051. const shape = shapes[ i ];
  21052. addShape( shape );
  21053. }
  21054. // build geometry
  21055. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21056. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21057. this.computeVertexNormals();
  21058. // functions
  21059. function addShape( shape ) {
  21060. const placeholder = [];
  21061. // options
  21062. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21063. const steps = options.steps !== undefined ? options.steps : 1;
  21064. const depth = options.depth !== undefined ? options.depth : 1;
  21065. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21066. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21067. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21068. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21069. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21070. const extrudePath = options.extrudePath;
  21071. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21072. //
  21073. let extrudePts, extrudeByPath = false;
  21074. let splineTube, binormal, normal, position2;
  21075. if ( extrudePath ) {
  21076. extrudePts = extrudePath.getSpacedPoints( steps );
  21077. extrudeByPath = true;
  21078. bevelEnabled = false; // bevels not supported for path extrusion
  21079. // SETUP TNB variables
  21080. // TODO1 - have a .isClosed in spline?
  21081. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21082. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21083. binormal = new Vector3();
  21084. normal = new Vector3();
  21085. position2 = new Vector3();
  21086. }
  21087. // Safeguards if bevels are not enabled
  21088. if ( ! bevelEnabled ) {
  21089. bevelSegments = 0;
  21090. bevelThickness = 0;
  21091. bevelSize = 0;
  21092. bevelOffset = 0;
  21093. }
  21094. // Variables initialization
  21095. const shapePoints = shape.extractPoints( curveSegments );
  21096. let vertices = shapePoints.shape;
  21097. const holes = shapePoints.holes;
  21098. const reverse = ! ShapeUtils.isClockWise( vertices );
  21099. if ( reverse ) {
  21100. vertices = vertices.reverse();
  21101. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21102. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21103. const ahole = holes[ h ];
  21104. if ( ShapeUtils.isClockWise( ahole ) ) {
  21105. holes[ h ] = ahole.reverse();
  21106. }
  21107. }
  21108. }
  21109. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21110. /* Vertices */
  21111. const contour = vertices; // vertices has all points but contour has only points of circumference
  21112. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21113. const ahole = holes[ h ];
  21114. vertices = vertices.concat( ahole );
  21115. }
  21116. function scalePt2( pt, vec, size ) {
  21117. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21118. return pt.clone().addScaledVector( vec, size );
  21119. }
  21120. const vlen = vertices.length, flen = faces.length;
  21121. // Find directions for point movement
  21122. function getBevelVec( inPt, inPrev, inNext ) {
  21123. // computes for inPt the corresponding point inPt' on a new contour
  21124. // shifted by 1 unit (length of normalized vector) to the left
  21125. // if we walk along contour clockwise, this new contour is outside the old one
  21126. //
  21127. // inPt' is the intersection of the two lines parallel to the two
  21128. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21129. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21130. // good reading for geometry algorithms (here: line-line intersection)
  21131. // http://geomalgorithms.com/a05-_intersect-1.html
  21132. const v_prev_x = inPt.x - inPrev.x,
  21133. v_prev_y = inPt.y - inPrev.y;
  21134. const v_next_x = inNext.x - inPt.x,
  21135. v_next_y = inNext.y - inPt.y;
  21136. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21137. // check for collinear edges
  21138. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21139. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21140. // not collinear
  21141. // length of vectors for normalizing
  21142. const v_prev_len = Math.sqrt( v_prev_lensq );
  21143. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21144. // shift adjacent points by unit vectors to the left
  21145. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21146. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21147. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21148. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21149. // scaling factor for v_prev to intersection point
  21150. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21151. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21152. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21153. // vector from inPt to intersection point
  21154. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21155. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21156. // Don't normalize!, otherwise sharp corners become ugly
  21157. // but prevent crazy spikes
  21158. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21159. if ( v_trans_lensq <= 2 ) {
  21160. return new Vector2( v_trans_x, v_trans_y );
  21161. } else {
  21162. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21163. }
  21164. } else {
  21165. // handle special case of collinear edges
  21166. let direction_eq = false; // assumes: opposite
  21167. if ( v_prev_x > Number.EPSILON ) {
  21168. if ( v_next_x > Number.EPSILON ) {
  21169. direction_eq = true;
  21170. }
  21171. } else {
  21172. if ( v_prev_x < - Number.EPSILON ) {
  21173. if ( v_next_x < - Number.EPSILON ) {
  21174. direction_eq = true;
  21175. }
  21176. } else {
  21177. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21178. direction_eq = true;
  21179. }
  21180. }
  21181. }
  21182. if ( direction_eq ) {
  21183. // console.log("Warning: lines are a straight sequence");
  21184. v_trans_x = - v_prev_y;
  21185. v_trans_y = v_prev_x;
  21186. shrink_by = Math.sqrt( v_prev_lensq );
  21187. } else {
  21188. // console.log("Warning: lines are a straight spike");
  21189. v_trans_x = v_prev_x;
  21190. v_trans_y = v_prev_y;
  21191. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21192. }
  21193. }
  21194. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21195. }
  21196. const contourMovements = [];
  21197. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21198. if ( j === il ) j = 0;
  21199. if ( k === il ) k = 0;
  21200. // (j)---(i)---(k)
  21201. // console.log('i,j,k', i, j , k)
  21202. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21203. }
  21204. const holesMovements = [];
  21205. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21206. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21207. const ahole = holes[ h ];
  21208. oneHoleMovements = [];
  21209. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21210. if ( j === il ) j = 0;
  21211. if ( k === il ) k = 0;
  21212. // (j)---(i)---(k)
  21213. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21214. }
  21215. holesMovements.push( oneHoleMovements );
  21216. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21217. }
  21218. // Loop bevelSegments, 1 for the front, 1 for the back
  21219. for ( let b = 0; b < bevelSegments; b ++ ) {
  21220. //for ( b = bevelSegments; b > 0; b -- ) {
  21221. const t = b / bevelSegments;
  21222. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21223. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21224. // contract shape
  21225. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21226. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21227. v( vert.x, vert.y, - z );
  21228. }
  21229. // expand holes
  21230. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21231. const ahole = holes[ h ];
  21232. oneHoleMovements = holesMovements[ h ];
  21233. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21234. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21235. v( vert.x, vert.y, - z );
  21236. }
  21237. }
  21238. }
  21239. const bs = bevelSize + bevelOffset;
  21240. // Back facing vertices
  21241. for ( let i = 0; i < vlen; i ++ ) {
  21242. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21243. if ( ! extrudeByPath ) {
  21244. v( vert.x, vert.y, 0 );
  21245. } else {
  21246. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21247. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21248. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21249. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21250. v( position2.x, position2.y, position2.z );
  21251. }
  21252. }
  21253. // Add stepped vertices...
  21254. // Including front facing vertices
  21255. for ( let s = 1; s <= steps; s ++ ) {
  21256. for ( let i = 0; i < vlen; i ++ ) {
  21257. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21258. if ( ! extrudeByPath ) {
  21259. v( vert.x, vert.y, depth / steps * s );
  21260. } else {
  21261. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21262. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21263. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21264. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21265. v( position2.x, position2.y, position2.z );
  21266. }
  21267. }
  21268. }
  21269. // Add bevel segments planes
  21270. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21271. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21272. const t = b / bevelSegments;
  21273. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21274. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21275. // contract shape
  21276. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21277. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21278. v( vert.x, vert.y, depth + z );
  21279. }
  21280. // expand holes
  21281. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21282. const ahole = holes[ h ];
  21283. oneHoleMovements = holesMovements[ h ];
  21284. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21285. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21286. if ( ! extrudeByPath ) {
  21287. v( vert.x, vert.y, depth + z );
  21288. } else {
  21289. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21290. }
  21291. }
  21292. }
  21293. }
  21294. /* Faces */
  21295. // Top and bottom faces
  21296. buildLidFaces();
  21297. // Sides faces
  21298. buildSideFaces();
  21299. ///// Internal functions
  21300. function buildLidFaces() {
  21301. const start = verticesArray.length / 3;
  21302. if ( bevelEnabled ) {
  21303. let layer = 0; // steps + 1
  21304. let offset = vlen * layer;
  21305. // Bottom faces
  21306. for ( let i = 0; i < flen; i ++ ) {
  21307. const face = faces[ i ];
  21308. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21309. }
  21310. layer = steps + bevelSegments * 2;
  21311. offset = vlen * layer;
  21312. // Top faces
  21313. for ( let i = 0; i < flen; i ++ ) {
  21314. const face = faces[ i ];
  21315. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21316. }
  21317. } else {
  21318. // Bottom faces
  21319. for ( let i = 0; i < flen; i ++ ) {
  21320. const face = faces[ i ];
  21321. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21322. }
  21323. // Top faces
  21324. for ( let i = 0; i < flen; i ++ ) {
  21325. const face = faces[ i ];
  21326. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21327. }
  21328. }
  21329. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21330. }
  21331. // Create faces for the z-sides of the shape
  21332. function buildSideFaces() {
  21333. const start = verticesArray.length / 3;
  21334. let layeroffset = 0;
  21335. sidewalls( contour, layeroffset );
  21336. layeroffset += contour.length;
  21337. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21338. const ahole = holes[ h ];
  21339. sidewalls( ahole, layeroffset );
  21340. //, true
  21341. layeroffset += ahole.length;
  21342. }
  21343. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21344. }
  21345. function sidewalls( contour, layeroffset ) {
  21346. let i = contour.length;
  21347. while ( -- i >= 0 ) {
  21348. const j = i;
  21349. let k = i - 1;
  21350. if ( k < 0 ) k = contour.length - 1;
  21351. //console.log('b', i,j, i-1, k,vertices.length);
  21352. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21353. const slen1 = vlen * s;
  21354. const slen2 = vlen * ( s + 1 );
  21355. const a = layeroffset + j + slen1,
  21356. b = layeroffset + k + slen1,
  21357. c = layeroffset + k + slen2,
  21358. d = layeroffset + j + slen2;
  21359. f4( a, b, c, d );
  21360. }
  21361. }
  21362. }
  21363. function v( x, y, z ) {
  21364. placeholder.push( x );
  21365. placeholder.push( y );
  21366. placeholder.push( z );
  21367. }
  21368. function f3( a, b, c ) {
  21369. addVertex( a );
  21370. addVertex( b );
  21371. addVertex( c );
  21372. const nextIndex = verticesArray.length / 3;
  21373. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21374. addUV( uvs[ 0 ] );
  21375. addUV( uvs[ 1 ] );
  21376. addUV( uvs[ 2 ] );
  21377. }
  21378. function f4( a, b, c, d ) {
  21379. addVertex( a );
  21380. addVertex( b );
  21381. addVertex( d );
  21382. addVertex( b );
  21383. addVertex( c );
  21384. addVertex( d );
  21385. const nextIndex = verticesArray.length / 3;
  21386. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21387. addUV( uvs[ 0 ] );
  21388. addUV( uvs[ 1 ] );
  21389. addUV( uvs[ 3 ] );
  21390. addUV( uvs[ 1 ] );
  21391. addUV( uvs[ 2 ] );
  21392. addUV( uvs[ 3 ] );
  21393. }
  21394. function addVertex( index ) {
  21395. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21396. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21397. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21398. }
  21399. function addUV( vector2 ) {
  21400. uvArray.push( vector2.x );
  21401. uvArray.push( vector2.y );
  21402. }
  21403. }
  21404. }
  21405. copy( source ) {
  21406. super.copy( source );
  21407. this.parameters = Object.assign( {}, source.parameters );
  21408. return this;
  21409. }
  21410. toJSON() {
  21411. const data = super.toJSON();
  21412. const shapes = this.parameters.shapes;
  21413. const options = this.parameters.options;
  21414. return toJSON$1( shapes, options, data );
  21415. }
  21416. /**
  21417. * Factory method for creating an instance of this class from the given
  21418. * JSON object.
  21419. *
  21420. * @param {Object} data - A JSON object representing the serialized geometry.
  21421. * @param {Array<Shape>} shapes - An array of shapes.
  21422. * @return {ExtrudeGeometry} A new instance.
  21423. */
  21424. static fromJSON( data, shapes ) {
  21425. const geometryShapes = [];
  21426. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21427. const shape = shapes[ data.shapes[ j ] ];
  21428. geometryShapes.push( shape );
  21429. }
  21430. const extrudePath = data.options.extrudePath;
  21431. if ( extrudePath !== undefined ) {
  21432. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21433. }
  21434. return new ExtrudeGeometry( geometryShapes, data.options );
  21435. }
  21436. }
  21437. const WorldUVGenerator = {
  21438. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21439. const a_x = vertices[ indexA * 3 ];
  21440. const a_y = vertices[ indexA * 3 + 1 ];
  21441. const b_x = vertices[ indexB * 3 ];
  21442. const b_y = vertices[ indexB * 3 + 1 ];
  21443. const c_x = vertices[ indexC * 3 ];
  21444. const c_y = vertices[ indexC * 3 + 1 ];
  21445. return [
  21446. new Vector2( a_x, a_y ),
  21447. new Vector2( b_x, b_y ),
  21448. new Vector2( c_x, c_y )
  21449. ];
  21450. },
  21451. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21452. const a_x = vertices[ indexA * 3 ];
  21453. const a_y = vertices[ indexA * 3 + 1 ];
  21454. const a_z = vertices[ indexA * 3 + 2 ];
  21455. const b_x = vertices[ indexB * 3 ];
  21456. const b_y = vertices[ indexB * 3 + 1 ];
  21457. const b_z = vertices[ indexB * 3 + 2 ];
  21458. const c_x = vertices[ indexC * 3 ];
  21459. const c_y = vertices[ indexC * 3 + 1 ];
  21460. const c_z = vertices[ indexC * 3 + 2 ];
  21461. const d_x = vertices[ indexD * 3 ];
  21462. const d_y = vertices[ indexD * 3 + 1 ];
  21463. const d_z = vertices[ indexD * 3 + 2 ];
  21464. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21465. return [
  21466. new Vector2( a_x, 1 - a_z ),
  21467. new Vector2( b_x, 1 - b_z ),
  21468. new Vector2( c_x, 1 - c_z ),
  21469. new Vector2( d_x, 1 - d_z )
  21470. ];
  21471. } else {
  21472. return [
  21473. new Vector2( a_y, 1 - a_z ),
  21474. new Vector2( b_y, 1 - b_z ),
  21475. new Vector2( c_y, 1 - c_z ),
  21476. new Vector2( d_y, 1 - d_z )
  21477. ];
  21478. }
  21479. }
  21480. };
  21481. function toJSON$1( shapes, options, data ) {
  21482. data.shapes = [];
  21483. if ( Array.isArray( shapes ) ) {
  21484. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21485. const shape = shapes[ i ];
  21486. data.shapes.push( shape.uuid );
  21487. }
  21488. } else {
  21489. data.shapes.push( shapes.uuid );
  21490. }
  21491. data.options = Object.assign( {}, options );
  21492. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21493. return data;
  21494. }
  21495. /**
  21496. * A geometry class for representing an icosahedron.
  21497. *
  21498. * ```js
  21499. * const geometry = new THREE.IcosahedronGeometry();
  21500. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21501. * const icosahedron = new THREE.Mesh( geometry, material );
  21502. * scene.add( icosahedron );
  21503. * ```
  21504. *
  21505. * @augments PolyhedronGeometry
  21506. */
  21507. class IcosahedronGeometry extends PolyhedronGeometry {
  21508. /**
  21509. * Constructs a new icosahedron geometry.
  21510. *
  21511. * @param {number} [radius=1] - Radius of the icosahedron.
  21512. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  21513. */
  21514. constructor( radius = 1, detail = 0 ) {
  21515. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21516. const vertices = [
  21517. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  21518. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  21519. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  21520. ];
  21521. const indices = [
  21522. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21523. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21524. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21525. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21526. ];
  21527. super( vertices, indices, radius, detail );
  21528. this.type = 'IcosahedronGeometry';
  21529. /**
  21530. * Holds the constructor parameters that have been
  21531. * used to generate the geometry. Any modification
  21532. * after instantiation does not change the geometry.
  21533. *
  21534. * @type {Object}
  21535. */
  21536. this.parameters = {
  21537. radius: radius,
  21538. detail: detail
  21539. };
  21540. }
  21541. /**
  21542. * Factory method for creating an instance of this class from the given
  21543. * JSON object.
  21544. *
  21545. * @param {Object} data - A JSON object representing the serialized geometry.
  21546. * @return {IcosahedronGeometry} A new instance.
  21547. */
  21548. static fromJSON( data ) {
  21549. return new IcosahedronGeometry( data.radius, data.detail );
  21550. }
  21551. }
  21552. /**
  21553. * A geometry class for representing an octahedron.
  21554. *
  21555. * ```js
  21556. * const geometry = new THREE.OctahedronGeometry();
  21557. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21558. * const octahedron = new THREE.Mesh( geometry, material );
  21559. * scene.add( octahedron );
  21560. * ```
  21561. *
  21562. * @augments PolyhedronGeometry
  21563. */
  21564. class OctahedronGeometry extends PolyhedronGeometry {
  21565. /**
  21566. * Constructs a new octahedron geometry.
  21567. *
  21568. * @param {number} [radius=1] - Radius of the octahedron.
  21569. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  21570. */
  21571. constructor( radius = 1, detail = 0 ) {
  21572. const vertices = [
  21573. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  21574. 0, -1, 0, 0, 0, 1, 0, 0, -1
  21575. ];
  21576. const indices = [
  21577. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21578. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21579. 1, 3, 4, 1, 4, 2
  21580. ];
  21581. super( vertices, indices, radius, detail );
  21582. this.type = 'OctahedronGeometry';
  21583. /**
  21584. * Holds the constructor parameters that have been
  21585. * used to generate the geometry. Any modification
  21586. * after instantiation does not change the geometry.
  21587. *
  21588. * @type {Object}
  21589. */
  21590. this.parameters = {
  21591. radius: radius,
  21592. detail: detail
  21593. };
  21594. }
  21595. /**
  21596. * Factory method for creating an instance of this class from the given
  21597. * JSON object.
  21598. *
  21599. * @param {Object} data - A JSON object representing the serialized geometry.
  21600. * @return {OctahedronGeometry} A new instance.
  21601. */
  21602. static fromJSON( data ) {
  21603. return new OctahedronGeometry( data.radius, data.detail );
  21604. }
  21605. }
  21606. /**
  21607. * A geometry class for representing a plane.
  21608. *
  21609. * ```js
  21610. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  21611. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  21612. * const plane = new THREE.Mesh( geometry, material );
  21613. * scene.add( plane );
  21614. * ```
  21615. *
  21616. * @augments BufferGeometry
  21617. */
  21618. class PlaneGeometry extends BufferGeometry {
  21619. /**
  21620. * Constructs a new plane geometry.
  21621. *
  21622. * @param {number} [width=1] - The width along the X axis.
  21623. * @param {number} [height=1] - The height along the Y axis
  21624. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  21625. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  21626. */
  21627. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  21628. super();
  21629. this.type = 'PlaneGeometry';
  21630. /**
  21631. * Holds the constructor parameters that have been
  21632. * used to generate the geometry. Any modification
  21633. * after instantiation does not change the geometry.
  21634. *
  21635. * @type {Object}
  21636. */
  21637. this.parameters = {
  21638. width: width,
  21639. height: height,
  21640. widthSegments: widthSegments,
  21641. heightSegments: heightSegments
  21642. };
  21643. const width_half = width / 2;
  21644. const height_half = height / 2;
  21645. const gridX = Math.floor( widthSegments );
  21646. const gridY = Math.floor( heightSegments );
  21647. const gridX1 = gridX + 1;
  21648. const gridY1 = gridY + 1;
  21649. const segment_width = width / gridX;
  21650. const segment_height = height / gridY;
  21651. //
  21652. const indices = [];
  21653. const vertices = [];
  21654. const normals = [];
  21655. const uvs = [];
  21656. for ( let iy = 0; iy < gridY1; iy ++ ) {
  21657. const y = iy * segment_height - height_half;
  21658. for ( let ix = 0; ix < gridX1; ix ++ ) {
  21659. const x = ix * segment_width - width_half;
  21660. vertices.push( x, - y, 0 );
  21661. normals.push( 0, 0, 1 );
  21662. uvs.push( ix / gridX );
  21663. uvs.push( 1 - ( iy / gridY ) );
  21664. }
  21665. }
  21666. for ( let iy = 0; iy < gridY; iy ++ ) {
  21667. for ( let ix = 0; ix < gridX; ix ++ ) {
  21668. const a = ix + gridX1 * iy;
  21669. const b = ix + gridX1 * ( iy + 1 );
  21670. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  21671. const d = ( ix + 1 ) + gridX1 * iy;
  21672. indices.push( a, b, d );
  21673. indices.push( b, c, d );
  21674. }
  21675. }
  21676. this.setIndex( indices );
  21677. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21678. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21679. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21680. }
  21681. copy( source ) {
  21682. super.copy( source );
  21683. this.parameters = Object.assign( {}, source.parameters );
  21684. return this;
  21685. }
  21686. /**
  21687. * Factory method for creating an instance of this class from the given
  21688. * JSON object.
  21689. *
  21690. * @param {Object} data - A JSON object representing the serialized geometry.
  21691. * @return {PlaneGeometry} A new instance.
  21692. */
  21693. static fromJSON( data ) {
  21694. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  21695. }
  21696. }
  21697. /**
  21698. * A class for generating a two-dimensional ring geometry.
  21699. *
  21700. * ```js
  21701. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  21702. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  21703. * const mesh = new THREE.Mesh( geometry, material );
  21704. * scene.add( mesh );
  21705. * ```
  21706. *
  21707. * @augments BufferGeometry
  21708. */
  21709. class RingGeometry extends BufferGeometry {
  21710. /**
  21711. * Constructs a new ring geometry.
  21712. *
  21713. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  21714. * @param {number} [outerRadius=1] - The outer radius of the ring.
  21715. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  21716. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  21717. * @param {number} [thetaStart=0] - Starting angle in radians.
  21718. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  21719. */
  21720. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21721. super();
  21722. this.type = 'RingGeometry';
  21723. /**
  21724. * Holds the constructor parameters that have been
  21725. * used to generate the geometry. Any modification
  21726. * after instantiation does not change the geometry.
  21727. *
  21728. * @type {Object}
  21729. */
  21730. this.parameters = {
  21731. innerRadius: innerRadius,
  21732. outerRadius: outerRadius,
  21733. thetaSegments: thetaSegments,
  21734. phiSegments: phiSegments,
  21735. thetaStart: thetaStart,
  21736. thetaLength: thetaLength
  21737. };
  21738. thetaSegments = Math.max( 3, thetaSegments );
  21739. phiSegments = Math.max( 1, phiSegments );
  21740. // buffers
  21741. const indices = [];
  21742. const vertices = [];
  21743. const normals = [];
  21744. const uvs = [];
  21745. // some helper variables
  21746. let radius = innerRadius;
  21747. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21748. const vertex = new Vector3();
  21749. const uv = new Vector2();
  21750. // generate vertices, normals and uvs
  21751. for ( let j = 0; j <= phiSegments; j ++ ) {
  21752. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21753. // values are generate from the inside of the ring to the outside
  21754. const segment = thetaStart + i / thetaSegments * thetaLength;
  21755. // vertex
  21756. vertex.x = radius * Math.cos( segment );
  21757. vertex.y = radius * Math.sin( segment );
  21758. vertices.push( vertex.x, vertex.y, vertex.z );
  21759. // normal
  21760. normals.push( 0, 0, 1 );
  21761. // uv
  21762. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21763. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21764. uvs.push( uv.x, uv.y );
  21765. }
  21766. // increase the radius for next row of vertices
  21767. radius += radiusStep;
  21768. }
  21769. // indices
  21770. for ( let j = 0; j < phiSegments; j ++ ) {
  21771. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21772. for ( let i = 0; i < thetaSegments; i ++ ) {
  21773. const segment = i + thetaSegmentLevel;
  21774. const a = segment;
  21775. const b = segment + thetaSegments + 1;
  21776. const c = segment + thetaSegments + 2;
  21777. const d = segment + 1;
  21778. // faces
  21779. indices.push( a, b, d );
  21780. indices.push( b, c, d );
  21781. }
  21782. }
  21783. // build geometry
  21784. this.setIndex( indices );
  21785. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21786. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21787. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21788. }
  21789. copy( source ) {
  21790. super.copy( source );
  21791. this.parameters = Object.assign( {}, source.parameters );
  21792. return this;
  21793. }
  21794. /**
  21795. * Factory method for creating an instance of this class from the given
  21796. * JSON object.
  21797. *
  21798. * @param {Object} data - A JSON object representing the serialized geometry.
  21799. * @return {RingGeometry} A new instance.
  21800. */
  21801. static fromJSON( data ) {
  21802. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21803. }
  21804. }
  21805. /**
  21806. * Creates an one-sided polygonal geometry from one or more path shapes.
  21807. *
  21808. * ```js
  21809. * const arcShape = new THREE.Shape()
  21810. * .moveTo( 5, 1 )
  21811. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  21812. *
  21813. * const geometry = new THREE.ShapeGeometry( arcShape );
  21814. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  21815. * const mesh = new THREE.Mesh( geometry, material ) ;
  21816. * scene.add( mesh );
  21817. * ```
  21818. *
  21819. * @augments BufferGeometry
  21820. */
  21821. class ShapeGeometry extends BufferGeometry {
  21822. /**
  21823. * Constructs a new shape geometry.
  21824. *
  21825. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  21826. * @param {number} [curveSegments=12] - Number of segments per shape.
  21827. */
  21828. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  21829. super();
  21830. this.type = 'ShapeGeometry';
  21831. /**
  21832. * Holds the constructor parameters that have been
  21833. * used to generate the geometry. Any modification
  21834. * after instantiation does not change the geometry.
  21835. *
  21836. * @type {Object}
  21837. */
  21838. this.parameters = {
  21839. shapes: shapes,
  21840. curveSegments: curveSegments
  21841. };
  21842. // buffers
  21843. const indices = [];
  21844. const vertices = [];
  21845. const normals = [];
  21846. const uvs = [];
  21847. // helper variables
  21848. let groupStart = 0;
  21849. let groupCount = 0;
  21850. // allow single and array values for "shapes" parameter
  21851. if ( Array.isArray( shapes ) === false ) {
  21852. addShape( shapes );
  21853. } else {
  21854. for ( let i = 0; i < shapes.length; i ++ ) {
  21855. addShape( shapes[ i ] );
  21856. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21857. groupStart += groupCount;
  21858. groupCount = 0;
  21859. }
  21860. }
  21861. // build geometry
  21862. this.setIndex( indices );
  21863. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21864. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21865. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21866. // helper functions
  21867. function addShape( shape ) {
  21868. const indexOffset = vertices.length / 3;
  21869. const points = shape.extractPoints( curveSegments );
  21870. let shapeVertices = points.shape;
  21871. const shapeHoles = points.holes;
  21872. // check direction of vertices
  21873. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21874. shapeVertices = shapeVertices.reverse();
  21875. }
  21876. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21877. const shapeHole = shapeHoles[ i ];
  21878. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21879. shapeHoles[ i ] = shapeHole.reverse();
  21880. }
  21881. }
  21882. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21883. // join vertices of inner and outer paths to a single array
  21884. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21885. const shapeHole = shapeHoles[ i ];
  21886. shapeVertices = shapeVertices.concat( shapeHole );
  21887. }
  21888. // vertices, normals, uvs
  21889. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21890. const vertex = shapeVertices[ i ];
  21891. vertices.push( vertex.x, vertex.y, 0 );
  21892. normals.push( 0, 0, 1 );
  21893. uvs.push( vertex.x, vertex.y ); // world uvs
  21894. }
  21895. // indices
  21896. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21897. const face = faces[ i ];
  21898. const a = face[ 0 ] + indexOffset;
  21899. const b = face[ 1 ] + indexOffset;
  21900. const c = face[ 2 ] + indexOffset;
  21901. indices.push( a, b, c );
  21902. groupCount += 3;
  21903. }
  21904. }
  21905. }
  21906. copy( source ) {
  21907. super.copy( source );
  21908. this.parameters = Object.assign( {}, source.parameters );
  21909. return this;
  21910. }
  21911. toJSON() {
  21912. const data = super.toJSON();
  21913. const shapes = this.parameters.shapes;
  21914. return toJSON( shapes, data );
  21915. }
  21916. /**
  21917. * Factory method for creating an instance of this class from the given
  21918. * JSON object.
  21919. *
  21920. * @param {Object} data - A JSON object representing the serialized geometry.
  21921. * @param {Array<Shape>} shapes - An array of shapes.
  21922. * @return {ShapeGeometry} A new instance.
  21923. */
  21924. static fromJSON( data, shapes ) {
  21925. const geometryShapes = [];
  21926. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21927. const shape = shapes[ data.shapes[ j ] ];
  21928. geometryShapes.push( shape );
  21929. }
  21930. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21931. }
  21932. }
  21933. function toJSON( shapes, data ) {
  21934. data.shapes = [];
  21935. if ( Array.isArray( shapes ) ) {
  21936. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21937. const shape = shapes[ i ];
  21938. data.shapes.push( shape.uuid );
  21939. }
  21940. } else {
  21941. data.shapes.push( shapes.uuid );
  21942. }
  21943. return data;
  21944. }
  21945. /**
  21946. * A class for generating a sphere geometry.
  21947. *
  21948. * ```js
  21949. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  21950. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  21951. * const sphere = new THREE.Mesh( geometry, material );
  21952. * scene.add( sphere );
  21953. * ```
  21954. *
  21955. * @augments BufferGeometry
  21956. */
  21957. class SphereGeometry extends BufferGeometry {
  21958. /**
  21959. * Constructs a new sphere geometry.
  21960. *
  21961. * @param {number} [radius=1] - The sphere radius.
  21962. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  21963. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  21964. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  21965. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  21966. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  21967. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  21968. */
  21969. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21970. super();
  21971. this.type = 'SphereGeometry';
  21972. /**
  21973. * Holds the constructor parameters that have been
  21974. * used to generate the geometry. Any modification
  21975. * after instantiation does not change the geometry.
  21976. *
  21977. * @type {Object}
  21978. */
  21979. this.parameters = {
  21980. radius: radius,
  21981. widthSegments: widthSegments,
  21982. heightSegments: heightSegments,
  21983. phiStart: phiStart,
  21984. phiLength: phiLength,
  21985. thetaStart: thetaStart,
  21986. thetaLength: thetaLength
  21987. };
  21988. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21989. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21990. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21991. let index = 0;
  21992. const grid = [];
  21993. const vertex = new Vector3();
  21994. const normal = new Vector3();
  21995. // buffers
  21996. const indices = [];
  21997. const vertices = [];
  21998. const normals = [];
  21999. const uvs = [];
  22000. // generate vertices, normals and uvs
  22001. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22002. const verticesRow = [];
  22003. const v = iy / heightSegments;
  22004. // special case for the poles
  22005. let uOffset = 0;
  22006. if ( iy === 0 && thetaStart === 0 ) {
  22007. uOffset = 0.5 / widthSegments;
  22008. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22009. uOffset = -0.5 / widthSegments;
  22010. }
  22011. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22012. const u = ix / widthSegments;
  22013. // vertex
  22014. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22015. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22016. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22017. vertices.push( vertex.x, vertex.y, vertex.z );
  22018. // normal
  22019. normal.copy( vertex ).normalize();
  22020. normals.push( normal.x, normal.y, normal.z );
  22021. // uv
  22022. uvs.push( u + uOffset, 1 - v );
  22023. verticesRow.push( index ++ );
  22024. }
  22025. grid.push( verticesRow );
  22026. }
  22027. // indices
  22028. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22029. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22030. const a = grid[ iy ][ ix + 1 ];
  22031. const b = grid[ iy ][ ix ];
  22032. const c = grid[ iy + 1 ][ ix ];
  22033. const d = grid[ iy + 1 ][ ix + 1 ];
  22034. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22035. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22036. }
  22037. }
  22038. // build geometry
  22039. this.setIndex( indices );
  22040. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22041. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22042. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22043. }
  22044. copy( source ) {
  22045. super.copy( source );
  22046. this.parameters = Object.assign( {}, source.parameters );
  22047. return this;
  22048. }
  22049. /**
  22050. * Factory method for creating an instance of this class from the given
  22051. * JSON object.
  22052. *
  22053. * @param {Object} data - A JSON object representing the serialized geometry.
  22054. * @return {SphereGeometry} A new instance.
  22055. */
  22056. static fromJSON( data ) {
  22057. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22058. }
  22059. }
  22060. /**
  22061. * A geometry class for representing an tetrahedron.
  22062. *
  22063. * ```js
  22064. * const geometry = new THREE.TetrahedronGeometry();
  22065. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22066. * const tetrahedron = new THREE.Mesh( geometry, material );
  22067. * scene.add( tetrahedron );
  22068. * ```
  22069. *
  22070. * @augments PolyhedronGeometry
  22071. */
  22072. class TetrahedronGeometry extends PolyhedronGeometry {
  22073. /**
  22074. * Constructs a new tetrahedron geometry.
  22075. *
  22076. * @param {number} [radius=1] - Radius of the tetrahedron.
  22077. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  22078. */
  22079. constructor( radius = 1, detail = 0 ) {
  22080. const vertices = [
  22081. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  22082. ];
  22083. const indices = [
  22084. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22085. ];
  22086. super( vertices, indices, radius, detail );
  22087. this.type = 'TetrahedronGeometry';
  22088. /**
  22089. * Holds the constructor parameters that have been
  22090. * used to generate the geometry. Any modification
  22091. * after instantiation does not change the geometry.
  22092. *
  22093. * @type {Object}
  22094. */
  22095. this.parameters = {
  22096. radius: radius,
  22097. detail: detail
  22098. };
  22099. }
  22100. /**
  22101. * Factory method for creating an instance of this class from the given
  22102. * JSON object.
  22103. *
  22104. * @param {Object} data - A JSON object representing the serialized geometry.
  22105. * @return {TetrahedronGeometry} A new instance.
  22106. */
  22107. static fromJSON( data ) {
  22108. return new TetrahedronGeometry( data.radius, data.detail );
  22109. }
  22110. }
  22111. /**
  22112. * A geometry class for representing an torus.
  22113. *
  22114. * ```js
  22115. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  22116. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22117. * const torus = new THREE.Mesh( geometry, material );
  22118. * scene.add( torus );
  22119. * ```
  22120. *
  22121. * @augments BufferGeometry
  22122. */
  22123. class TorusGeometry extends BufferGeometry {
  22124. /**
  22125. * Constructs a new torus geometry.
  22126. *
  22127. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  22128. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  22129. * @param {number} [radialSegments=12] - The number of radial segments.
  22130. * @param {number} [tubularSegments=48] - The number of tubular segments.
  22131. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  22132. */
  22133. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22134. super();
  22135. this.type = 'TorusGeometry';
  22136. /**
  22137. * Holds the constructor parameters that have been
  22138. * used to generate the geometry. Any modification
  22139. * after instantiation does not change the geometry.
  22140. *
  22141. * @type {Object}
  22142. */
  22143. this.parameters = {
  22144. radius: radius,
  22145. tube: tube,
  22146. radialSegments: radialSegments,
  22147. tubularSegments: tubularSegments,
  22148. arc: arc
  22149. };
  22150. radialSegments = Math.floor( radialSegments );
  22151. tubularSegments = Math.floor( tubularSegments );
  22152. // buffers
  22153. const indices = [];
  22154. const vertices = [];
  22155. const normals = [];
  22156. const uvs = [];
  22157. // helper variables
  22158. const center = new Vector3();
  22159. const vertex = new Vector3();
  22160. const normal = new Vector3();
  22161. // generate vertices, normals and uvs
  22162. for ( let j = 0; j <= radialSegments; j ++ ) {
  22163. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22164. const u = i / tubularSegments * arc;
  22165. const v = j / radialSegments * Math.PI * 2;
  22166. // vertex
  22167. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22168. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22169. vertex.z = tube * Math.sin( v );
  22170. vertices.push( vertex.x, vertex.y, vertex.z );
  22171. // normal
  22172. center.x = radius * Math.cos( u );
  22173. center.y = radius * Math.sin( u );
  22174. normal.subVectors( vertex, center ).normalize();
  22175. normals.push( normal.x, normal.y, normal.z );
  22176. // uv
  22177. uvs.push( i / tubularSegments );
  22178. uvs.push( j / radialSegments );
  22179. }
  22180. }
  22181. // generate indices
  22182. for ( let j = 1; j <= radialSegments; j ++ ) {
  22183. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22184. // indices
  22185. const a = ( tubularSegments + 1 ) * j + i - 1;
  22186. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22187. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22188. const d = ( tubularSegments + 1 ) * j + i;
  22189. // faces
  22190. indices.push( a, b, d );
  22191. indices.push( b, c, d );
  22192. }
  22193. }
  22194. // build geometry
  22195. this.setIndex( indices );
  22196. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22197. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22198. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22199. }
  22200. copy( source ) {
  22201. super.copy( source );
  22202. this.parameters = Object.assign( {}, source.parameters );
  22203. return this;
  22204. }
  22205. /**
  22206. * Factory method for creating an instance of this class from the given
  22207. * JSON object.
  22208. *
  22209. * @param {Object} data - A JSON object representing the serialized geometry.
  22210. * @return {TorusGeometry} A new instance.
  22211. */
  22212. static fromJSON( data ) {
  22213. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22214. }
  22215. }
  22216. /**
  22217. * Creates a torus knot, the particular shape of which is defined by a pair
  22218. * of coprime integers, p and q. If p and q are not coprime, the result will
  22219. * be a torus link.
  22220. *
  22221. * ```js
  22222. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  22223. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22224. * const torusKnot = new THREE.Mesh( geometry, material );
  22225. * scene.add( torusKnot );
  22226. * ```
  22227. *
  22228. * @augments BufferGeometry
  22229. */
  22230. class TorusKnotGeometry extends BufferGeometry {
  22231. /**
  22232. * Constructs a new torus knot geometry.
  22233. *
  22234. * @param {number} [radius=1] - Radius of the torus knot.
  22235. * @param {number} [tube=0.4] - Radius of the tube.
  22236. * @param {number} [tubularSegments=64] - The number of tubular segments.
  22237. * @param {number} [radialSegments=8] - The number of radial segments.
  22238. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  22239. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  22240. */
  22241. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22242. super();
  22243. this.type = 'TorusKnotGeometry';
  22244. /**
  22245. * Holds the constructor parameters that have been
  22246. * used to generate the geometry. Any modification
  22247. * after instantiation does not change the geometry.
  22248. *
  22249. * @type {Object}
  22250. */
  22251. this.parameters = {
  22252. radius: radius,
  22253. tube: tube,
  22254. tubularSegments: tubularSegments,
  22255. radialSegments: radialSegments,
  22256. p: p,
  22257. q: q
  22258. };
  22259. tubularSegments = Math.floor( tubularSegments );
  22260. radialSegments = Math.floor( radialSegments );
  22261. // buffers
  22262. const indices = [];
  22263. const vertices = [];
  22264. const normals = [];
  22265. const uvs = [];
  22266. // helper variables
  22267. const vertex = new Vector3();
  22268. const normal = new Vector3();
  22269. const P1 = new Vector3();
  22270. const P2 = new Vector3();
  22271. const B = new Vector3();
  22272. const T = new Vector3();
  22273. const N = new Vector3();
  22274. // generate vertices, normals and uvs
  22275. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22276. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22277. const u = i / tubularSegments * p * Math.PI * 2;
  22278. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22279. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22280. calculatePositionOnCurve( u, p, q, radius, P1 );
  22281. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22282. // calculate orthonormal basis
  22283. T.subVectors( P2, P1 );
  22284. N.addVectors( P2, P1 );
  22285. B.crossVectors( T, N );
  22286. N.crossVectors( B, T );
  22287. // normalize B, N. T can be ignored, we don't use it
  22288. B.normalize();
  22289. N.normalize();
  22290. for ( let j = 0; j <= radialSegments; ++ j ) {
  22291. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22292. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22293. const v = j / radialSegments * Math.PI * 2;
  22294. const cx = - tube * Math.cos( v );
  22295. const cy = tube * Math.sin( v );
  22296. // now calculate the final vertex position.
  22297. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22298. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22299. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22300. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22301. vertices.push( vertex.x, vertex.y, vertex.z );
  22302. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22303. normal.subVectors( vertex, P1 ).normalize();
  22304. normals.push( normal.x, normal.y, normal.z );
  22305. // uv
  22306. uvs.push( i / tubularSegments );
  22307. uvs.push( j / radialSegments );
  22308. }
  22309. }
  22310. // generate indices
  22311. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22312. for ( let i = 1; i <= radialSegments; i ++ ) {
  22313. // indices
  22314. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22315. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22316. const c = ( radialSegments + 1 ) * j + i;
  22317. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22318. // faces
  22319. indices.push( a, b, d );
  22320. indices.push( b, c, d );
  22321. }
  22322. }
  22323. // build geometry
  22324. this.setIndex( indices );
  22325. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22326. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22327. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22328. // this function calculates the current position on the torus curve
  22329. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22330. const cu = Math.cos( u );
  22331. const su = Math.sin( u );
  22332. const quOverP = q / p * u;
  22333. const cs = Math.cos( quOverP );
  22334. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22335. position.y = radius * ( 2 + cs ) * su * 0.5;
  22336. position.z = radius * Math.sin( quOverP ) * 0.5;
  22337. }
  22338. }
  22339. copy( source ) {
  22340. super.copy( source );
  22341. this.parameters = Object.assign( {}, source.parameters );
  22342. return this;
  22343. }
  22344. /**
  22345. * Factory method for creating an instance of this class from the given
  22346. * JSON object.
  22347. *
  22348. * @param {Object} data - A JSON object representing the serialized geometry.
  22349. * @return {TorusKnotGeometry} A new instance.
  22350. */
  22351. static fromJSON( data ) {
  22352. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22353. }
  22354. }
  22355. /**
  22356. * Creates a tube that extrudes along a 3D curve.
  22357. *
  22358. * ```js
  22359. * class CustomSinCurve extends THREE.Curve {
  22360. *
  22361. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  22362. *
  22363. * const tx = t * 3 - 1.5;
  22364. * const ty = Math.sin( 2 * Math.PI * t );
  22365. * const tz = 0;
  22366. *
  22367. * return optionalTarget.set( tx, ty, tz );
  22368. * }
  22369. *
  22370. * }
  22371. *
  22372. * const path = new CustomSinCurve( 10 );
  22373. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  22374. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22375. * const mesh = new THREE.Mesh( geometry, material );
  22376. * scene.add( mesh );
  22377. * ```
  22378. *
  22379. * @augments BufferGeometry
  22380. */
  22381. class TubeGeometry extends BufferGeometry {
  22382. /**
  22383. * Constructs a new tube geometry.
  22384. *
  22385. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  22386. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  22387. * @param {number} [radius=1] -The radius of the tube.
  22388. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  22389. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  22390. */
  22391. 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 ) {
  22392. super();
  22393. this.type = 'TubeGeometry';
  22394. /**
  22395. * Holds the constructor parameters that have been
  22396. * used to generate the geometry. Any modification
  22397. * after instantiation does not change the geometry.
  22398. *
  22399. * @type {Object}
  22400. */
  22401. this.parameters = {
  22402. path: path,
  22403. tubularSegments: tubularSegments,
  22404. radius: radius,
  22405. radialSegments: radialSegments,
  22406. closed: closed
  22407. };
  22408. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22409. // expose internals
  22410. this.tangents = frames.tangents;
  22411. this.normals = frames.normals;
  22412. this.binormals = frames.binormals;
  22413. // helper variables
  22414. const vertex = new Vector3();
  22415. const normal = new Vector3();
  22416. const uv = new Vector2();
  22417. let P = new Vector3();
  22418. // buffer
  22419. const vertices = [];
  22420. const normals = [];
  22421. const uvs = [];
  22422. const indices = [];
  22423. // create buffer data
  22424. generateBufferData();
  22425. // build geometry
  22426. this.setIndex( indices );
  22427. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22428. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22429. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22430. // functions
  22431. function generateBufferData() {
  22432. for ( let i = 0; i < tubularSegments; i ++ ) {
  22433. generateSegment( i );
  22434. }
  22435. // if the geometry is not closed, generate the last row of vertices and normals
  22436. // at the regular position on the given path
  22437. //
  22438. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22439. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22440. // uvs are generated in a separate function.
  22441. // this makes it easy compute correct values for closed geometries
  22442. generateUVs();
  22443. // finally create faces
  22444. generateIndices();
  22445. }
  22446. function generateSegment( i ) {
  22447. // we use getPointAt to sample evenly distributed points from the given path
  22448. P = path.getPointAt( i / tubularSegments, P );
  22449. // retrieve corresponding normal and binormal
  22450. const N = frames.normals[ i ];
  22451. const B = frames.binormals[ i ];
  22452. // generate normals and vertices for the current segment
  22453. for ( let j = 0; j <= radialSegments; j ++ ) {
  22454. const v = j / radialSegments * Math.PI * 2;
  22455. const sin = Math.sin( v );
  22456. const cos = - Math.cos( v );
  22457. // normal
  22458. normal.x = ( cos * N.x + sin * B.x );
  22459. normal.y = ( cos * N.y + sin * B.y );
  22460. normal.z = ( cos * N.z + sin * B.z );
  22461. normal.normalize();
  22462. normals.push( normal.x, normal.y, normal.z );
  22463. // vertex
  22464. vertex.x = P.x + radius * normal.x;
  22465. vertex.y = P.y + radius * normal.y;
  22466. vertex.z = P.z + radius * normal.z;
  22467. vertices.push( vertex.x, vertex.y, vertex.z );
  22468. }
  22469. }
  22470. function generateIndices() {
  22471. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22472. for ( let i = 1; i <= radialSegments; i ++ ) {
  22473. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22474. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22475. const c = ( radialSegments + 1 ) * j + i;
  22476. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22477. // faces
  22478. indices.push( a, b, d );
  22479. indices.push( b, c, d );
  22480. }
  22481. }
  22482. }
  22483. function generateUVs() {
  22484. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22485. for ( let j = 0; j <= radialSegments; j ++ ) {
  22486. uv.x = i / tubularSegments;
  22487. uv.y = j / radialSegments;
  22488. uvs.push( uv.x, uv.y );
  22489. }
  22490. }
  22491. }
  22492. }
  22493. copy( source ) {
  22494. super.copy( source );
  22495. this.parameters = Object.assign( {}, source.parameters );
  22496. return this;
  22497. }
  22498. toJSON() {
  22499. const data = super.toJSON();
  22500. data.path = this.parameters.path.toJSON();
  22501. return data;
  22502. }
  22503. /**
  22504. * Factory method for creating an instance of this class from the given
  22505. * JSON object.
  22506. *
  22507. * @param {Object} data - A JSON object representing the serialized geometry.
  22508. * @return {TubeGeometry} A new instance.
  22509. */
  22510. static fromJSON( data ) {
  22511. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22512. // User defined curves or instances of CurvePath will not be deserialized.
  22513. return new TubeGeometry(
  22514. new Curves[ data.path.type ]().fromJSON( data.path ),
  22515. data.tubularSegments,
  22516. data.radius,
  22517. data.radialSegments,
  22518. data.closed
  22519. );
  22520. }
  22521. }
  22522. /**
  22523. * Can be used as a helper object to visualize a geometry as a wireframe.
  22524. *
  22525. * ```js
  22526. * const geometry = new THREE.SphereGeometry();
  22527. *
  22528. * const wireframe = new THREE.WireframeGeometry( geometry );
  22529. *
  22530. * const line = new THREE.LineSegments( wireframe );
  22531. * line.material.depthWrite = false;
  22532. * line.material.opacity = 0.25;
  22533. * line.material.transparent = true;
  22534. *
  22535. * scene.add( line );
  22536. * ```
  22537. *
  22538. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22539. *
  22540. * @augments BufferGeometry
  22541. */
  22542. class WireframeGeometry extends BufferGeometry {
  22543. /**
  22544. * Constructs a new wireframe geometry.
  22545. *
  22546. * @param {?BufferGeometry} [geometry=null] - The geometry.
  22547. */
  22548. constructor( geometry = null ) {
  22549. super();
  22550. this.type = 'WireframeGeometry';
  22551. /**
  22552. * Holds the constructor parameters that have been
  22553. * used to generate the geometry. Any modification
  22554. * after instantiation does not change the geometry.
  22555. *
  22556. * @type {Object}
  22557. */
  22558. this.parameters = {
  22559. geometry: geometry
  22560. };
  22561. if ( geometry !== null ) {
  22562. // buffer
  22563. const vertices = [];
  22564. const edges = new Set();
  22565. // helper variables
  22566. const start = new Vector3();
  22567. const end = new Vector3();
  22568. if ( geometry.index !== null ) {
  22569. // indexed BufferGeometry
  22570. const position = geometry.attributes.position;
  22571. const indices = geometry.index;
  22572. let groups = geometry.groups;
  22573. if ( groups.length === 0 ) {
  22574. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22575. }
  22576. // create a data structure that contains all edges without duplicates
  22577. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22578. const group = groups[ o ];
  22579. const groupStart = group.start;
  22580. const groupCount = group.count;
  22581. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22582. for ( let j = 0; j < 3; j ++ ) {
  22583. const index1 = indices.getX( i + j );
  22584. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22585. start.fromBufferAttribute( position, index1 );
  22586. end.fromBufferAttribute( position, index2 );
  22587. if ( isUniqueEdge( start, end, edges ) === true ) {
  22588. vertices.push( start.x, start.y, start.z );
  22589. vertices.push( end.x, end.y, end.z );
  22590. }
  22591. }
  22592. }
  22593. }
  22594. } else {
  22595. // non-indexed BufferGeometry
  22596. const position = geometry.attributes.position;
  22597. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22598. for ( let j = 0; j < 3; j ++ ) {
  22599. // three edges per triangle, an edge is represented as (index1, index2)
  22600. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22601. const index1 = 3 * i + j;
  22602. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22603. start.fromBufferAttribute( position, index1 );
  22604. end.fromBufferAttribute( position, index2 );
  22605. if ( isUniqueEdge( start, end, edges ) === true ) {
  22606. vertices.push( start.x, start.y, start.z );
  22607. vertices.push( end.x, end.y, end.z );
  22608. }
  22609. }
  22610. }
  22611. }
  22612. // build geometry
  22613. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22614. }
  22615. }
  22616. copy( source ) {
  22617. super.copy( source );
  22618. this.parameters = Object.assign( {}, source.parameters );
  22619. return this;
  22620. }
  22621. }
  22622. function isUniqueEdge( start, end, edges ) {
  22623. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22624. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22625. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22626. return false;
  22627. } else {
  22628. edges.add( hash1 );
  22629. edges.add( hash2 );
  22630. return true;
  22631. }
  22632. }
  22633. var Geometries = /*#__PURE__*/Object.freeze({
  22634. __proto__: null,
  22635. BoxGeometry: BoxGeometry,
  22636. CapsuleGeometry: CapsuleGeometry,
  22637. CircleGeometry: CircleGeometry,
  22638. ConeGeometry: ConeGeometry,
  22639. CylinderGeometry: CylinderGeometry,
  22640. DodecahedronGeometry: DodecahedronGeometry,
  22641. EdgesGeometry: EdgesGeometry,
  22642. ExtrudeGeometry: ExtrudeGeometry,
  22643. IcosahedronGeometry: IcosahedronGeometry,
  22644. LatheGeometry: LatheGeometry,
  22645. OctahedronGeometry: OctahedronGeometry,
  22646. PlaneGeometry: PlaneGeometry,
  22647. PolyhedronGeometry: PolyhedronGeometry,
  22648. RingGeometry: RingGeometry,
  22649. ShapeGeometry: ShapeGeometry,
  22650. SphereGeometry: SphereGeometry,
  22651. TetrahedronGeometry: TetrahedronGeometry,
  22652. TorusGeometry: TorusGeometry,
  22653. TorusKnotGeometry: TorusKnotGeometry,
  22654. TubeGeometry: TubeGeometry,
  22655. WireframeGeometry: WireframeGeometry
  22656. });
  22657. class ShadowMaterial extends Material {
  22658. constructor( parameters ) {
  22659. super();
  22660. this.isShadowMaterial = true;
  22661. this.type = 'ShadowMaterial';
  22662. this.color = new Color( 0x000000 );
  22663. this.transparent = true;
  22664. this.fog = true;
  22665. this.setValues( parameters );
  22666. }
  22667. copy( source ) {
  22668. super.copy( source );
  22669. this.color.copy( source.color );
  22670. this.fog = source.fog;
  22671. return this;
  22672. }
  22673. }
  22674. class RawShaderMaterial extends ShaderMaterial {
  22675. constructor( parameters ) {
  22676. super( parameters );
  22677. this.isRawShaderMaterial = true;
  22678. this.type = 'RawShaderMaterial';
  22679. }
  22680. }
  22681. class MeshStandardMaterial extends Material {
  22682. constructor( parameters ) {
  22683. super();
  22684. this.isMeshStandardMaterial = true;
  22685. this.type = 'MeshStandardMaterial';
  22686. this.defines = { 'STANDARD': '' };
  22687. this.color = new Color( 0xffffff ); // diffuse
  22688. this.roughness = 1.0;
  22689. this.metalness = 0.0;
  22690. this.map = null;
  22691. this.lightMap = null;
  22692. this.lightMapIntensity = 1.0;
  22693. this.aoMap = null;
  22694. this.aoMapIntensity = 1.0;
  22695. this.emissive = new Color( 0x000000 );
  22696. this.emissiveIntensity = 1.0;
  22697. this.emissiveMap = null;
  22698. this.bumpMap = null;
  22699. this.bumpScale = 1;
  22700. this.normalMap = null;
  22701. this.normalMapType = TangentSpaceNormalMap;
  22702. this.normalScale = new Vector2( 1, 1 );
  22703. this.displacementMap = null;
  22704. this.displacementScale = 1;
  22705. this.displacementBias = 0;
  22706. this.roughnessMap = null;
  22707. this.metalnessMap = null;
  22708. this.alphaMap = null;
  22709. this.envMap = null;
  22710. this.envMapRotation = new Euler();
  22711. this.envMapIntensity = 1.0;
  22712. this.wireframe = false;
  22713. this.wireframeLinewidth = 1;
  22714. this.wireframeLinecap = 'round';
  22715. this.wireframeLinejoin = 'round';
  22716. this.flatShading = false;
  22717. this.fog = true;
  22718. this.setValues( parameters );
  22719. }
  22720. copy( source ) {
  22721. super.copy( source );
  22722. this.defines = { 'STANDARD': '' };
  22723. this.color.copy( source.color );
  22724. this.roughness = source.roughness;
  22725. this.metalness = source.metalness;
  22726. this.map = source.map;
  22727. this.lightMap = source.lightMap;
  22728. this.lightMapIntensity = source.lightMapIntensity;
  22729. this.aoMap = source.aoMap;
  22730. this.aoMapIntensity = source.aoMapIntensity;
  22731. this.emissive.copy( source.emissive );
  22732. this.emissiveMap = source.emissiveMap;
  22733. this.emissiveIntensity = source.emissiveIntensity;
  22734. this.bumpMap = source.bumpMap;
  22735. this.bumpScale = source.bumpScale;
  22736. this.normalMap = source.normalMap;
  22737. this.normalMapType = source.normalMapType;
  22738. this.normalScale.copy( source.normalScale );
  22739. this.displacementMap = source.displacementMap;
  22740. this.displacementScale = source.displacementScale;
  22741. this.displacementBias = source.displacementBias;
  22742. this.roughnessMap = source.roughnessMap;
  22743. this.metalnessMap = source.metalnessMap;
  22744. this.alphaMap = source.alphaMap;
  22745. this.envMap = source.envMap;
  22746. this.envMapRotation.copy( source.envMapRotation );
  22747. this.envMapIntensity = source.envMapIntensity;
  22748. this.wireframe = source.wireframe;
  22749. this.wireframeLinewidth = source.wireframeLinewidth;
  22750. this.wireframeLinecap = source.wireframeLinecap;
  22751. this.wireframeLinejoin = source.wireframeLinejoin;
  22752. this.flatShading = source.flatShading;
  22753. this.fog = source.fog;
  22754. return this;
  22755. }
  22756. }
  22757. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22758. constructor( parameters ) {
  22759. super();
  22760. this.isMeshPhysicalMaterial = true;
  22761. this.defines = {
  22762. 'STANDARD': '',
  22763. 'PHYSICAL': ''
  22764. };
  22765. this.type = 'MeshPhysicalMaterial';
  22766. this.anisotropyRotation = 0;
  22767. this.anisotropyMap = null;
  22768. this.clearcoatMap = null;
  22769. this.clearcoatRoughness = 0.0;
  22770. this.clearcoatRoughnessMap = null;
  22771. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22772. this.clearcoatNormalMap = null;
  22773. this.ior = 1.5;
  22774. Object.defineProperty( this, 'reflectivity', {
  22775. get: function () {
  22776. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22777. },
  22778. set: function ( reflectivity ) {
  22779. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22780. }
  22781. } );
  22782. this.iridescenceMap = null;
  22783. this.iridescenceIOR = 1.3;
  22784. this.iridescenceThicknessRange = [ 100, 400 ];
  22785. this.iridescenceThicknessMap = null;
  22786. this.sheenColor = new Color( 0x000000 );
  22787. this.sheenColorMap = null;
  22788. this.sheenRoughness = 1.0;
  22789. this.sheenRoughnessMap = null;
  22790. this.transmissionMap = null;
  22791. this.thickness = 0;
  22792. this.thicknessMap = null;
  22793. this.attenuationDistance = Infinity;
  22794. this.attenuationColor = new Color( 1, 1, 1 );
  22795. this.specularIntensity = 1.0;
  22796. this.specularIntensityMap = null;
  22797. this.specularColor = new Color( 1, 1, 1 );
  22798. this.specularColorMap = null;
  22799. this._anisotropy = 0;
  22800. this._clearcoat = 0;
  22801. this._dispersion = 0;
  22802. this._iridescence = 0;
  22803. this._sheen = 0.0;
  22804. this._transmission = 0;
  22805. this.setValues( parameters );
  22806. }
  22807. get anisotropy() {
  22808. return this._anisotropy;
  22809. }
  22810. set anisotropy( value ) {
  22811. if ( this._anisotropy > 0 !== value > 0 ) {
  22812. this.version ++;
  22813. }
  22814. this._anisotropy = value;
  22815. }
  22816. get clearcoat() {
  22817. return this._clearcoat;
  22818. }
  22819. set clearcoat( value ) {
  22820. if ( this._clearcoat > 0 !== value > 0 ) {
  22821. this.version ++;
  22822. }
  22823. this._clearcoat = value;
  22824. }
  22825. get iridescence() {
  22826. return this._iridescence;
  22827. }
  22828. set iridescence( value ) {
  22829. if ( this._iridescence > 0 !== value > 0 ) {
  22830. this.version ++;
  22831. }
  22832. this._iridescence = value;
  22833. }
  22834. get dispersion() {
  22835. return this._dispersion;
  22836. }
  22837. set dispersion( value ) {
  22838. if ( this._dispersion > 0 !== value > 0 ) {
  22839. this.version ++;
  22840. }
  22841. this._dispersion = value;
  22842. }
  22843. get sheen() {
  22844. return this._sheen;
  22845. }
  22846. set sheen( value ) {
  22847. if ( this._sheen > 0 !== value > 0 ) {
  22848. this.version ++;
  22849. }
  22850. this._sheen = value;
  22851. }
  22852. get transmission() {
  22853. return this._transmission;
  22854. }
  22855. set transmission( value ) {
  22856. if ( this._transmission > 0 !== value > 0 ) {
  22857. this.version ++;
  22858. }
  22859. this._transmission = value;
  22860. }
  22861. copy( source ) {
  22862. super.copy( source );
  22863. this.defines = {
  22864. 'STANDARD': '',
  22865. 'PHYSICAL': ''
  22866. };
  22867. this.anisotropy = source.anisotropy;
  22868. this.anisotropyRotation = source.anisotropyRotation;
  22869. this.anisotropyMap = source.anisotropyMap;
  22870. this.clearcoat = source.clearcoat;
  22871. this.clearcoatMap = source.clearcoatMap;
  22872. this.clearcoatRoughness = source.clearcoatRoughness;
  22873. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22874. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22875. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22876. this.dispersion = source.dispersion;
  22877. this.ior = source.ior;
  22878. this.iridescence = source.iridescence;
  22879. this.iridescenceMap = source.iridescenceMap;
  22880. this.iridescenceIOR = source.iridescenceIOR;
  22881. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22882. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22883. this.sheen = source.sheen;
  22884. this.sheenColor.copy( source.sheenColor );
  22885. this.sheenColorMap = source.sheenColorMap;
  22886. this.sheenRoughness = source.sheenRoughness;
  22887. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22888. this.transmission = source.transmission;
  22889. this.transmissionMap = source.transmissionMap;
  22890. this.thickness = source.thickness;
  22891. this.thicknessMap = source.thicknessMap;
  22892. this.attenuationDistance = source.attenuationDistance;
  22893. this.attenuationColor.copy( source.attenuationColor );
  22894. this.specularIntensity = source.specularIntensity;
  22895. this.specularIntensityMap = source.specularIntensityMap;
  22896. this.specularColor.copy( source.specularColor );
  22897. this.specularColorMap = source.specularColorMap;
  22898. return this;
  22899. }
  22900. }
  22901. class MeshPhongMaterial extends Material {
  22902. constructor( parameters ) {
  22903. super();
  22904. this.isMeshPhongMaterial = true;
  22905. this.type = 'MeshPhongMaterial';
  22906. this.color = new Color( 0xffffff ); // diffuse
  22907. this.specular = new Color( 0x111111 );
  22908. this.shininess = 30;
  22909. this.map = null;
  22910. this.lightMap = null;
  22911. this.lightMapIntensity = 1.0;
  22912. this.aoMap = null;
  22913. this.aoMapIntensity = 1.0;
  22914. this.emissive = new Color( 0x000000 );
  22915. this.emissiveIntensity = 1.0;
  22916. this.emissiveMap = null;
  22917. this.bumpMap = null;
  22918. this.bumpScale = 1;
  22919. this.normalMap = null;
  22920. this.normalMapType = TangentSpaceNormalMap;
  22921. this.normalScale = new Vector2( 1, 1 );
  22922. this.displacementMap = null;
  22923. this.displacementScale = 1;
  22924. this.displacementBias = 0;
  22925. this.specularMap = null;
  22926. this.alphaMap = null;
  22927. this.envMap = null;
  22928. this.envMapRotation = new Euler();
  22929. this.combine = MultiplyOperation;
  22930. this.reflectivity = 1;
  22931. this.refractionRatio = 0.98;
  22932. this.wireframe = false;
  22933. this.wireframeLinewidth = 1;
  22934. this.wireframeLinecap = 'round';
  22935. this.wireframeLinejoin = 'round';
  22936. this.flatShading = false;
  22937. this.fog = true;
  22938. this.setValues( parameters );
  22939. }
  22940. copy( source ) {
  22941. super.copy( source );
  22942. this.color.copy( source.color );
  22943. this.specular.copy( source.specular );
  22944. this.shininess = source.shininess;
  22945. this.map = source.map;
  22946. this.lightMap = source.lightMap;
  22947. this.lightMapIntensity = source.lightMapIntensity;
  22948. this.aoMap = source.aoMap;
  22949. this.aoMapIntensity = source.aoMapIntensity;
  22950. this.emissive.copy( source.emissive );
  22951. this.emissiveMap = source.emissiveMap;
  22952. this.emissiveIntensity = source.emissiveIntensity;
  22953. this.bumpMap = source.bumpMap;
  22954. this.bumpScale = source.bumpScale;
  22955. this.normalMap = source.normalMap;
  22956. this.normalMapType = source.normalMapType;
  22957. this.normalScale.copy( source.normalScale );
  22958. this.displacementMap = source.displacementMap;
  22959. this.displacementScale = source.displacementScale;
  22960. this.displacementBias = source.displacementBias;
  22961. this.specularMap = source.specularMap;
  22962. this.alphaMap = source.alphaMap;
  22963. this.envMap = source.envMap;
  22964. this.envMapRotation.copy( source.envMapRotation );
  22965. this.combine = source.combine;
  22966. this.reflectivity = source.reflectivity;
  22967. this.refractionRatio = source.refractionRatio;
  22968. this.wireframe = source.wireframe;
  22969. this.wireframeLinewidth = source.wireframeLinewidth;
  22970. this.wireframeLinecap = source.wireframeLinecap;
  22971. this.wireframeLinejoin = source.wireframeLinejoin;
  22972. this.flatShading = source.flatShading;
  22973. this.fog = source.fog;
  22974. return this;
  22975. }
  22976. }
  22977. class MeshToonMaterial extends Material {
  22978. constructor( parameters ) {
  22979. super();
  22980. this.isMeshToonMaterial = true;
  22981. this.defines = { 'TOON': '' };
  22982. this.type = 'MeshToonMaterial';
  22983. this.color = new Color( 0xffffff );
  22984. this.map = null;
  22985. this.gradientMap = null;
  22986. this.lightMap = null;
  22987. this.lightMapIntensity = 1.0;
  22988. this.aoMap = null;
  22989. this.aoMapIntensity = 1.0;
  22990. this.emissive = new Color( 0x000000 );
  22991. this.emissiveIntensity = 1.0;
  22992. this.emissiveMap = null;
  22993. this.bumpMap = null;
  22994. this.bumpScale = 1;
  22995. this.normalMap = null;
  22996. this.normalMapType = TangentSpaceNormalMap;
  22997. this.normalScale = new Vector2( 1, 1 );
  22998. this.displacementMap = null;
  22999. this.displacementScale = 1;
  23000. this.displacementBias = 0;
  23001. this.alphaMap = null;
  23002. this.wireframe = false;
  23003. this.wireframeLinewidth = 1;
  23004. this.wireframeLinecap = 'round';
  23005. this.wireframeLinejoin = 'round';
  23006. this.fog = true;
  23007. this.setValues( parameters );
  23008. }
  23009. copy( source ) {
  23010. super.copy( source );
  23011. this.color.copy( source.color );
  23012. this.map = source.map;
  23013. this.gradientMap = source.gradientMap;
  23014. this.lightMap = source.lightMap;
  23015. this.lightMapIntensity = source.lightMapIntensity;
  23016. this.aoMap = source.aoMap;
  23017. this.aoMapIntensity = source.aoMapIntensity;
  23018. this.emissive.copy( source.emissive );
  23019. this.emissiveMap = source.emissiveMap;
  23020. this.emissiveIntensity = source.emissiveIntensity;
  23021. this.bumpMap = source.bumpMap;
  23022. this.bumpScale = source.bumpScale;
  23023. this.normalMap = source.normalMap;
  23024. this.normalMapType = source.normalMapType;
  23025. this.normalScale.copy( source.normalScale );
  23026. this.displacementMap = source.displacementMap;
  23027. this.displacementScale = source.displacementScale;
  23028. this.displacementBias = source.displacementBias;
  23029. this.alphaMap = source.alphaMap;
  23030. this.wireframe = source.wireframe;
  23031. this.wireframeLinewidth = source.wireframeLinewidth;
  23032. this.wireframeLinecap = source.wireframeLinecap;
  23033. this.wireframeLinejoin = source.wireframeLinejoin;
  23034. this.fog = source.fog;
  23035. return this;
  23036. }
  23037. }
  23038. class MeshNormalMaterial extends Material {
  23039. constructor( parameters ) {
  23040. super();
  23041. this.isMeshNormalMaterial = true;
  23042. this.type = 'MeshNormalMaterial';
  23043. this.bumpMap = null;
  23044. this.bumpScale = 1;
  23045. this.normalMap = null;
  23046. this.normalMapType = TangentSpaceNormalMap;
  23047. this.normalScale = new Vector2( 1, 1 );
  23048. this.displacementMap = null;
  23049. this.displacementScale = 1;
  23050. this.displacementBias = 0;
  23051. this.wireframe = false;
  23052. this.wireframeLinewidth = 1;
  23053. this.flatShading = false;
  23054. this.setValues( parameters );
  23055. }
  23056. copy( source ) {
  23057. super.copy( source );
  23058. this.bumpMap = source.bumpMap;
  23059. this.bumpScale = source.bumpScale;
  23060. this.normalMap = source.normalMap;
  23061. this.normalMapType = source.normalMapType;
  23062. this.normalScale.copy( source.normalScale );
  23063. this.displacementMap = source.displacementMap;
  23064. this.displacementScale = source.displacementScale;
  23065. this.displacementBias = source.displacementBias;
  23066. this.wireframe = source.wireframe;
  23067. this.wireframeLinewidth = source.wireframeLinewidth;
  23068. this.flatShading = source.flatShading;
  23069. return this;
  23070. }
  23071. }
  23072. class MeshLambertMaterial extends Material {
  23073. constructor( parameters ) {
  23074. super();
  23075. this.isMeshLambertMaterial = true;
  23076. this.type = 'MeshLambertMaterial';
  23077. this.color = new Color( 0xffffff ); // diffuse
  23078. this.map = null;
  23079. this.lightMap = null;
  23080. this.lightMapIntensity = 1.0;
  23081. this.aoMap = null;
  23082. this.aoMapIntensity = 1.0;
  23083. this.emissive = new Color( 0x000000 );
  23084. this.emissiveIntensity = 1.0;
  23085. this.emissiveMap = null;
  23086. this.bumpMap = null;
  23087. this.bumpScale = 1;
  23088. this.normalMap = null;
  23089. this.normalMapType = TangentSpaceNormalMap;
  23090. this.normalScale = new Vector2( 1, 1 );
  23091. this.displacementMap = null;
  23092. this.displacementScale = 1;
  23093. this.displacementBias = 0;
  23094. this.specularMap = null;
  23095. this.alphaMap = null;
  23096. this.envMap = null;
  23097. this.envMapRotation = new Euler();
  23098. this.combine = MultiplyOperation;
  23099. this.reflectivity = 1;
  23100. this.refractionRatio = 0.98;
  23101. this.wireframe = false;
  23102. this.wireframeLinewidth = 1;
  23103. this.wireframeLinecap = 'round';
  23104. this.wireframeLinejoin = 'round';
  23105. this.flatShading = false;
  23106. this.fog = true;
  23107. this.setValues( parameters );
  23108. }
  23109. copy( source ) {
  23110. super.copy( source );
  23111. this.color.copy( source.color );
  23112. this.map = source.map;
  23113. this.lightMap = source.lightMap;
  23114. this.lightMapIntensity = source.lightMapIntensity;
  23115. this.aoMap = source.aoMap;
  23116. this.aoMapIntensity = source.aoMapIntensity;
  23117. this.emissive.copy( source.emissive );
  23118. this.emissiveMap = source.emissiveMap;
  23119. this.emissiveIntensity = source.emissiveIntensity;
  23120. this.bumpMap = source.bumpMap;
  23121. this.bumpScale = source.bumpScale;
  23122. this.normalMap = source.normalMap;
  23123. this.normalMapType = source.normalMapType;
  23124. this.normalScale.copy( source.normalScale );
  23125. this.displacementMap = source.displacementMap;
  23126. this.displacementScale = source.displacementScale;
  23127. this.displacementBias = source.displacementBias;
  23128. this.specularMap = source.specularMap;
  23129. this.alphaMap = source.alphaMap;
  23130. this.envMap = source.envMap;
  23131. this.envMapRotation.copy( source.envMapRotation );
  23132. this.combine = source.combine;
  23133. this.reflectivity = source.reflectivity;
  23134. this.refractionRatio = source.refractionRatio;
  23135. this.wireframe = source.wireframe;
  23136. this.wireframeLinewidth = source.wireframeLinewidth;
  23137. this.wireframeLinecap = source.wireframeLinecap;
  23138. this.wireframeLinejoin = source.wireframeLinejoin;
  23139. this.flatShading = source.flatShading;
  23140. this.fog = source.fog;
  23141. return this;
  23142. }
  23143. }
  23144. class MeshDepthMaterial extends Material {
  23145. constructor( parameters ) {
  23146. super();
  23147. this.isMeshDepthMaterial = true;
  23148. this.type = 'MeshDepthMaterial';
  23149. this.depthPacking = BasicDepthPacking;
  23150. this.map = null;
  23151. this.alphaMap = null;
  23152. this.displacementMap = null;
  23153. this.displacementScale = 1;
  23154. this.displacementBias = 0;
  23155. this.wireframe = false;
  23156. this.wireframeLinewidth = 1;
  23157. this.setValues( parameters );
  23158. }
  23159. copy( source ) {
  23160. super.copy( source );
  23161. this.depthPacking = source.depthPacking;
  23162. this.map = source.map;
  23163. this.alphaMap = source.alphaMap;
  23164. this.displacementMap = source.displacementMap;
  23165. this.displacementScale = source.displacementScale;
  23166. this.displacementBias = source.displacementBias;
  23167. this.wireframe = source.wireframe;
  23168. this.wireframeLinewidth = source.wireframeLinewidth;
  23169. return this;
  23170. }
  23171. }
  23172. class MeshDistanceMaterial extends Material {
  23173. constructor( parameters ) {
  23174. super();
  23175. this.isMeshDistanceMaterial = true;
  23176. this.type = 'MeshDistanceMaterial';
  23177. this.map = null;
  23178. this.alphaMap = null;
  23179. this.displacementMap = null;
  23180. this.displacementScale = 1;
  23181. this.displacementBias = 0;
  23182. this.setValues( parameters );
  23183. }
  23184. copy( source ) {
  23185. super.copy( source );
  23186. this.map = source.map;
  23187. this.alphaMap = source.alphaMap;
  23188. this.displacementMap = source.displacementMap;
  23189. this.displacementScale = source.displacementScale;
  23190. this.displacementBias = source.displacementBias;
  23191. return this;
  23192. }
  23193. }
  23194. class MeshMatcapMaterial extends Material {
  23195. constructor( parameters ) {
  23196. super();
  23197. this.isMeshMatcapMaterial = true;
  23198. this.defines = { 'MATCAP': '' };
  23199. this.type = 'MeshMatcapMaterial';
  23200. this.color = new Color( 0xffffff ); // diffuse
  23201. this.matcap = null;
  23202. this.map = null;
  23203. this.bumpMap = null;
  23204. this.bumpScale = 1;
  23205. this.normalMap = null;
  23206. this.normalMapType = TangentSpaceNormalMap;
  23207. this.normalScale = new Vector2( 1, 1 );
  23208. this.displacementMap = null;
  23209. this.displacementScale = 1;
  23210. this.displacementBias = 0;
  23211. this.alphaMap = null;
  23212. this.flatShading = false;
  23213. this.fog = true;
  23214. this.setValues( parameters );
  23215. }
  23216. copy( source ) {
  23217. super.copy( source );
  23218. this.defines = { 'MATCAP': '' };
  23219. this.color.copy( source.color );
  23220. this.matcap = source.matcap;
  23221. this.map = source.map;
  23222. this.bumpMap = source.bumpMap;
  23223. this.bumpScale = source.bumpScale;
  23224. this.normalMap = source.normalMap;
  23225. this.normalMapType = source.normalMapType;
  23226. this.normalScale.copy( source.normalScale );
  23227. this.displacementMap = source.displacementMap;
  23228. this.displacementScale = source.displacementScale;
  23229. this.displacementBias = source.displacementBias;
  23230. this.alphaMap = source.alphaMap;
  23231. this.flatShading = source.flatShading;
  23232. this.fog = source.fog;
  23233. return this;
  23234. }
  23235. }
  23236. class LineDashedMaterial extends LineBasicMaterial {
  23237. constructor( parameters ) {
  23238. super();
  23239. this.isLineDashedMaterial = true;
  23240. this.type = 'LineDashedMaterial';
  23241. this.scale = 1;
  23242. this.dashSize = 3;
  23243. this.gapSize = 1;
  23244. this.setValues( parameters );
  23245. }
  23246. copy( source ) {
  23247. super.copy( source );
  23248. this.scale = source.scale;
  23249. this.dashSize = source.dashSize;
  23250. this.gapSize = source.gapSize;
  23251. return this;
  23252. }
  23253. }
  23254. // converts an array to a specific type
  23255. function convertArray( array, type, forceClone ) {
  23256. if ( ! array || // let 'undefined' and 'null' pass
  23257. ! forceClone && array.constructor === type ) return array;
  23258. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23259. return new type( array ); // create typed array
  23260. }
  23261. return Array.prototype.slice.call( array ); // create Array
  23262. }
  23263. function isTypedArray( object ) {
  23264. return ArrayBuffer.isView( object ) &&
  23265. ! ( object instanceof DataView );
  23266. }
  23267. // returns an array by which times and values can be sorted
  23268. function getKeyframeOrder( times ) {
  23269. function compareTime( i, j ) {
  23270. return times[ i ] - times[ j ];
  23271. }
  23272. const n = times.length;
  23273. const result = new Array( n );
  23274. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23275. result.sort( compareTime );
  23276. return result;
  23277. }
  23278. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23279. function sortedArray( values, stride, order ) {
  23280. const nValues = values.length;
  23281. const result = new values.constructor( nValues );
  23282. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23283. const srcOffset = order[ i ] * stride;
  23284. for ( let j = 0; j !== stride; ++ j ) {
  23285. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23286. }
  23287. }
  23288. return result;
  23289. }
  23290. // function for parsing AOS keyframe formats
  23291. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23292. let i = 1, key = jsonKeys[ 0 ];
  23293. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23294. key = jsonKeys[ i ++ ];
  23295. }
  23296. if ( key === undefined ) return; // no data
  23297. let value = key[ valuePropertyName ];
  23298. if ( value === undefined ) return; // no data
  23299. if ( Array.isArray( value ) ) {
  23300. do {
  23301. value = key[ valuePropertyName ];
  23302. if ( value !== undefined ) {
  23303. times.push( key.time );
  23304. values.push( ...value ); // push all elements
  23305. }
  23306. key = jsonKeys[ i ++ ];
  23307. } while ( key !== undefined );
  23308. } else if ( value.toArray !== undefined ) {
  23309. // ...assume THREE.Math-ish
  23310. do {
  23311. value = key[ valuePropertyName ];
  23312. if ( value !== undefined ) {
  23313. times.push( key.time );
  23314. value.toArray( values, values.length );
  23315. }
  23316. key = jsonKeys[ i ++ ];
  23317. } while ( key !== undefined );
  23318. } else {
  23319. // otherwise push as-is
  23320. do {
  23321. value = key[ valuePropertyName ];
  23322. if ( value !== undefined ) {
  23323. times.push( key.time );
  23324. values.push( value );
  23325. }
  23326. key = jsonKeys[ i ++ ];
  23327. } while ( key !== undefined );
  23328. }
  23329. }
  23330. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23331. const clip = sourceClip.clone();
  23332. clip.name = name;
  23333. const tracks = [];
  23334. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23335. const track = clip.tracks[ i ];
  23336. const valueSize = track.getValueSize();
  23337. const times = [];
  23338. const values = [];
  23339. for ( let j = 0; j < track.times.length; ++ j ) {
  23340. const frame = track.times[ j ] * fps;
  23341. if ( frame < startFrame || frame >= endFrame ) continue;
  23342. times.push( track.times[ j ] );
  23343. for ( let k = 0; k < valueSize; ++ k ) {
  23344. values.push( track.values[ j * valueSize + k ] );
  23345. }
  23346. }
  23347. if ( times.length === 0 ) continue;
  23348. track.times = convertArray( times, track.times.constructor );
  23349. track.values = convertArray( values, track.values.constructor );
  23350. tracks.push( track );
  23351. }
  23352. clip.tracks = tracks;
  23353. // find minimum .times value across all tracks in the trimmed clip
  23354. let minStartTime = Infinity;
  23355. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23356. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23357. minStartTime = clip.tracks[ i ].times[ 0 ];
  23358. }
  23359. }
  23360. // shift all tracks such that clip begins at t=0
  23361. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23362. clip.tracks[ i ].shift( -1 * minStartTime );
  23363. }
  23364. clip.resetDuration();
  23365. return clip;
  23366. }
  23367. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23368. if ( fps <= 0 ) fps = 30;
  23369. const numTracks = referenceClip.tracks.length;
  23370. const referenceTime = referenceFrame / fps;
  23371. // Make each track's values relative to the values at the reference frame
  23372. for ( let i = 0; i < numTracks; ++ i ) {
  23373. const referenceTrack = referenceClip.tracks[ i ];
  23374. const referenceTrackType = referenceTrack.ValueTypeName;
  23375. // Skip this track if it's non-numeric
  23376. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23377. // Find the track in the target clip whose name and type matches the reference track
  23378. const targetTrack = targetClip.tracks.find( function ( track ) {
  23379. return track.name === referenceTrack.name
  23380. && track.ValueTypeName === referenceTrackType;
  23381. } );
  23382. if ( targetTrack === undefined ) continue;
  23383. let referenceOffset = 0;
  23384. const referenceValueSize = referenceTrack.getValueSize();
  23385. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23386. referenceOffset = referenceValueSize / 3;
  23387. }
  23388. let targetOffset = 0;
  23389. const targetValueSize = targetTrack.getValueSize();
  23390. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23391. targetOffset = targetValueSize / 3;
  23392. }
  23393. const lastIndex = referenceTrack.times.length - 1;
  23394. let referenceValue;
  23395. // Find the value to subtract out of the track
  23396. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23397. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23398. const startIndex = referenceOffset;
  23399. const endIndex = referenceValueSize - referenceOffset;
  23400. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  23401. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23402. // Reference frame is after the last keyframe, so just use the last keyframe
  23403. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23404. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23405. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  23406. } else {
  23407. // Interpolate to the reference value
  23408. const interpolant = referenceTrack.createInterpolant();
  23409. const startIndex = referenceOffset;
  23410. const endIndex = referenceValueSize - referenceOffset;
  23411. interpolant.evaluate( referenceTime );
  23412. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  23413. }
  23414. // Conjugate the quaternion
  23415. if ( referenceTrackType === 'quaternion' ) {
  23416. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23417. referenceQuat.toArray( referenceValue );
  23418. }
  23419. // Subtract the reference value from all of the track values
  23420. const numTimes = targetTrack.times.length;
  23421. for ( let j = 0; j < numTimes; ++ j ) {
  23422. const valueStart = j * targetValueSize + targetOffset;
  23423. if ( referenceTrackType === 'quaternion' ) {
  23424. // Multiply the conjugate for quaternion track types
  23425. Quaternion.multiplyQuaternionsFlat(
  23426. targetTrack.values,
  23427. valueStart,
  23428. referenceValue,
  23429. 0,
  23430. targetTrack.values,
  23431. valueStart
  23432. );
  23433. } else {
  23434. const valueEnd = targetValueSize - targetOffset * 2;
  23435. // Subtract each value for all other numeric track types
  23436. for ( let k = 0; k < valueEnd; ++ k ) {
  23437. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23438. }
  23439. }
  23440. }
  23441. }
  23442. targetClip.blendMode = AdditiveAnimationBlendMode;
  23443. return targetClip;
  23444. }
  23445. const AnimationUtils = {
  23446. convertArray: convertArray,
  23447. isTypedArray: isTypedArray,
  23448. getKeyframeOrder: getKeyframeOrder,
  23449. sortedArray: sortedArray,
  23450. flattenJSON: flattenJSON,
  23451. subclip: subclip,
  23452. makeClipAdditive: makeClipAdditive
  23453. };
  23454. /**
  23455. * Abstract base class of interpolants over parametric samples.
  23456. *
  23457. * The parameter domain is one dimensional, typically the time or a path
  23458. * along a curve defined by the data.
  23459. *
  23460. * The sample values can have any dimensionality and derived classes may
  23461. * apply special interpretations to the data.
  23462. *
  23463. * This class provides the interval seek in a Template Method, deferring
  23464. * the actual interpolation to derived classes.
  23465. *
  23466. * Time complexity is O(1) for linear access crossing at most two points
  23467. * and O(log N) for random access, where N is the number of positions.
  23468. *
  23469. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  23470. *
  23471. * @abstract
  23472. */
  23473. class Interpolant {
  23474. /**
  23475. * Constructs a new interpolant.
  23476. *
  23477. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23478. * @param {TypedArray} sampleValues - The sample values.
  23479. * @param {number} sampleSize - The sample size
  23480. * @param {TypedArray} [resultBuffer] - The result buffer.
  23481. */
  23482. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23483. /**
  23484. * The parameter positions.
  23485. *
  23486. * @type {TypedArray}
  23487. */
  23488. this.parameterPositions = parameterPositions;
  23489. /**
  23490. * A cache index.
  23491. *
  23492. * @private
  23493. * @type {number}
  23494. * @default 0
  23495. */
  23496. this._cachedIndex = 0;
  23497. /**
  23498. * The result buffer.
  23499. *
  23500. * @type {TypedArray}
  23501. */
  23502. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  23503. /**
  23504. * The sample values.
  23505. *
  23506. * @type {TypedArray}
  23507. */
  23508. this.sampleValues = sampleValues;
  23509. /**
  23510. * The value size.
  23511. *
  23512. * @type {TypedArray}
  23513. */
  23514. this.valueSize = sampleSize;
  23515. /**
  23516. * The interpolation settings.
  23517. *
  23518. * @type {?Object}
  23519. * @default null
  23520. */
  23521. this.settings = null;
  23522. /**
  23523. * The default settings object.
  23524. *
  23525. * @type {Object}
  23526. */
  23527. this.DefaultSettings_ = {};
  23528. }
  23529. /**
  23530. * Evaluate the interpolant at position `t`.
  23531. *
  23532. * @param {number} t - The interpolation factor.
  23533. * @return {TypedArray} The result buffer.
  23534. */
  23535. evaluate( t ) {
  23536. const pp = this.parameterPositions;
  23537. let i1 = this._cachedIndex,
  23538. t1 = pp[ i1 ],
  23539. t0 = pp[ i1 - 1 ];
  23540. validate_interval: {
  23541. seek: {
  23542. let right;
  23543. linear_scan: {
  23544. //- See http://jsperf.com/comparison-to-undefined/3
  23545. //- slower code:
  23546. //-
  23547. //- if ( t >= t1 || t1 === undefined ) {
  23548. forward_scan: if ( ! ( t < t1 ) ) {
  23549. for ( let giveUpAt = i1 + 2; ; ) {
  23550. if ( t1 === undefined ) {
  23551. if ( t < t0 ) break forward_scan;
  23552. // after end
  23553. i1 = pp.length;
  23554. this._cachedIndex = i1;
  23555. return this.copySampleValue_( i1 - 1 );
  23556. }
  23557. if ( i1 === giveUpAt ) break; // this loop
  23558. t0 = t1;
  23559. t1 = pp[ ++ i1 ];
  23560. if ( t < t1 ) {
  23561. // we have arrived at the sought interval
  23562. break seek;
  23563. }
  23564. }
  23565. // prepare binary search on the right side of the index
  23566. right = pp.length;
  23567. break linear_scan;
  23568. }
  23569. //- slower code:
  23570. //- if ( t < t0 || t0 === undefined ) {
  23571. if ( ! ( t >= t0 ) ) {
  23572. // looping?
  23573. const t1global = pp[ 1 ];
  23574. if ( t < t1global ) {
  23575. i1 = 2; // + 1, using the scan for the details
  23576. t0 = t1global;
  23577. }
  23578. // linear reverse scan
  23579. for ( let giveUpAt = i1 - 2; ; ) {
  23580. if ( t0 === undefined ) {
  23581. // before start
  23582. this._cachedIndex = 0;
  23583. return this.copySampleValue_( 0 );
  23584. }
  23585. if ( i1 === giveUpAt ) break; // this loop
  23586. t1 = t0;
  23587. t0 = pp[ -- i1 - 1 ];
  23588. if ( t >= t0 ) {
  23589. // we have arrived at the sought interval
  23590. break seek;
  23591. }
  23592. }
  23593. // prepare binary search on the left side of the index
  23594. right = i1;
  23595. i1 = 0;
  23596. break linear_scan;
  23597. }
  23598. // the interval is valid
  23599. break validate_interval;
  23600. } // linear scan
  23601. // binary search
  23602. while ( i1 < right ) {
  23603. const mid = ( i1 + right ) >>> 1;
  23604. if ( t < pp[ mid ] ) {
  23605. right = mid;
  23606. } else {
  23607. i1 = mid + 1;
  23608. }
  23609. }
  23610. t1 = pp[ i1 ];
  23611. t0 = pp[ i1 - 1 ];
  23612. // check boundary cases, again
  23613. if ( t0 === undefined ) {
  23614. this._cachedIndex = 0;
  23615. return this.copySampleValue_( 0 );
  23616. }
  23617. if ( t1 === undefined ) {
  23618. i1 = pp.length;
  23619. this._cachedIndex = i1;
  23620. return this.copySampleValue_( i1 - 1 );
  23621. }
  23622. } // seek
  23623. this._cachedIndex = i1;
  23624. this.intervalChanged_( i1, t0, t1 );
  23625. } // validate_interval
  23626. return this.interpolate_( i1, t0, t, t1 );
  23627. }
  23628. /**
  23629. * Returns the interpolation settings.
  23630. *
  23631. * @return {Object} The interpolation settings.
  23632. */
  23633. getSettings_() {
  23634. return this.settings || this.DefaultSettings_;
  23635. }
  23636. /**
  23637. * Copies a sample value to the result buffer.
  23638. *
  23639. * @param {number} index - An index into the sample value buffer.
  23640. * @return {TypedArray} The result buffer.
  23641. */
  23642. copySampleValue_( index ) {
  23643. // copies a sample value to the result buffer
  23644. const result = this.resultBuffer,
  23645. values = this.sampleValues,
  23646. stride = this.valueSize,
  23647. offset = index * stride;
  23648. for ( let i = 0; i !== stride; ++ i ) {
  23649. result[ i ] = values[ offset + i ];
  23650. }
  23651. return result;
  23652. }
  23653. /**
  23654. * Copies a sample value to the result buffer.
  23655. *
  23656. * @abstract
  23657. * @param {number} i1 - An index into the sample value buffer.
  23658. * @param {number} t0 - The previous interpolation factor.
  23659. * @param {number} t - The current interpolation factor.
  23660. * @param {number} t1 - The next interpolation factor.
  23661. * @return {TypedArray} The result buffer.
  23662. */
  23663. interpolate_( /* i1, t0, t, t1 */ ) {
  23664. throw new Error( 'call to abstract method' );
  23665. // implementations shall return this.resultBuffer
  23666. }
  23667. /**
  23668. * Optional method that is executed when the interval has changed.
  23669. *
  23670. * @param {number} i1 - An index into the sample value buffer.
  23671. * @param {number} t0 - The previous interpolation factor.
  23672. * @param {number} t - The current interpolation factor.
  23673. */
  23674. intervalChanged_( /* i1, t0, t1 */ ) {
  23675. // empty
  23676. }
  23677. }
  23678. /**
  23679. * Fast and simple cubic spline interpolant.
  23680. *
  23681. * It was derived from a Hermitian construction setting the first derivative
  23682. * at each sample position to the linear slope between neighboring positions
  23683. * over their parameter interval.
  23684. *
  23685. * @augments Interpolant
  23686. */
  23687. class CubicInterpolant extends Interpolant {
  23688. /**
  23689. * Constructs a new cubic interpolant.
  23690. *
  23691. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23692. * @param {TypedArray} sampleValues - The sample values.
  23693. * @param {number} sampleSize - The sample size
  23694. * @param {TypedArray} [resultBuffer] - The result buffer.
  23695. */
  23696. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23697. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23698. this._weightPrev = -0;
  23699. this._offsetPrev = -0;
  23700. this._weightNext = -0;
  23701. this._offsetNext = -0;
  23702. this.DefaultSettings_ = {
  23703. endingStart: ZeroCurvatureEnding,
  23704. endingEnd: ZeroCurvatureEnding
  23705. };
  23706. }
  23707. intervalChanged_( i1, t0, t1 ) {
  23708. const pp = this.parameterPositions;
  23709. let iPrev = i1 - 2,
  23710. iNext = i1 + 1,
  23711. tPrev = pp[ iPrev ],
  23712. tNext = pp[ iNext ];
  23713. if ( tPrev === undefined ) {
  23714. switch ( this.getSettings_().endingStart ) {
  23715. case ZeroSlopeEnding:
  23716. // f'(t0) = 0
  23717. iPrev = i1;
  23718. tPrev = 2 * t0 - t1;
  23719. break;
  23720. case WrapAroundEnding:
  23721. // use the other end of the curve
  23722. iPrev = pp.length - 2;
  23723. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23724. break;
  23725. default: // ZeroCurvatureEnding
  23726. // f''(t0) = 0 a.k.a. Natural Spline
  23727. iPrev = i1;
  23728. tPrev = t1;
  23729. }
  23730. }
  23731. if ( tNext === undefined ) {
  23732. switch ( this.getSettings_().endingEnd ) {
  23733. case ZeroSlopeEnding:
  23734. // f'(tN) = 0
  23735. iNext = i1;
  23736. tNext = 2 * t1 - t0;
  23737. break;
  23738. case WrapAroundEnding:
  23739. // use the other end of the curve
  23740. iNext = 1;
  23741. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23742. break;
  23743. default: // ZeroCurvatureEnding
  23744. // f''(tN) = 0, a.k.a. Natural Spline
  23745. iNext = i1 - 1;
  23746. tNext = t0;
  23747. }
  23748. }
  23749. const halfDt = ( t1 - t0 ) * 0.5,
  23750. stride = this.valueSize;
  23751. this._weightPrev = halfDt / ( t0 - tPrev );
  23752. this._weightNext = halfDt / ( tNext - t1 );
  23753. this._offsetPrev = iPrev * stride;
  23754. this._offsetNext = iNext * stride;
  23755. }
  23756. interpolate_( i1, t0, t, t1 ) {
  23757. const result = this.resultBuffer,
  23758. values = this.sampleValues,
  23759. stride = this.valueSize,
  23760. o1 = i1 * stride, o0 = o1 - stride,
  23761. oP = this._offsetPrev, oN = this._offsetNext,
  23762. wP = this._weightPrev, wN = this._weightNext,
  23763. p = ( t - t0 ) / ( t1 - t0 ),
  23764. pp = p * p,
  23765. ppp = pp * p;
  23766. // evaluate polynomials
  23767. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23768. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  23769. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23770. const sN = wN * ppp - wN * pp;
  23771. // combine data linearly
  23772. for ( let i = 0; i !== stride; ++ i ) {
  23773. result[ i ] =
  23774. sP * values[ oP + i ] +
  23775. s0 * values[ o0 + i ] +
  23776. s1 * values[ o1 + i ] +
  23777. sN * values[ oN + i ];
  23778. }
  23779. return result;
  23780. }
  23781. }
  23782. /**
  23783. * A basic linear interpolant.
  23784. *
  23785. * @augments Interpolant
  23786. */
  23787. class LinearInterpolant extends Interpolant {
  23788. /**
  23789. * Constructs a new linear interpolant.
  23790. *
  23791. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23792. * @param {TypedArray} sampleValues - The sample values.
  23793. * @param {number} sampleSize - The sample size
  23794. * @param {TypedArray} [resultBuffer] - The result buffer.
  23795. */
  23796. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23797. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23798. }
  23799. interpolate_( i1, t0, t, t1 ) {
  23800. const result = this.resultBuffer,
  23801. values = this.sampleValues,
  23802. stride = this.valueSize,
  23803. offset1 = i1 * stride,
  23804. offset0 = offset1 - stride,
  23805. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23806. weight0 = 1 - weight1;
  23807. for ( let i = 0; i !== stride; ++ i ) {
  23808. result[ i ] =
  23809. values[ offset0 + i ] * weight0 +
  23810. values[ offset1 + i ] * weight1;
  23811. }
  23812. return result;
  23813. }
  23814. }
  23815. /**
  23816. * Interpolant that evaluates to the sample value at the position preceding
  23817. * the parameter.
  23818. *
  23819. * @augments Interpolant
  23820. */
  23821. class DiscreteInterpolant extends Interpolant {
  23822. /**
  23823. * Constructs a new discrete interpolant.
  23824. *
  23825. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  23826. * @param {TypedArray} sampleValues - The sample values.
  23827. * @param {number} sampleSize - The sample size
  23828. * @param {TypedArray} [resultBuffer] - The result buffer.
  23829. */
  23830. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23831. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23832. }
  23833. interpolate_( i1 /*, t0, t, t1 */ ) {
  23834. return this.copySampleValue_( i1 - 1 );
  23835. }
  23836. }
  23837. class KeyframeTrack {
  23838. constructor( name, times, values, interpolation ) {
  23839. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23840. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23841. this.name = name;
  23842. this.times = convertArray( times, this.TimeBufferType );
  23843. this.values = convertArray( values, this.ValueBufferType );
  23844. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23845. }
  23846. // Serialization (in static context, because of constructor invocation
  23847. // and automatic invocation of .toJSON):
  23848. static toJSON( track ) {
  23849. const trackType = track.constructor;
  23850. let json;
  23851. // derived classes can define a static toJSON method
  23852. if ( trackType.toJSON !== this.toJSON ) {
  23853. json = trackType.toJSON( track );
  23854. } else {
  23855. // by default, we assume the data can be serialized as-is
  23856. json = {
  23857. 'name': track.name,
  23858. 'times': convertArray( track.times, Array ),
  23859. 'values': convertArray( track.values, Array )
  23860. };
  23861. const interpolation = track.getInterpolation();
  23862. if ( interpolation !== track.DefaultInterpolation ) {
  23863. json.interpolation = interpolation;
  23864. }
  23865. }
  23866. json.type = track.ValueTypeName; // mandatory
  23867. return json;
  23868. }
  23869. InterpolantFactoryMethodDiscrete( result ) {
  23870. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23871. }
  23872. InterpolantFactoryMethodLinear( result ) {
  23873. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23874. }
  23875. InterpolantFactoryMethodSmooth( result ) {
  23876. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23877. }
  23878. setInterpolation( interpolation ) {
  23879. let factoryMethod;
  23880. switch ( interpolation ) {
  23881. case InterpolateDiscrete:
  23882. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23883. break;
  23884. case InterpolateLinear:
  23885. factoryMethod = this.InterpolantFactoryMethodLinear;
  23886. break;
  23887. case InterpolateSmooth:
  23888. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23889. break;
  23890. }
  23891. if ( factoryMethod === undefined ) {
  23892. const message = 'unsupported interpolation for ' +
  23893. this.ValueTypeName + ' keyframe track named ' + this.name;
  23894. if ( this.createInterpolant === undefined ) {
  23895. // fall back to default, unless the default itself is messed up
  23896. if ( interpolation !== this.DefaultInterpolation ) {
  23897. this.setInterpolation( this.DefaultInterpolation );
  23898. } else {
  23899. throw new Error( message ); // fatal, in this case
  23900. }
  23901. }
  23902. console.warn( 'THREE.KeyframeTrack:', message );
  23903. return this;
  23904. }
  23905. this.createInterpolant = factoryMethod;
  23906. return this;
  23907. }
  23908. getInterpolation() {
  23909. switch ( this.createInterpolant ) {
  23910. case this.InterpolantFactoryMethodDiscrete:
  23911. return InterpolateDiscrete;
  23912. case this.InterpolantFactoryMethodLinear:
  23913. return InterpolateLinear;
  23914. case this.InterpolantFactoryMethodSmooth:
  23915. return InterpolateSmooth;
  23916. }
  23917. }
  23918. getValueSize() {
  23919. return this.values.length / this.times.length;
  23920. }
  23921. // move all keyframes either forwards or backwards in time
  23922. shift( timeOffset ) {
  23923. if ( timeOffset !== 0.0 ) {
  23924. const times = this.times;
  23925. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23926. times[ i ] += timeOffset;
  23927. }
  23928. }
  23929. return this;
  23930. }
  23931. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23932. scale( timeScale ) {
  23933. if ( timeScale !== 1.0 ) {
  23934. const times = this.times;
  23935. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23936. times[ i ] *= timeScale;
  23937. }
  23938. }
  23939. return this;
  23940. }
  23941. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23942. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23943. trim( startTime, endTime ) {
  23944. const times = this.times,
  23945. nKeys = times.length;
  23946. let from = 0,
  23947. to = nKeys - 1;
  23948. while ( from !== nKeys && times[ from ] < startTime ) {
  23949. ++ from;
  23950. }
  23951. while ( to !== -1 && times[ to ] > endTime ) {
  23952. -- to;
  23953. }
  23954. ++ to; // inclusive -> exclusive bound
  23955. if ( from !== 0 || to !== nKeys ) {
  23956. // empty tracks are forbidden, so keep at least one keyframe
  23957. if ( from >= to ) {
  23958. to = Math.max( to, 1 );
  23959. from = to - 1;
  23960. }
  23961. const stride = this.getValueSize();
  23962. this.times = times.slice( from, to );
  23963. this.values = this.values.slice( from * stride, to * stride );
  23964. }
  23965. return this;
  23966. }
  23967. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23968. validate() {
  23969. let valid = true;
  23970. const valueSize = this.getValueSize();
  23971. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23972. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23973. valid = false;
  23974. }
  23975. const times = this.times,
  23976. values = this.values,
  23977. nKeys = times.length;
  23978. if ( nKeys === 0 ) {
  23979. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23980. valid = false;
  23981. }
  23982. let prevTime = null;
  23983. for ( let i = 0; i !== nKeys; i ++ ) {
  23984. const currTime = times[ i ];
  23985. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23986. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23987. valid = false;
  23988. break;
  23989. }
  23990. if ( prevTime !== null && prevTime > currTime ) {
  23991. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23992. valid = false;
  23993. break;
  23994. }
  23995. prevTime = currTime;
  23996. }
  23997. if ( values !== undefined ) {
  23998. if ( isTypedArray( values ) ) {
  23999. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  24000. const value = values[ i ];
  24001. if ( isNaN( value ) ) {
  24002. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24003. valid = false;
  24004. break;
  24005. }
  24006. }
  24007. }
  24008. }
  24009. return valid;
  24010. }
  24011. // removes equivalent sequential keys as common in morph target sequences
  24012. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24013. optimize() {
  24014. // times or values may be shared with other tracks, so overwriting is unsafe
  24015. const times = this.times.slice(),
  24016. values = this.values.slice(),
  24017. stride = this.getValueSize(),
  24018. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24019. lastIndex = times.length - 1;
  24020. let writeIndex = 1;
  24021. for ( let i = 1; i < lastIndex; ++ i ) {
  24022. let keep = false;
  24023. const time = times[ i ];
  24024. const timeNext = times[ i + 1 ];
  24025. // remove adjacent keyframes scheduled at the same time
  24026. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  24027. if ( ! smoothInterpolation ) {
  24028. // remove unnecessary keyframes same as their neighbors
  24029. const offset = i * stride,
  24030. offsetP = offset - stride,
  24031. offsetN = offset + stride;
  24032. for ( let j = 0; j !== stride; ++ j ) {
  24033. const value = values[ offset + j ];
  24034. if ( value !== values[ offsetP + j ] ||
  24035. value !== values[ offsetN + j ] ) {
  24036. keep = true;
  24037. break;
  24038. }
  24039. }
  24040. } else {
  24041. keep = true;
  24042. }
  24043. }
  24044. // in-place compaction
  24045. if ( keep ) {
  24046. if ( i !== writeIndex ) {
  24047. times[ writeIndex ] = times[ i ];
  24048. const readOffset = i * stride,
  24049. writeOffset = writeIndex * stride;
  24050. for ( let j = 0; j !== stride; ++ j ) {
  24051. values[ writeOffset + j ] = values[ readOffset + j ];
  24052. }
  24053. }
  24054. ++ writeIndex;
  24055. }
  24056. }
  24057. // flush last keyframe (compaction looks ahead)
  24058. if ( lastIndex > 0 ) {
  24059. times[ writeIndex ] = times[ lastIndex ];
  24060. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24061. values[ writeOffset + j ] = values[ readOffset + j ];
  24062. }
  24063. ++ writeIndex;
  24064. }
  24065. if ( writeIndex !== times.length ) {
  24066. this.times = times.slice( 0, writeIndex );
  24067. this.values = values.slice( 0, writeIndex * stride );
  24068. } else {
  24069. this.times = times;
  24070. this.values = values;
  24071. }
  24072. return this;
  24073. }
  24074. clone() {
  24075. const times = this.times.slice();
  24076. const values = this.values.slice();
  24077. const TypedKeyframeTrack = this.constructor;
  24078. const track = new TypedKeyframeTrack( this.name, times, values );
  24079. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24080. track.createInterpolant = this.createInterpolant;
  24081. return track;
  24082. }
  24083. }
  24084. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  24085. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  24086. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24087. /**
  24088. * A Track of Boolean keyframe values.
  24089. */
  24090. class BooleanKeyframeTrack extends KeyframeTrack {
  24091. // No interpolation parameter because only InterpolateDiscrete is valid.
  24092. constructor( name, times, values ) {
  24093. super( name, times, values );
  24094. }
  24095. }
  24096. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  24097. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  24098. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24099. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24100. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24101. /**
  24102. * A Track of keyframe values that represent color.
  24103. */
  24104. class ColorKeyframeTrack extends KeyframeTrack {}
  24105. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  24106. /**
  24107. * A Track of numeric keyframe values.
  24108. */
  24109. class NumberKeyframeTrack extends KeyframeTrack {}
  24110. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  24111. /**
  24112. * Spherical linear unit quaternion interpolant.
  24113. *
  24114. * @augments Interpolant
  24115. */
  24116. class QuaternionLinearInterpolant extends Interpolant {
  24117. /**
  24118. * Constructs a new SLERP interpolant.
  24119. *
  24120. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  24121. * @param {TypedArray} sampleValues - The sample values.
  24122. * @param {number} sampleSize - The sample size
  24123. * @param {TypedArray} [resultBuffer] - The result buffer.
  24124. */
  24125. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24126. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24127. }
  24128. interpolate_( i1, t0, t, t1 ) {
  24129. const result = this.resultBuffer,
  24130. values = this.sampleValues,
  24131. stride = this.valueSize,
  24132. alpha = ( t - t0 ) / ( t1 - t0 );
  24133. let offset = i1 * stride;
  24134. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  24135. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24136. }
  24137. return result;
  24138. }
  24139. }
  24140. /**
  24141. * A Track of quaternion keyframe values.
  24142. */
  24143. class QuaternionKeyframeTrack extends KeyframeTrack {
  24144. InterpolantFactoryMethodLinear( result ) {
  24145. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24146. }
  24147. }
  24148. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  24149. // ValueBufferType is inherited
  24150. // DefaultInterpolation is inherited;
  24151. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24152. /**
  24153. * A Track that interpolates Strings
  24154. */
  24155. class StringKeyframeTrack extends KeyframeTrack {
  24156. // No interpolation parameter because only InterpolateDiscrete is valid.
  24157. constructor( name, times, values ) {
  24158. super( name, times, values );
  24159. }
  24160. }
  24161. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  24162. StringKeyframeTrack.prototype.ValueBufferType = Array;
  24163. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24164. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24165. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24166. /**
  24167. * A Track of vectored keyframe values.
  24168. */
  24169. class VectorKeyframeTrack extends KeyframeTrack {}
  24170. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  24171. class AnimationClip {
  24172. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  24173. this.name = name;
  24174. this.tracks = tracks;
  24175. this.duration = duration;
  24176. this.blendMode = blendMode;
  24177. this.uuid = generateUUID();
  24178. // this means it should figure out its duration by scanning the tracks
  24179. if ( this.duration < 0 ) {
  24180. this.resetDuration();
  24181. }
  24182. }
  24183. static parse( json ) {
  24184. const tracks = [],
  24185. jsonTracks = json.tracks,
  24186. frameTime = 1.0 / ( json.fps || 1.0 );
  24187. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24188. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  24189. }
  24190. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  24191. clip.uuid = json.uuid;
  24192. return clip;
  24193. }
  24194. static toJSON( clip ) {
  24195. const tracks = [],
  24196. clipTracks = clip.tracks;
  24197. const json = {
  24198. 'name': clip.name,
  24199. 'duration': clip.duration,
  24200. 'tracks': tracks,
  24201. 'uuid': clip.uuid,
  24202. 'blendMode': clip.blendMode
  24203. };
  24204. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  24205. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  24206. }
  24207. return json;
  24208. }
  24209. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  24210. const numMorphTargets = morphTargetSequence.length;
  24211. const tracks = [];
  24212. for ( let i = 0; i < numMorphTargets; i ++ ) {
  24213. let times = [];
  24214. let values = [];
  24215. times.push(
  24216. ( i + numMorphTargets - 1 ) % numMorphTargets,
  24217. i,
  24218. ( i + 1 ) % numMorphTargets );
  24219. values.push( 0, 1, 0 );
  24220. const order = getKeyframeOrder( times );
  24221. times = sortedArray( times, 1, order );
  24222. values = sortedArray( values, 1, order );
  24223. // if there is a key at the first frame, duplicate it as the
  24224. // last frame as well for perfect loop.
  24225. if ( ! noLoop && times[ 0 ] === 0 ) {
  24226. times.push( numMorphTargets );
  24227. values.push( values[ 0 ] );
  24228. }
  24229. tracks.push(
  24230. new NumberKeyframeTrack(
  24231. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  24232. times, values
  24233. ).scale( 1.0 / fps ) );
  24234. }
  24235. return new this( name, -1, tracks );
  24236. }
  24237. static findByName( objectOrClipArray, name ) {
  24238. let clipArray = objectOrClipArray;
  24239. if ( ! Array.isArray( objectOrClipArray ) ) {
  24240. const o = objectOrClipArray;
  24241. clipArray = o.geometry && o.geometry.animations || o.animations;
  24242. }
  24243. for ( let i = 0; i < clipArray.length; i ++ ) {
  24244. if ( clipArray[ i ].name === name ) {
  24245. return clipArray[ i ];
  24246. }
  24247. }
  24248. return null;
  24249. }
  24250. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24251. const animationToMorphTargets = {};
  24252. // tested with https://regex101.com/ on trick sequences
  24253. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24254. const pattern = /^([\w-]*?)([\d]+)$/;
  24255. // sort morph target names into animation groups based
  24256. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24257. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24258. const morphTarget = morphTargets[ i ];
  24259. const parts = morphTarget.name.match( pattern );
  24260. if ( parts && parts.length > 1 ) {
  24261. const name = parts[ 1 ];
  24262. let animationMorphTargets = animationToMorphTargets[ name ];
  24263. if ( ! animationMorphTargets ) {
  24264. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24265. }
  24266. animationMorphTargets.push( morphTarget );
  24267. }
  24268. }
  24269. const clips = [];
  24270. for ( const name in animationToMorphTargets ) {
  24271. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24272. }
  24273. return clips;
  24274. }
  24275. // parse the animation.hierarchy format
  24276. static parseAnimation( animation, bones ) {
  24277. if ( ! animation ) {
  24278. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24279. return null;
  24280. }
  24281. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24282. // only return track if there are actually keys.
  24283. if ( animationKeys.length !== 0 ) {
  24284. const times = [];
  24285. const values = [];
  24286. flattenJSON( animationKeys, times, values, propertyName );
  24287. // empty keys are filtered out, so check again
  24288. if ( times.length !== 0 ) {
  24289. destTracks.push( new trackType( trackName, times, values ) );
  24290. }
  24291. }
  24292. };
  24293. const tracks = [];
  24294. const clipName = animation.name || 'default';
  24295. const fps = animation.fps || 30;
  24296. const blendMode = animation.blendMode;
  24297. // automatic length determination in AnimationClip.
  24298. let duration = animation.length || -1;
  24299. const hierarchyTracks = animation.hierarchy || [];
  24300. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24301. const animationKeys = hierarchyTracks[ h ].keys;
  24302. // skip empty tracks
  24303. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24304. // process morph targets
  24305. if ( animationKeys[ 0 ].morphTargets ) {
  24306. // figure out all morph targets used in this track
  24307. const morphTargetNames = {};
  24308. let k;
  24309. for ( k = 0; k < animationKeys.length; k ++ ) {
  24310. if ( animationKeys[ k ].morphTargets ) {
  24311. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24312. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  24313. }
  24314. }
  24315. }
  24316. // create a track for each morph target with all zero
  24317. // morphTargetInfluences except for the keys in which
  24318. // the morphTarget is named.
  24319. for ( const morphTargetName in morphTargetNames ) {
  24320. const times = [];
  24321. const values = [];
  24322. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24323. const animationKey = animationKeys[ k ];
  24324. times.push( animationKey.time );
  24325. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24326. }
  24327. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24328. }
  24329. duration = morphTargetNames.length * fps;
  24330. } else {
  24331. // ...assume skeletal animation
  24332. const boneName = '.bones[' + bones[ h ].name + ']';
  24333. addNonemptyTrack(
  24334. VectorKeyframeTrack, boneName + '.position',
  24335. animationKeys, 'pos', tracks );
  24336. addNonemptyTrack(
  24337. QuaternionKeyframeTrack, boneName + '.quaternion',
  24338. animationKeys, 'rot', tracks );
  24339. addNonemptyTrack(
  24340. VectorKeyframeTrack, boneName + '.scale',
  24341. animationKeys, 'scl', tracks );
  24342. }
  24343. }
  24344. if ( tracks.length === 0 ) {
  24345. return null;
  24346. }
  24347. const clip = new this( clipName, duration, tracks, blendMode );
  24348. return clip;
  24349. }
  24350. resetDuration() {
  24351. const tracks = this.tracks;
  24352. let duration = 0;
  24353. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24354. const track = this.tracks[ i ];
  24355. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24356. }
  24357. this.duration = duration;
  24358. return this;
  24359. }
  24360. trim() {
  24361. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24362. this.tracks[ i ].trim( 0, this.duration );
  24363. }
  24364. return this;
  24365. }
  24366. validate() {
  24367. let valid = true;
  24368. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24369. valid = valid && this.tracks[ i ].validate();
  24370. }
  24371. return valid;
  24372. }
  24373. optimize() {
  24374. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24375. this.tracks[ i ].optimize();
  24376. }
  24377. return this;
  24378. }
  24379. clone() {
  24380. const tracks = [];
  24381. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24382. tracks.push( this.tracks[ i ].clone() );
  24383. }
  24384. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24385. }
  24386. toJSON() {
  24387. return this.constructor.toJSON( this );
  24388. }
  24389. }
  24390. function getTrackTypeForValueTypeName( typeName ) {
  24391. switch ( typeName.toLowerCase() ) {
  24392. case 'scalar':
  24393. case 'double':
  24394. case 'float':
  24395. case 'number':
  24396. case 'integer':
  24397. return NumberKeyframeTrack;
  24398. case 'vector':
  24399. case 'vector2':
  24400. case 'vector3':
  24401. case 'vector4':
  24402. return VectorKeyframeTrack;
  24403. case 'color':
  24404. return ColorKeyframeTrack;
  24405. case 'quaternion':
  24406. return QuaternionKeyframeTrack;
  24407. case 'bool':
  24408. case 'boolean':
  24409. return BooleanKeyframeTrack;
  24410. case 'string':
  24411. return StringKeyframeTrack;
  24412. }
  24413. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24414. }
  24415. function parseKeyframeTrack( json ) {
  24416. if ( json.type === undefined ) {
  24417. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24418. }
  24419. const trackType = getTrackTypeForValueTypeName( json.type );
  24420. if ( json.times === undefined ) {
  24421. const times = [], values = [];
  24422. flattenJSON( json.keys, times, values, 'value' );
  24423. json.times = times;
  24424. json.values = values;
  24425. }
  24426. // derived classes can define a static parse method
  24427. if ( trackType.parse !== undefined ) {
  24428. return trackType.parse( json );
  24429. } else {
  24430. // by default, we assume a constructor compatible with the base
  24431. return new trackType( json.name, json.times, json.values, json.interpolation );
  24432. }
  24433. }
  24434. const Cache = {
  24435. enabled: false,
  24436. files: {},
  24437. add: function ( key, file ) {
  24438. if ( this.enabled === false ) return;
  24439. // console.log( 'THREE.Cache', 'Adding key:', key );
  24440. this.files[ key ] = file;
  24441. },
  24442. get: function ( key ) {
  24443. if ( this.enabled === false ) return;
  24444. // console.log( 'THREE.Cache', 'Checking key:', key );
  24445. return this.files[ key ];
  24446. },
  24447. remove: function ( key ) {
  24448. delete this.files[ key ];
  24449. },
  24450. clear: function () {
  24451. this.files = {};
  24452. }
  24453. };
  24454. class LoadingManager {
  24455. constructor( onLoad, onProgress, onError ) {
  24456. const scope = this;
  24457. let isLoading = false;
  24458. let itemsLoaded = 0;
  24459. let itemsTotal = 0;
  24460. let urlModifier = undefined;
  24461. const handlers = [];
  24462. // Refer to #5689 for the reason why we don't set .onStart
  24463. // in the constructor
  24464. this.onStart = undefined;
  24465. this.onLoad = onLoad;
  24466. this.onProgress = onProgress;
  24467. this.onError = onError;
  24468. this.itemStart = function ( url ) {
  24469. itemsTotal ++;
  24470. if ( isLoading === false ) {
  24471. if ( scope.onStart !== undefined ) {
  24472. scope.onStart( url, itemsLoaded, itemsTotal );
  24473. }
  24474. }
  24475. isLoading = true;
  24476. };
  24477. this.itemEnd = function ( url ) {
  24478. itemsLoaded ++;
  24479. if ( scope.onProgress !== undefined ) {
  24480. scope.onProgress( url, itemsLoaded, itemsTotal );
  24481. }
  24482. if ( itemsLoaded === itemsTotal ) {
  24483. isLoading = false;
  24484. if ( scope.onLoad !== undefined ) {
  24485. scope.onLoad();
  24486. }
  24487. }
  24488. };
  24489. this.itemError = function ( url ) {
  24490. if ( scope.onError !== undefined ) {
  24491. scope.onError( url );
  24492. }
  24493. };
  24494. this.resolveURL = function ( url ) {
  24495. if ( urlModifier ) {
  24496. return urlModifier( url );
  24497. }
  24498. return url;
  24499. };
  24500. this.setURLModifier = function ( transform ) {
  24501. urlModifier = transform;
  24502. return this;
  24503. };
  24504. this.addHandler = function ( regex, loader ) {
  24505. handlers.push( regex, loader );
  24506. return this;
  24507. };
  24508. this.removeHandler = function ( regex ) {
  24509. const index = handlers.indexOf( regex );
  24510. if ( index !== -1 ) {
  24511. handlers.splice( index, 2 );
  24512. }
  24513. return this;
  24514. };
  24515. this.getHandler = function ( file ) {
  24516. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24517. const regex = handlers[ i ];
  24518. const loader = handlers[ i + 1 ];
  24519. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24520. if ( regex.test( file ) ) {
  24521. return loader;
  24522. }
  24523. }
  24524. return null;
  24525. };
  24526. }
  24527. }
  24528. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24529. /**
  24530. * Abstract base class for loaders.
  24531. *
  24532. * @abstract
  24533. */
  24534. class Loader {
  24535. /**
  24536. * Constructs a new loader.
  24537. *
  24538. * @param {LoadingManager} [manager] - The loading manager.
  24539. */
  24540. constructor( manager ) {
  24541. /**
  24542. * The loading manager.
  24543. *
  24544. * @type {LoadingManager}
  24545. * @default DefaultLoadingManager
  24546. */
  24547. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24548. /**
  24549. * The crossOrigin string to implement CORS for loading the url from a
  24550. * different domain that allows CORS.
  24551. *
  24552. * @type {string}
  24553. * @default 'anonymous'
  24554. */
  24555. this.crossOrigin = 'anonymous';
  24556. /**
  24557. * Whether the XMLHttpRequest uses credentials.
  24558. *
  24559. * @type {boolean}
  24560. * @default false
  24561. */
  24562. this.withCredentials = false;
  24563. /**
  24564. * The base path from which the asset will be loaded.
  24565. *
  24566. * @type {string}
  24567. */
  24568. this.path = '';
  24569. /**
  24570. * The base path from which additional resources like textures will be loaded.
  24571. *
  24572. * @type {string}
  24573. */
  24574. this.resourcePath = '';
  24575. /**
  24576. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  24577. * used in HTTP request.
  24578. *
  24579. * @type {Object}
  24580. */
  24581. this.requestHeader = {};
  24582. }
  24583. /**
  24584. * This method needs to be implemented by all concrete loaders. It holds the
  24585. * logic for loading assets from the backend.
  24586. *
  24587. * @param {string} url - The path/URL of the file to be loaded.
  24588. * @param {Function} onLoad - Executed when the loading process has been finished.
  24589. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  24590. * @param {onErrorCallback} onError - Executed when errors occur.
  24591. */
  24592. load( /* url, onLoad, onProgress, onError */ ) {}
  24593. /**
  24594. * A async version of {@link Loader#load}.
  24595. *
  24596. * @param {string} url - The path/URL of the file to be loaded.
  24597. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  24598. * @return {Promise} A Promise that resolves when the asset has been loaded.
  24599. */
  24600. loadAsync( url, onProgress ) {
  24601. const scope = this;
  24602. return new Promise( function ( resolve, reject ) {
  24603. scope.load( url, resolve, onProgress, reject );
  24604. } );
  24605. }
  24606. /**
  24607. * This method needs to be implemented by all concrete loaders. It holds the
  24608. * logic for parsing the asset into three.js entities.
  24609. *
  24610. * @param {any} data - The data to parse.
  24611. */
  24612. parse( /* data */ ) {}
  24613. /**
  24614. * Sets the `crossOrigin` String to implement CORS for loading the URL
  24615. * from a different domain that allows CORS.
  24616. *
  24617. * @param {string} crossOrigin - The `crossOrigin` value.
  24618. * @return {Loader} A reference to this instance.
  24619. */
  24620. setCrossOrigin( crossOrigin ) {
  24621. this.crossOrigin = crossOrigin;
  24622. return this;
  24623. }
  24624. /**
  24625. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  24626. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  24627. *
  24628. * Note: This setting has no effect if you are loading files locally or from the same domain.
  24629. *
  24630. * @param {boolean} value - The `withCredentials` value.
  24631. * @return {Loader} A reference to this instance.
  24632. */
  24633. setWithCredentials( value ) {
  24634. this.withCredentials = value;
  24635. return this;
  24636. }
  24637. /**
  24638. * Sets the base path for the asset.
  24639. *
  24640. * @param {string} path - The base path.
  24641. * @return {Loader} A reference to this instance.
  24642. */
  24643. setPath( path ) {
  24644. this.path = path;
  24645. return this;
  24646. }
  24647. /**
  24648. * Sets the base path for dependent resources like textures.
  24649. *
  24650. * @param {string} resourcePath - The resource path.
  24651. * @return {Loader} A reference to this instance.
  24652. */
  24653. setResourcePath( resourcePath ) {
  24654. this.resourcePath = resourcePath;
  24655. return this;
  24656. }
  24657. /**
  24658. * Sets the given request header.
  24659. *
  24660. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  24661. * for configuring the HTTP request.
  24662. * @return {Loader} A reference to this instance.
  24663. */
  24664. setRequestHeader( requestHeader ) {
  24665. this.requestHeader = requestHeader;
  24666. return this;
  24667. }
  24668. }
  24669. /**
  24670. * Callback for onProgress in loaders.
  24671. *
  24672. *
  24673. * @callback onProgressCallback
  24674. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  24675. */
  24676. /**
  24677. * Callback for onError in loaders.
  24678. *
  24679. *
  24680. * @callback onErrorCallback
  24681. * @param {Error} error - The error which occurred during the loading process.
  24682. */
  24683. /**
  24684. * The default material name that is used by loaders
  24685. * when creating materials for loaded 3D objects.
  24686. *
  24687. * Note: Not all loaders might honor this setting.
  24688. *
  24689. * @static
  24690. * @type {string}
  24691. * @default '__DEFAULT'
  24692. */
  24693. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  24694. const loading = {};
  24695. class HttpError extends Error {
  24696. constructor( message, response ) {
  24697. super( message );
  24698. this.response = response;
  24699. }
  24700. }
  24701. class FileLoader extends Loader {
  24702. constructor( manager ) {
  24703. super( manager );
  24704. }
  24705. load( url, onLoad, onProgress, onError ) {
  24706. if ( url === undefined ) url = '';
  24707. if ( this.path !== undefined ) url = this.path + url;
  24708. url = this.manager.resolveURL( url );
  24709. const cached = Cache.get( url );
  24710. if ( cached !== undefined ) {
  24711. this.manager.itemStart( url );
  24712. setTimeout( () => {
  24713. if ( onLoad ) onLoad( cached );
  24714. this.manager.itemEnd( url );
  24715. }, 0 );
  24716. return cached;
  24717. }
  24718. // Check if request is duplicate
  24719. if ( loading[ url ] !== undefined ) {
  24720. loading[ url ].push( {
  24721. onLoad: onLoad,
  24722. onProgress: onProgress,
  24723. onError: onError
  24724. } );
  24725. return;
  24726. }
  24727. // Initialise array for duplicate requests
  24728. loading[ url ] = [];
  24729. loading[ url ].push( {
  24730. onLoad: onLoad,
  24731. onProgress: onProgress,
  24732. onError: onError,
  24733. } );
  24734. // create request
  24735. const req = new Request( url, {
  24736. headers: new Headers( this.requestHeader ),
  24737. credentials: this.withCredentials ? 'include' : 'same-origin',
  24738. // An abort controller could be added within a future PR
  24739. } );
  24740. // record states ( avoid data race )
  24741. const mimeType = this.mimeType;
  24742. const responseType = this.responseType;
  24743. // start the fetch
  24744. fetch( req )
  24745. .then( response => {
  24746. if ( response.status === 200 || response.status === 0 ) {
  24747. // Some browsers return HTTP Status 0 when using non-http protocol
  24748. // e.g. 'file://' or 'data://'. Handle as success.
  24749. if ( response.status === 0 ) {
  24750. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24751. }
  24752. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24753. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24754. return response;
  24755. }
  24756. const callbacks = loading[ url ];
  24757. const reader = response.body.getReader();
  24758. // Nginx needs X-File-Size check
  24759. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24760. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  24761. const total = contentLength ? parseInt( contentLength ) : 0;
  24762. const lengthComputable = total !== 0;
  24763. let loaded = 0;
  24764. // periodically read data into the new stream tracking while download progress
  24765. const stream = new ReadableStream( {
  24766. start( controller ) {
  24767. readData();
  24768. function readData() {
  24769. reader.read().then( ( { done, value } ) => {
  24770. if ( done ) {
  24771. controller.close();
  24772. } else {
  24773. loaded += value.byteLength;
  24774. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24775. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24776. const callback = callbacks[ i ];
  24777. if ( callback.onProgress ) callback.onProgress( event );
  24778. }
  24779. controller.enqueue( value );
  24780. readData();
  24781. }
  24782. }, ( e ) => {
  24783. controller.error( e );
  24784. } );
  24785. }
  24786. }
  24787. } );
  24788. return new Response( stream );
  24789. } else {
  24790. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24791. }
  24792. } )
  24793. .then( response => {
  24794. switch ( responseType ) {
  24795. case 'arraybuffer':
  24796. return response.arrayBuffer();
  24797. case 'blob':
  24798. return response.blob();
  24799. case 'document':
  24800. return response.text()
  24801. .then( text => {
  24802. const parser = new DOMParser();
  24803. return parser.parseFromString( text, mimeType );
  24804. } );
  24805. case 'json':
  24806. return response.json();
  24807. default:
  24808. if ( mimeType === undefined ) {
  24809. return response.text();
  24810. } else {
  24811. // sniff encoding
  24812. const re = /charset="?([^;"\s]*)"?/i;
  24813. const exec = re.exec( mimeType );
  24814. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24815. const decoder = new TextDecoder( label );
  24816. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24817. }
  24818. }
  24819. } )
  24820. .then( data => {
  24821. // Add to cache only on HTTP success, so that we do not cache
  24822. // error response bodies as proper responses to requests.
  24823. Cache.add( url, data );
  24824. const callbacks = loading[ url ];
  24825. delete loading[ url ];
  24826. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24827. const callback = callbacks[ i ];
  24828. if ( callback.onLoad ) callback.onLoad( data );
  24829. }
  24830. } )
  24831. .catch( err => {
  24832. // Abort errors and other errors are handled the same
  24833. const callbacks = loading[ url ];
  24834. if ( callbacks === undefined ) {
  24835. // When onLoad was called and url was deleted in `loading`
  24836. this.manager.itemError( url );
  24837. throw err;
  24838. }
  24839. delete loading[ url ];
  24840. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24841. const callback = callbacks[ i ];
  24842. if ( callback.onError ) callback.onError( err );
  24843. }
  24844. this.manager.itemError( url );
  24845. } )
  24846. .finally( () => {
  24847. this.manager.itemEnd( url );
  24848. } );
  24849. this.manager.itemStart( url );
  24850. }
  24851. setResponseType( value ) {
  24852. this.responseType = value;
  24853. return this;
  24854. }
  24855. setMimeType( value ) {
  24856. this.mimeType = value;
  24857. return this;
  24858. }
  24859. }
  24860. class AnimationLoader extends Loader {
  24861. constructor( manager ) {
  24862. super( manager );
  24863. }
  24864. load( url, onLoad, onProgress, onError ) {
  24865. const scope = this;
  24866. const loader = new FileLoader( this.manager );
  24867. loader.setPath( this.path );
  24868. loader.setRequestHeader( this.requestHeader );
  24869. loader.setWithCredentials( this.withCredentials );
  24870. loader.load( url, function ( text ) {
  24871. try {
  24872. onLoad( scope.parse( JSON.parse( text ) ) );
  24873. } catch ( e ) {
  24874. if ( onError ) {
  24875. onError( e );
  24876. } else {
  24877. console.error( e );
  24878. }
  24879. scope.manager.itemError( url );
  24880. }
  24881. }, onProgress, onError );
  24882. }
  24883. parse( json ) {
  24884. const animations = [];
  24885. for ( let i = 0; i < json.length; i ++ ) {
  24886. const clip = AnimationClip.parse( json[ i ] );
  24887. animations.push( clip );
  24888. }
  24889. return animations;
  24890. }
  24891. }
  24892. /**
  24893. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24894. *
  24895. * Sub classes have to implement the parse() method which will be used in load().
  24896. */
  24897. class CompressedTextureLoader extends Loader {
  24898. constructor( manager ) {
  24899. super( manager );
  24900. }
  24901. load( url, onLoad, onProgress, onError ) {
  24902. const scope = this;
  24903. const images = [];
  24904. const texture = new CompressedTexture();
  24905. const loader = new FileLoader( this.manager );
  24906. loader.setPath( this.path );
  24907. loader.setResponseType( 'arraybuffer' );
  24908. loader.setRequestHeader( this.requestHeader );
  24909. loader.setWithCredentials( scope.withCredentials );
  24910. let loaded = 0;
  24911. function loadTexture( i ) {
  24912. loader.load( url[ i ], function ( buffer ) {
  24913. const texDatas = scope.parse( buffer, true );
  24914. images[ i ] = {
  24915. width: texDatas.width,
  24916. height: texDatas.height,
  24917. format: texDatas.format,
  24918. mipmaps: texDatas.mipmaps
  24919. };
  24920. loaded += 1;
  24921. if ( loaded === 6 ) {
  24922. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24923. texture.image = images;
  24924. texture.format = texDatas.format;
  24925. texture.needsUpdate = true;
  24926. if ( onLoad ) onLoad( texture );
  24927. }
  24928. }, onProgress, onError );
  24929. }
  24930. if ( Array.isArray( url ) ) {
  24931. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24932. loadTexture( i );
  24933. }
  24934. } else {
  24935. // compressed cubemap texture stored in a single DDS file
  24936. loader.load( url, function ( buffer ) {
  24937. const texDatas = scope.parse( buffer, true );
  24938. if ( texDatas.isCubemap ) {
  24939. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24940. for ( let f = 0; f < faces; f ++ ) {
  24941. images[ f ] = { mipmaps: [] };
  24942. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24943. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24944. images[ f ].format = texDatas.format;
  24945. images[ f ].width = texDatas.width;
  24946. images[ f ].height = texDatas.height;
  24947. }
  24948. }
  24949. texture.image = images;
  24950. } else {
  24951. texture.image.width = texDatas.width;
  24952. texture.image.height = texDatas.height;
  24953. texture.mipmaps = texDatas.mipmaps;
  24954. }
  24955. if ( texDatas.mipmapCount === 1 ) {
  24956. texture.minFilter = LinearFilter;
  24957. }
  24958. texture.format = texDatas.format;
  24959. texture.needsUpdate = true;
  24960. if ( onLoad ) onLoad( texture );
  24961. }, onProgress, onError );
  24962. }
  24963. return texture;
  24964. }
  24965. }
  24966. class ImageLoader extends Loader {
  24967. constructor( manager ) {
  24968. super( manager );
  24969. }
  24970. load( url, onLoad, onProgress, onError ) {
  24971. if ( this.path !== undefined ) url = this.path + url;
  24972. url = this.manager.resolveURL( url );
  24973. const scope = this;
  24974. const cached = Cache.get( url );
  24975. if ( cached !== undefined ) {
  24976. scope.manager.itemStart( url );
  24977. setTimeout( function () {
  24978. if ( onLoad ) onLoad( cached );
  24979. scope.manager.itemEnd( url );
  24980. }, 0 );
  24981. return cached;
  24982. }
  24983. const image = createElementNS( 'img' );
  24984. function onImageLoad() {
  24985. removeEventListeners();
  24986. Cache.add( url, this );
  24987. if ( onLoad ) onLoad( this );
  24988. scope.manager.itemEnd( url );
  24989. }
  24990. function onImageError( event ) {
  24991. removeEventListeners();
  24992. if ( onError ) onError( event );
  24993. scope.manager.itemError( url );
  24994. scope.manager.itemEnd( url );
  24995. }
  24996. function removeEventListeners() {
  24997. image.removeEventListener( 'load', onImageLoad, false );
  24998. image.removeEventListener( 'error', onImageError, false );
  24999. }
  25000. image.addEventListener( 'load', onImageLoad, false );
  25001. image.addEventListener( 'error', onImageError, false );
  25002. if ( url.slice( 0, 5 ) !== 'data:' ) {
  25003. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25004. }
  25005. scope.manager.itemStart( url );
  25006. image.src = url;
  25007. return image;
  25008. }
  25009. }
  25010. class CubeTextureLoader extends Loader {
  25011. constructor( manager ) {
  25012. super( manager );
  25013. }
  25014. load( urls, onLoad, onProgress, onError ) {
  25015. const texture = new CubeTexture();
  25016. texture.colorSpace = SRGBColorSpace;
  25017. const loader = new ImageLoader( this.manager );
  25018. loader.setCrossOrigin( this.crossOrigin );
  25019. loader.setPath( this.path );
  25020. let loaded = 0;
  25021. function loadTexture( i ) {
  25022. loader.load( urls[ i ], function ( image ) {
  25023. texture.images[ i ] = image;
  25024. loaded ++;
  25025. if ( loaded === 6 ) {
  25026. texture.needsUpdate = true;
  25027. if ( onLoad ) onLoad( texture );
  25028. }
  25029. }, undefined, onError );
  25030. }
  25031. for ( let i = 0; i < urls.length; ++ i ) {
  25032. loadTexture( i );
  25033. }
  25034. return texture;
  25035. }
  25036. }
  25037. /**
  25038. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25039. *
  25040. * Sub classes have to implement the parse() method which will be used in load().
  25041. */
  25042. class DataTextureLoader extends Loader {
  25043. constructor( manager ) {
  25044. super( manager );
  25045. }
  25046. load( url, onLoad, onProgress, onError ) {
  25047. const scope = this;
  25048. const texture = new DataTexture();
  25049. const loader = new FileLoader( this.manager );
  25050. loader.setResponseType( 'arraybuffer' );
  25051. loader.setRequestHeader( this.requestHeader );
  25052. loader.setPath( this.path );
  25053. loader.setWithCredentials( scope.withCredentials );
  25054. loader.load( url, function ( buffer ) {
  25055. let texData;
  25056. try {
  25057. texData = scope.parse( buffer );
  25058. } catch ( error ) {
  25059. if ( onError !== undefined ) {
  25060. onError( error );
  25061. } else {
  25062. console.error( error );
  25063. return;
  25064. }
  25065. }
  25066. if ( texData.image !== undefined ) {
  25067. texture.image = texData.image;
  25068. } else if ( texData.data !== undefined ) {
  25069. texture.image.width = texData.width;
  25070. texture.image.height = texData.height;
  25071. texture.image.data = texData.data;
  25072. }
  25073. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25074. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25075. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25076. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  25077. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25078. if ( texData.colorSpace !== undefined ) {
  25079. texture.colorSpace = texData.colorSpace;
  25080. }
  25081. if ( texData.flipY !== undefined ) {
  25082. texture.flipY = texData.flipY;
  25083. }
  25084. if ( texData.format !== undefined ) {
  25085. texture.format = texData.format;
  25086. }
  25087. if ( texData.type !== undefined ) {
  25088. texture.type = texData.type;
  25089. }
  25090. if ( texData.mipmaps !== undefined ) {
  25091. texture.mipmaps = texData.mipmaps;
  25092. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  25093. }
  25094. if ( texData.mipmapCount === 1 ) {
  25095. texture.minFilter = LinearFilter;
  25096. }
  25097. if ( texData.generateMipmaps !== undefined ) {
  25098. texture.generateMipmaps = texData.generateMipmaps;
  25099. }
  25100. texture.needsUpdate = true;
  25101. if ( onLoad ) onLoad( texture, texData );
  25102. }, onProgress, onError );
  25103. return texture;
  25104. }
  25105. }
  25106. class TextureLoader extends Loader {
  25107. constructor( manager ) {
  25108. super( manager );
  25109. }
  25110. load( url, onLoad, onProgress, onError ) {
  25111. const texture = new Texture();
  25112. const loader = new ImageLoader( this.manager );
  25113. loader.setCrossOrigin( this.crossOrigin );
  25114. loader.setPath( this.path );
  25115. loader.load( url, function ( image ) {
  25116. texture.image = image;
  25117. texture.needsUpdate = true;
  25118. if ( onLoad !== undefined ) {
  25119. onLoad( texture );
  25120. }
  25121. }, onProgress, onError );
  25122. return texture;
  25123. }
  25124. }
  25125. /**
  25126. * Abstract base class for lights - all other light types inherit the
  25127. * properties and methods described here.
  25128. *
  25129. * @abstract
  25130. * @augments Object3D
  25131. */
  25132. class Light extends Object3D {
  25133. /**
  25134. * Constructs a new light.
  25135. *
  25136. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  25137. * @param {number} [intensity=1] - The light's strength/intensity.
  25138. */
  25139. constructor( color, intensity = 1 ) {
  25140. super();
  25141. /**
  25142. * This flag can be used for type testing.
  25143. *
  25144. * @type {boolean}
  25145. * @readonly
  25146. * @default true
  25147. */
  25148. this.isLight = true;
  25149. this.type = 'Light';
  25150. /**
  25151. * The light's color.
  25152. *
  25153. * @type {Color}
  25154. */
  25155. this.color = new Color( color );
  25156. /**
  25157. * The light's intensity.
  25158. *
  25159. * @type {number}
  25160. * @default 1
  25161. */
  25162. this.intensity = intensity;
  25163. }
  25164. /**
  25165. * Frees the GPU-related resources allocated by this instance. Call this
  25166. * method whenever this instance is no longer used in your app.
  25167. */
  25168. dispose() {
  25169. // Empty here in base class; some subclasses override.
  25170. }
  25171. copy( source, recursive ) {
  25172. super.copy( source, recursive );
  25173. this.color.copy( source.color );
  25174. this.intensity = source.intensity;
  25175. return this;
  25176. }
  25177. toJSON( meta ) {
  25178. const data = super.toJSON( meta );
  25179. data.object.color = this.color.getHex();
  25180. data.object.intensity = this.intensity;
  25181. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  25182. if ( this.distance !== undefined ) data.object.distance = this.distance;
  25183. if ( this.angle !== undefined ) data.object.angle = this.angle;
  25184. if ( this.decay !== undefined ) data.object.decay = this.decay;
  25185. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  25186. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  25187. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  25188. return data;
  25189. }
  25190. }
  25191. /**
  25192. * A light source positioned directly above the scene, with color fading from
  25193. * the sky color to the ground color.
  25194. *
  25195. * This light cannot be used to cast shadows.
  25196. *
  25197. * ```js
  25198. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  25199. * scene.add( light );
  25200. * ```
  25201. *
  25202. * @augments Light
  25203. */
  25204. class HemisphereLight extends Light {
  25205. /**
  25206. * Constructs a new hemisphere light.
  25207. *
  25208. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  25209. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  25210. * @param {number} [intensity=1] - The light's strength/intensity.
  25211. */
  25212. constructor( skyColor, groundColor, intensity ) {
  25213. super( skyColor, intensity );
  25214. /**
  25215. * This flag can be used for type testing.
  25216. *
  25217. * @type {boolean}
  25218. * @readonly
  25219. * @default true
  25220. */
  25221. this.isHemisphereLight = true;
  25222. this.type = 'HemisphereLight';
  25223. this.position.copy( Object3D.DEFAULT_UP );
  25224. this.updateMatrix();
  25225. /**
  25226. * The light's ground color.
  25227. *
  25228. * @type {Color}
  25229. */
  25230. this.groundColor = new Color( groundColor );
  25231. }
  25232. copy( source, recursive ) {
  25233. super.copy( source, recursive );
  25234. this.groundColor.copy( source.groundColor );
  25235. return this;
  25236. }
  25237. }
  25238. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  25239. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  25240. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  25241. /**
  25242. * Abstract base class for light shadow classes. These classes
  25243. * represent the shadow configuration for different ligth types.
  25244. *
  25245. * @abstract
  25246. */
  25247. class LightShadow {
  25248. /**
  25249. * Constructs a new light shadow.
  25250. *
  25251. * @param {Camera} camera - The light's view of the world.
  25252. */
  25253. constructor( camera ) {
  25254. /**
  25255. * The light's view of the world.
  25256. *
  25257. * @type {Camera}
  25258. */
  25259. this.camera = camera;
  25260. /**
  25261. * The intensity of the shadow. The default is `1`.
  25262. * Valid values are in the range `[0, 1]`.
  25263. *
  25264. * @type {number}
  25265. * @default 1
  25266. */
  25267. this.intensity = 1;
  25268. /**
  25269. * Shadow map bias, how much to add or subtract from the normalized depth
  25270. * when deciding whether a surface is in shadow.
  25271. *
  25272. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  25273. * may help reduce artifacts in shadows.
  25274. *
  25275. * @type {number}
  25276. * @default 0
  25277. */
  25278. this.bias = 0;
  25279. /**
  25280. * Defines how much the position used to query the shadow map is offset along
  25281. * the object normal. The default is `0`. Increasing this value can be used to
  25282. * reduce shadow acne especially in large scenes where light shines onto
  25283. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  25284. *
  25285. * @type {number}
  25286. * @default 0
  25287. */
  25288. this.normalBias = 0;
  25289. /**
  25290. * Setting this to values greater than 1 will blur the edges of the shadow.
  25291. * High values will cause unwanted banding effects in the shadows - a greater
  25292. * map size will allow for a higher value to be used here before these effects
  25293. * become visible.
  25294. *
  25295. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  25296. * and it is recommended to increase softness by decreasing the shadow map size instead.
  25297. *
  25298. * The property has no effect when the shadow map type is `BasicShadowMap`.
  25299. *
  25300. * @type {number}
  25301. * @default 1
  25302. */
  25303. this.radius = 1;
  25304. /**
  25305. * The amount of samples to use when blurring a VSM shadow map.
  25306. *
  25307. * @type {number}
  25308. * @default 8
  25309. */
  25310. this.blurSamples = 8;
  25311. /**
  25312. * Defines the width and height of the shadow map. Higher values give better quality
  25313. * shadows at the cost of computation time. Values must be powers of two.
  25314. *
  25315. * @type {Vector2}
  25316. * @default (512,512)
  25317. */
  25318. this.mapSize = new Vector2( 512, 512 );
  25319. /**
  25320. * The depth map generated using the internal camera; a location beyond a
  25321. * pixel's depth is in shadow. Computed internally during rendering.
  25322. *
  25323. * @type {?RenderTarget}
  25324. * @default null
  25325. */
  25326. this.map = null;
  25327. /**
  25328. * The distribution map generated using the internal camera; an occlusion is
  25329. * calculated based on the distribution of depths. Computed internally during
  25330. * rendering.
  25331. *
  25332. * @type {?RenderTarget}
  25333. * @default null
  25334. */
  25335. this.mapPass = null;
  25336. /**
  25337. * Model to shadow camera space, to compute location and depth in shadow map.
  25338. * This is computed internally during rendering.
  25339. *
  25340. * @type {Matrix4}
  25341. */
  25342. this.matrix = new Matrix4();
  25343. /**
  25344. * Enables automatic updates of the light's shadow. If you do not require dynamic
  25345. * lighting / shadows, you may set this to `false`.
  25346. *
  25347. * @type {boolean}
  25348. * @default true
  25349. */
  25350. this.autoUpdate = true;
  25351. /**
  25352. * When set to `true`, shadow maps will be updated in the next `render` call.
  25353. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  25354. * set this property to `true` and then make a render call to update the light's shadow.
  25355. *
  25356. * @type {boolean}
  25357. * @default false
  25358. */
  25359. this.needsUpdate = false;
  25360. this._frustum = new Frustum();
  25361. this._frameExtents = new Vector2( 1, 1 );
  25362. this._viewportCount = 1;
  25363. this._viewports = [
  25364. new Vector4( 0, 0, 1, 1 )
  25365. ];
  25366. }
  25367. /**
  25368. * Used internally by the renderer to get the number of viewports that need
  25369. * to be rendered for this shadow.
  25370. *
  25371. * @return {number} The viewport count.
  25372. */
  25373. getViewportCount() {
  25374. return this._viewportCount;
  25375. }
  25376. /**
  25377. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  25378. *
  25379. * @return {Frustum} The shadow camera frustum.
  25380. */
  25381. getFrustum() {
  25382. return this._frustum;
  25383. }
  25384. /**
  25385. * Update the matrices for the camera and shadow, used internally by the renderer.
  25386. *
  25387. * @param {Light} light - The light for which the shadow is being rendered.
  25388. */
  25389. updateMatrices( light ) {
  25390. const shadowCamera = this.camera;
  25391. const shadowMatrix = this.matrix;
  25392. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  25393. shadowCamera.position.copy( _lightPositionWorld$1 );
  25394. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  25395. shadowCamera.lookAt( _lookTarget$1 );
  25396. shadowCamera.updateMatrixWorld();
  25397. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  25398. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  25399. shadowMatrix.set(
  25400. 0.5, 0.0, 0.0, 0.5,
  25401. 0.0, 0.5, 0.0, 0.5,
  25402. 0.0, 0.0, 0.5, 0.5,
  25403. 0.0, 0.0, 0.0, 1.0
  25404. );
  25405. shadowMatrix.multiply( _projScreenMatrix$1 );
  25406. }
  25407. /**
  25408. * Returns a viewport definition for the given viewport index.
  25409. *
  25410. * @param {number} viewportIndex - The viewport index.
  25411. * @return {Vector4} The viewport.
  25412. */
  25413. getViewport( viewportIndex ) {
  25414. return this._viewports[ viewportIndex ];
  25415. }
  25416. /**
  25417. * Returns the frame extends.
  25418. *
  25419. * @return {Vector2} The frame extends.
  25420. */
  25421. getFrameExtents() {
  25422. return this._frameExtents;
  25423. }
  25424. /**
  25425. * Frees the GPU-related resources allocated by this instance. Call this
  25426. * method whenever this instance is no longer used in your app.
  25427. */
  25428. dispose() {
  25429. if ( this.map ) {
  25430. this.map.dispose();
  25431. }
  25432. if ( this.mapPass ) {
  25433. this.mapPass.dispose();
  25434. }
  25435. }
  25436. /**
  25437. * Copies the values of the given light shadow instance to this instance.
  25438. *
  25439. * @param {LightShadow} source - The light shadow to copy.
  25440. * @return {LightShadow} A reference to this light shadow instance.
  25441. */
  25442. copy( source ) {
  25443. this.camera = source.camera.clone();
  25444. this.intensity = source.intensity;
  25445. this.bias = source.bias;
  25446. this.radius = source.radius;
  25447. this.mapSize.copy( source.mapSize );
  25448. return this;
  25449. }
  25450. /**
  25451. * Returns a new light shadow instance with copied values from this instance.
  25452. *
  25453. * @return {LightShadow} A clone of this instance.
  25454. */
  25455. clone() {
  25456. return new this.constructor().copy( this );
  25457. }
  25458. /**
  25459. * Serializes the light shadow into JSON.
  25460. *
  25461. * @return {Object} A JSON object representing the serialized light shadow.
  25462. * @see {@link ObjectLoader#parse}
  25463. */
  25464. toJSON() {
  25465. const object = {};
  25466. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  25467. if ( this.bias !== 0 ) object.bias = this.bias;
  25468. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  25469. if ( this.radius !== 1 ) object.radius = this.radius;
  25470. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  25471. object.camera = this.camera.toJSON( false ).object;
  25472. delete object.camera.matrix;
  25473. return object;
  25474. }
  25475. }
  25476. /**
  25477. * Represents the shadow configuration of directional lights.
  25478. *
  25479. * @augments LightShadow
  25480. */
  25481. class SpotLightShadow extends LightShadow {
  25482. /**
  25483. * Constructs a new spot light shadow.
  25484. */
  25485. constructor() {
  25486. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  25487. /**
  25488. * This flag can be used for type testing.
  25489. *
  25490. * @type {boolean}
  25491. * @readonly
  25492. * @default true
  25493. */
  25494. this.isSpotLightShadow = true;
  25495. /**
  25496. * Used to focus the shadow camera. The camera's field of view is set as a
  25497. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  25498. *
  25499. * @type {number}
  25500. * @default 1
  25501. */
  25502. this.focus = 1;
  25503. }
  25504. updateMatrices( light ) {
  25505. const camera = this.camera;
  25506. const fov = RAD2DEG * 2 * light.angle * this.focus;
  25507. const aspect = this.mapSize.width / this.mapSize.height;
  25508. const far = light.distance || camera.far;
  25509. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  25510. camera.fov = fov;
  25511. camera.aspect = aspect;
  25512. camera.far = far;
  25513. camera.updateProjectionMatrix();
  25514. }
  25515. super.updateMatrices( light );
  25516. }
  25517. copy( source ) {
  25518. super.copy( source );
  25519. this.focus = source.focus;
  25520. return this;
  25521. }
  25522. }
  25523. /**
  25524. * This light gets emitted from a single point in one direction, along a cone
  25525. * that increases in size the further from the light it gets.
  25526. *
  25527. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  25528. *
  25529. * ```js
  25530. * // white spotlight shining from the side, modulated by a texture
  25531. * const spotLight = new THREE.SpotLight( 0xffffff );
  25532. * spotLight.position.set( 100, 1000, 100 );
  25533. * spotLight.map = new THREE.TextureLoader().load( url );
  25534. *
  25535. * spotLight.castShadow = true;
  25536. * spotLight.shadow.mapSize.width = 1024;
  25537. * spotLight.shadow.mapSize.height = 1024;
  25538. * spotLight.shadow.camera.near = 500;
  25539. * spotLight.shadow.camera.far = 4000;
  25540. * spotLight.shadow.camera.fov = 30;s
  25541. * ```
  25542. *
  25543. * @augments Light
  25544. */
  25545. class SpotLight extends Light {
  25546. /**
  25547. * Constructs a new spot light.
  25548. *
  25549. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  25550. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  25551. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  25552. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  25553. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  25554. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  25555. */
  25556. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  25557. super( color, intensity );
  25558. /**
  25559. * This flag can be used for type testing.
  25560. *
  25561. * @type {boolean}
  25562. * @readonly
  25563. * @default true
  25564. */
  25565. this.isSpotLight = true;
  25566. this.type = 'SpotLight';
  25567. this.position.copy( Object3D.DEFAULT_UP );
  25568. this.updateMatrix();
  25569. /**
  25570. * The spot light points from its position to the
  25571. * target's position.
  25572. *
  25573. * For the target's position to be changed to anything other
  25574. * than the default, it must be added to the scene.
  25575. *
  25576. * It is also possible to set the target to be another 3D object
  25577. * in the scene. The light will now track the target object.
  25578. *
  25579. * @type {Object3D}
  25580. */
  25581. this.target = new Object3D();
  25582. /**
  25583. * Maximum range of the light. `0` means no limit.
  25584. *
  25585. * @type {number}
  25586. * @default 0
  25587. */
  25588. this.distance = distance;
  25589. /**
  25590. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  25591. *
  25592. * @type {number}
  25593. * @default Math.PI/3
  25594. */
  25595. this.angle = angle;
  25596. /**
  25597. * Percent of the spotlight cone that is attenuated due to penumbra.
  25598. * Value range is `[0,1]`.
  25599. *
  25600. * @type {number}
  25601. * @default 0
  25602. */
  25603. this.penumbra = penumbra;
  25604. /**
  25605. * The amount the light dims along the distance of the light. In context of
  25606. * physically-correct rendering the default value should not be changed.
  25607. *
  25608. * @type {number}
  25609. * @default 2
  25610. */
  25611. this.decay = decay;
  25612. /**
  25613. * A texture used to modulate the color of the light. The spot light
  25614. * color is mixed with the RGB value of this texture, with a ratio
  25615. * corresponding to its alpha value. The cookie-like masking effect is
  25616. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  25617. *
  25618. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  25619. *
  25620. * @type {?Texture}
  25621. * @default null
  25622. */
  25623. this.map = null;
  25624. /**
  25625. * This property holds the light's shadow configuration.
  25626. *
  25627. * @type {SpotLightShadow}
  25628. */
  25629. this.shadow = new SpotLightShadow();
  25630. }
  25631. /**
  25632. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  25633. * Changing the power will also change the light's intensity.
  25634. *
  25635. * @type {number}
  25636. */
  25637. get power() {
  25638. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25639. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  25640. return this.intensity * Math.PI;
  25641. }
  25642. set power( power ) {
  25643. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25644. this.intensity = power / Math.PI;
  25645. }
  25646. dispose() {
  25647. this.shadow.dispose();
  25648. }
  25649. copy( source, recursive ) {
  25650. super.copy( source, recursive );
  25651. this.distance = source.distance;
  25652. this.angle = source.angle;
  25653. this.penumbra = source.penumbra;
  25654. this.decay = source.decay;
  25655. this.target = source.target.clone();
  25656. this.shadow = source.shadow.clone();
  25657. return this;
  25658. }
  25659. }
  25660. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  25661. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  25662. const _lookTarget = /*@__PURE__*/ new Vector3();
  25663. /**
  25664. * Represents the shadow configuration of point lights.
  25665. *
  25666. * @augments LightShadow
  25667. */
  25668. class PointLightShadow extends LightShadow {
  25669. /**
  25670. * Constructs a new point light shadow.
  25671. */
  25672. constructor() {
  25673. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25674. /**
  25675. * This flag can be used for type testing.
  25676. *
  25677. * @type {boolean}
  25678. * @readonly
  25679. * @default true
  25680. */
  25681. this.isPointLightShadow = true;
  25682. this._frameExtents = new Vector2( 4, 2 );
  25683. this._viewportCount = 6;
  25684. this._viewports = [
  25685. // These viewports map a cube-map onto a 2D texture with the
  25686. // following orientation:
  25687. //
  25688. // xzXZ
  25689. // y Y
  25690. //
  25691. // X - Positive x direction
  25692. // x - Negative x direction
  25693. // Y - Positive y direction
  25694. // y - Negative y direction
  25695. // Z - Positive z direction
  25696. // z - Negative z direction
  25697. // positive X
  25698. new Vector4( 2, 1, 1, 1 ),
  25699. // negative X
  25700. new Vector4( 0, 1, 1, 1 ),
  25701. // positive Z
  25702. new Vector4( 3, 1, 1, 1 ),
  25703. // negative Z
  25704. new Vector4( 1, 1, 1, 1 ),
  25705. // positive Y
  25706. new Vector4( 3, 0, 1, 1 ),
  25707. // negative Y
  25708. new Vector4( 1, 0, 1, 1 )
  25709. ];
  25710. this._cubeDirections = [
  25711. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  25712. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  25713. ];
  25714. this._cubeUps = [
  25715. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25716. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  25717. ];
  25718. }
  25719. /**
  25720. * Update the matrices for the camera and shadow, used internally by the renderer.
  25721. *
  25722. * @param {Light} light - The light for which the shadow is being rendered.
  25723. * @param {number} [viewportIndex=0] - The viewport index.
  25724. */
  25725. updateMatrices( light, viewportIndex = 0 ) {
  25726. const camera = this.camera;
  25727. const shadowMatrix = this.matrix;
  25728. const far = light.distance || camera.far;
  25729. if ( far !== camera.far ) {
  25730. camera.far = far;
  25731. camera.updateProjectionMatrix();
  25732. }
  25733. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25734. camera.position.copy( _lightPositionWorld );
  25735. _lookTarget.copy( camera.position );
  25736. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25737. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25738. camera.lookAt( _lookTarget );
  25739. camera.updateMatrixWorld();
  25740. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25741. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25742. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25743. }
  25744. }
  25745. /**
  25746. * A light that gets emitted from a single point in all directions. A common
  25747. * use case for this is to replicate the light emitted from a bare
  25748. * lightbulb.
  25749. *
  25750. * This light can cast shadows - see the {@link PointLightShadow} for details.
  25751. *
  25752. * ```js
  25753. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  25754. * light.position.set( 50, 50, 50 );
  25755. * scene.add( light );
  25756. * ```
  25757. *
  25758. * @augments Light
  25759. */
  25760. class PointLight extends Light {
  25761. /**
  25762. * Constructs a new point light.
  25763. *
  25764. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  25765. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  25766. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  25767. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  25768. */
  25769. constructor( color, intensity, distance = 0, decay = 2 ) {
  25770. super( color, intensity );
  25771. /**
  25772. * This flag can be used for type testing.
  25773. *
  25774. * @type {boolean}
  25775. * @readonly
  25776. * @default true
  25777. */
  25778. this.isPointLight = true;
  25779. this.type = 'PointLight';
  25780. /**
  25781. * When distance is zero, light will attenuate according to inverse-square
  25782. * law to infinite distance. When distance is non-zero, light will attenuate
  25783. * according to inverse-square law until near the distance cutoff, where it
  25784. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  25785. * physically correct.
  25786. *
  25787. * @type {number}
  25788. * @default 0
  25789. */
  25790. this.distance = distance;
  25791. /**
  25792. * The amount the light dims along the distance of the light. In context of
  25793. * physically-correct rendering the default value should not be changed.
  25794. *
  25795. * @type {number}
  25796. * @default 2
  25797. */
  25798. this.decay = decay;
  25799. /**
  25800. * This property holds the light's shadow configuration.
  25801. *
  25802. * @type {PointLightShadow}
  25803. */
  25804. this.shadow = new PointLightShadow();
  25805. }
  25806. /**
  25807. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  25808. * Changing the power will also change the light's intensity.
  25809. *
  25810. * @type {number}
  25811. */
  25812. get power() {
  25813. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25814. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25815. return this.intensity * 4 * Math.PI;
  25816. }
  25817. set power( power ) {
  25818. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25819. this.intensity = power / ( 4 * Math.PI );
  25820. }
  25821. dispose() {
  25822. this.shadow.dispose();
  25823. }
  25824. copy( source, recursive ) {
  25825. super.copy( source, recursive );
  25826. this.distance = source.distance;
  25827. this.decay = source.decay;
  25828. this.shadow = source.shadow.clone();
  25829. return this;
  25830. }
  25831. }
  25832. /**
  25833. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  25834. *
  25835. * In this projection mode, an object's size in the rendered image stays
  25836. * constant regardless of its distance from the camera. This can be useful
  25837. * for rendering 2D scenes and UI elements, amongst other things.
  25838. *
  25839. * ```js
  25840. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  25841. * scene.add( camera );
  25842. * ```
  25843. *
  25844. * @augments Camera
  25845. */
  25846. class OrthographicCamera extends Camera {
  25847. /**
  25848. * Constructs a new orthographic camera.
  25849. *
  25850. * @param {number} [left=-1] - The left plane of the camera's frustum.
  25851. * @param {number} [right=1] - The right plane of the camera's frustum.
  25852. * @param {number} [top=1] - The top plane of the camera's frustum.
  25853. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  25854. * @param {number} [near=0.1] - The camera's near plane.
  25855. * @param {number} [far=2000] - The camera's far plane.
  25856. */
  25857. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  25858. super();
  25859. /**
  25860. * This flag can be used for type testing.
  25861. *
  25862. * @type {boolean}
  25863. * @readonly
  25864. * @default true
  25865. */
  25866. this.isOrthographicCamera = true;
  25867. this.type = 'OrthographicCamera';
  25868. /**
  25869. * The zoom factor of the camera.
  25870. *
  25871. * @type {number}
  25872. * @default 1
  25873. */
  25874. this.zoom = 1;
  25875. /**
  25876. * Represents the frustum window specification. This property should not be edited
  25877. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  25878. *
  25879. * @type {?Object}
  25880. * @default null
  25881. */
  25882. this.view = null;
  25883. /**
  25884. * The left plane of the camera's frustum.
  25885. *
  25886. * @type {number}
  25887. * @default -1
  25888. */
  25889. this.left = left;
  25890. /**
  25891. * The right plane of the camera's frustum.
  25892. *
  25893. * @type {number}
  25894. * @default 1
  25895. */
  25896. this.right = right;
  25897. /**
  25898. * The top plane of the camera's frustum.
  25899. *
  25900. * @type {number}
  25901. * @default 1
  25902. */
  25903. this.top = top;
  25904. /**
  25905. * The bottom plane of the camera's frustum.
  25906. *
  25907. * @type {number}
  25908. * @default -1
  25909. */
  25910. this.bottom = bottom;
  25911. /**
  25912. * The camera's near plane. The valid range is greater than `0`
  25913. * and less than the current value of {@link OrthographicCamera#far}.
  25914. *
  25915. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  25916. * valid value for an orthographic camera's near plane.
  25917. *
  25918. * @type {number}
  25919. * @default 0.1
  25920. */
  25921. this.near = near;
  25922. /**
  25923. * The camera's far plane. Must be greater than the
  25924. * current value of {@link OrthographicCamera#near}.
  25925. *
  25926. * @type {number}
  25927. * @default 2000
  25928. */
  25929. this.far = far;
  25930. this.updateProjectionMatrix();
  25931. }
  25932. copy( source, recursive ) {
  25933. super.copy( source, recursive );
  25934. this.left = source.left;
  25935. this.right = source.right;
  25936. this.top = source.top;
  25937. this.bottom = source.bottom;
  25938. this.near = source.near;
  25939. this.far = source.far;
  25940. this.zoom = source.zoom;
  25941. this.view = source.view === null ? null : Object.assign( {}, source.view );
  25942. return this;
  25943. }
  25944. /**
  25945. * Sets an offset in a larger frustum. This is useful for multi-window or
  25946. * multi-monitor/multi-machine setups.
  25947. *
  25948. * @param {number} fullWidth - The full width of multiview setup.
  25949. * @param {number} fullHeight - The full height of multiview setup.
  25950. * @param {number} x - The horizontal offset of the subcamera.
  25951. * @param {number} y - The vertical offset of the subcamera.
  25952. * @param {number} width - The width of subcamera.
  25953. * @param {number} height - The height of subcamera.
  25954. * @see {@link PerspectiveCamera#setViewOffset}
  25955. */
  25956. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  25957. if ( this.view === null ) {
  25958. this.view = {
  25959. enabled: true,
  25960. fullWidth: 1,
  25961. fullHeight: 1,
  25962. offsetX: 0,
  25963. offsetY: 0,
  25964. width: 1,
  25965. height: 1
  25966. };
  25967. }
  25968. this.view.enabled = true;
  25969. this.view.fullWidth = fullWidth;
  25970. this.view.fullHeight = fullHeight;
  25971. this.view.offsetX = x;
  25972. this.view.offsetY = y;
  25973. this.view.width = width;
  25974. this.view.height = height;
  25975. this.updateProjectionMatrix();
  25976. }
  25977. /**
  25978. * Removes the view offset from the projection matrix.
  25979. */
  25980. clearViewOffset() {
  25981. if ( this.view !== null ) {
  25982. this.view.enabled = false;
  25983. }
  25984. this.updateProjectionMatrix();
  25985. }
  25986. /**
  25987. * Updates the camera's projection matrix. Must be called after any change of
  25988. * camera properties.
  25989. */
  25990. updateProjectionMatrix() {
  25991. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  25992. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  25993. const cx = ( this.right + this.left ) / 2;
  25994. const cy = ( this.top + this.bottom ) / 2;
  25995. let left = cx - dx;
  25996. let right = cx + dx;
  25997. let top = cy + dy;
  25998. let bottom = cy - dy;
  25999. if ( this.view !== null && this.view.enabled ) {
  26000. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  26001. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  26002. left += scaleW * this.view.offsetX;
  26003. right = left + scaleW * this.view.width;
  26004. top -= scaleH * this.view.offsetY;
  26005. bottom = top - scaleH * this.view.height;
  26006. }
  26007. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  26008. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  26009. }
  26010. toJSON( meta ) {
  26011. const data = super.toJSON( meta );
  26012. data.object.zoom = this.zoom;
  26013. data.object.left = this.left;
  26014. data.object.right = this.right;
  26015. data.object.top = this.top;
  26016. data.object.bottom = this.bottom;
  26017. data.object.near = this.near;
  26018. data.object.far = this.far;
  26019. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  26020. return data;
  26021. }
  26022. }
  26023. /**
  26024. * Represents the shadow configuration of directional lights.
  26025. *
  26026. * @augments LightShadow
  26027. */
  26028. class DirectionalLightShadow extends LightShadow {
  26029. /**
  26030. * Constructs a new directional light shadow.
  26031. */
  26032. constructor() {
  26033. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  26034. /**
  26035. * This flag can be used for type testing.
  26036. *
  26037. * @type {boolean}
  26038. * @readonly
  26039. * @default true
  26040. */
  26041. this.isDirectionalLightShadow = true;
  26042. }
  26043. }
  26044. /**
  26045. * A light that gets emitted in a specific direction. This light will behave
  26046. * as though it is infinitely far away and the rays produced from it are all
  26047. * parallel. The common use case for this is to simulate daylight; the sun is
  26048. * far enough away that its position can be considered to be infinite, and
  26049. * all light rays coming from it are parallel.
  26050. *
  26051. * A common point of confusion for directional lights is that setting the
  26052. * rotation has no effect. This is because three.js's DirectionalLight is the
  26053. * equivalent to what is often called a 'Target Direct Light' in other
  26054. * applications.
  26055. *
  26056. * This means that its direction is calculated as pointing from the light's
  26057. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  26058. * (as opposed to a 'Free Direct Light' that just has a rotation
  26059. * component).
  26060. *
  26061. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  26062. *
  26063. * ```js
  26064. * // White directional light at half intensity shining from the top.
  26065. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  26066. * scene.add( directionalLight );
  26067. * ```
  26068. *
  26069. * @augments Light
  26070. */
  26071. class DirectionalLight extends Light {
  26072. /**
  26073. * Constructs a new directional light.
  26074. *
  26075. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  26076. * @param {number} [intensity=1] - The light's strength/intensity.
  26077. */
  26078. constructor( color, intensity ) {
  26079. super( color, intensity );
  26080. /**
  26081. * This flag can be used for type testing.
  26082. *
  26083. * @type {boolean}
  26084. * @readonly
  26085. * @default true
  26086. */
  26087. this.isDirectionalLight = true;
  26088. this.type = 'DirectionalLight';
  26089. this.position.copy( Object3D.DEFAULT_UP );
  26090. this.updateMatrix();
  26091. /**
  26092. * The directional light points from its position to the
  26093. * target's position.
  26094. *
  26095. * For the target's position to be changed to anything other
  26096. * than the default, it must be added to the scene.
  26097. *
  26098. * It is also possible to set the target to be another 3D object
  26099. * in the scene. The light will now track the target object.
  26100. *
  26101. * @type {Object3D}
  26102. */
  26103. this.target = new Object3D();
  26104. /**
  26105. * This property holds the light's shadow configuration.
  26106. *
  26107. * @type {DirectionalLightShadow}
  26108. */
  26109. this.shadow = new DirectionalLightShadow();
  26110. }
  26111. dispose() {
  26112. this.shadow.dispose();
  26113. }
  26114. copy( source ) {
  26115. super.copy( source );
  26116. this.target = source.target.clone();
  26117. this.shadow = source.shadow.clone();
  26118. return this;
  26119. }
  26120. }
  26121. /**
  26122. * This light globally illuminates all objects in the scene equally.
  26123. *
  26124. * It cannot be used to cast shadows as it does not have a direction.
  26125. *
  26126. * ```js
  26127. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  26128. * scene.add( light );
  26129. * ```
  26130. *
  26131. * @augments Light
  26132. */
  26133. class AmbientLight extends Light {
  26134. /**
  26135. * Constructs a new ambient light.
  26136. *
  26137. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  26138. * @param {number} [intensity=1] - The light's strength/intensity.
  26139. */
  26140. constructor( color, intensity ) {
  26141. super( color, intensity );
  26142. /**
  26143. * This flag can be used for type testing.
  26144. *
  26145. * @type {boolean}
  26146. * @readonly
  26147. * @default true
  26148. */
  26149. this.isAmbientLight = true;
  26150. this.type = 'AmbientLight';
  26151. }
  26152. }
  26153. /**
  26154. * This class emits light uniformly across the face a rectangular plane.
  26155. * This light type can be used to simulate light sources such as bright
  26156. * windows or strip lighting.
  26157. *
  26158. * Important Notes:
  26159. *
  26160. * - There is no shadow support.
  26161. * - Only PBR materials are supported.
  26162. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  26163. * into your app and init the uniforms/textures.
  26164. *
  26165. * ```js
  26166. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  26167. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  26168. *
  26169. * const intensity = 1; const width = 10; const height = 10;
  26170. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  26171. * rectLight.position.set( 5, 5, 0 );
  26172. * rectLight.lookAt( 0, 0, 0 );
  26173. * scene.add( rectLight )
  26174. * ```
  26175. *
  26176. * @augments Light
  26177. */
  26178. class RectAreaLight extends Light {
  26179. /**
  26180. * Constructs a new area light.
  26181. *
  26182. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  26183. * @param {number} [intensity=1] - The light's strength/intensity.
  26184. * @param {number} [width=10] - The width of the light.
  26185. * @param {number} [height=10] - The height of the light.
  26186. */
  26187. constructor( color, intensity, width = 10, height = 10 ) {
  26188. super( color, intensity );
  26189. /**
  26190. * This flag can be used for type testing.
  26191. *
  26192. * @type {boolean}
  26193. * @readonly
  26194. * @default true
  26195. */
  26196. this.isRectAreaLight = true;
  26197. this.type = 'RectAreaLight';
  26198. /**
  26199. * The width of the light.
  26200. *
  26201. * @type {number}
  26202. * @default 10
  26203. */
  26204. this.width = width;
  26205. /**
  26206. * The height of the light.
  26207. *
  26208. * @type {number}
  26209. * @default 10
  26210. */
  26211. this.height = height;
  26212. }
  26213. /**
  26214. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  26215. * Changing the power will also change the light's intensity.
  26216. *
  26217. * @type {number}
  26218. */
  26219. get power() {
  26220. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26221. return this.intensity * this.width * this.height * Math.PI;
  26222. }
  26223. set power( power ) {
  26224. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26225. this.intensity = power / ( this.width * this.height * Math.PI );
  26226. }
  26227. copy( source ) {
  26228. super.copy( source );
  26229. this.width = source.width;
  26230. this.height = source.height;
  26231. return this;
  26232. }
  26233. toJSON( meta ) {
  26234. const data = super.toJSON( meta );
  26235. data.object.width = this.width;
  26236. data.object.height = this.height;
  26237. return data;
  26238. }
  26239. }
  26240. /**
  26241. * Represents a third-order spherical harmonics (SH). Light probes use this class
  26242. * to encode lighting information.
  26243. *
  26244. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  26245. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  26246. */
  26247. class SphericalHarmonics3 {
  26248. /**
  26249. * Constructs a new spherical harmonics.
  26250. */
  26251. constructor() {
  26252. /**
  26253. * This flag can be used for type testing.
  26254. *
  26255. * @type {boolean}
  26256. * @readonly
  26257. * @default true
  26258. */
  26259. this.isSphericalHarmonics3 = true;
  26260. /**
  26261. * An array holding the (9) SH coefficients.
  26262. *
  26263. * @type {Array<Vector3>}
  26264. */
  26265. this.coefficients = [];
  26266. for ( let i = 0; i < 9; i ++ ) {
  26267. this.coefficients.push( new Vector3() );
  26268. }
  26269. }
  26270. /**
  26271. * Sets the given SH coefficients to this instance by copying
  26272. * the values.
  26273. *
  26274. * @param {Array<Vector3>} coefficients - The SH coefficients.
  26275. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26276. */
  26277. set( coefficients ) {
  26278. for ( let i = 0; i < 9; i ++ ) {
  26279. this.coefficients[ i ].copy( coefficients[ i ] );
  26280. }
  26281. return this;
  26282. }
  26283. /**
  26284. * Sets all SH coefficients to `0`.
  26285. *
  26286. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26287. */
  26288. zero() {
  26289. for ( let i = 0; i < 9; i ++ ) {
  26290. this.coefficients[ i ].set( 0, 0, 0 );
  26291. }
  26292. return this;
  26293. }
  26294. /**
  26295. * Returns the radiance in the direction of the given normal.
  26296. *
  26297. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  26298. * @param {Vector3} target - The target vector that is used to store the method's result.
  26299. * @return {Vector3} The radiance.
  26300. */
  26301. getAt( normal, target ) {
  26302. // normal is assumed to be unit length
  26303. const x = normal.x, y = normal.y, z = normal.z;
  26304. const coeff = this.coefficients;
  26305. // band 0
  26306. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26307. // band 1
  26308. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26309. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26310. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26311. // band 2
  26312. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26313. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26314. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26315. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26316. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26317. return target;
  26318. }
  26319. /**
  26320. * Returns the irradiance (radiance convolved with cosine lobe) in the
  26321. * direction of the given normal.
  26322. *
  26323. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  26324. * @param {Vector3} target - The target vector that is used to store the method's result.
  26325. * @return {Vector3} The irradiance.
  26326. */
  26327. getIrradianceAt( normal, target ) {
  26328. // normal is assumed to be unit length
  26329. const x = normal.x, y = normal.y, z = normal.z;
  26330. const coeff = this.coefficients;
  26331. // band 0
  26332. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26333. // band 1
  26334. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26335. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26336. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26337. // band 2
  26338. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26339. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26340. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26341. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26342. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26343. return target;
  26344. }
  26345. /**
  26346. * Adds the given SH to this instance.
  26347. *
  26348. * @param {SphericalHarmonics3} sh - The SH to add.
  26349. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26350. */
  26351. add( sh ) {
  26352. for ( let i = 0; i < 9; i ++ ) {
  26353. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26354. }
  26355. return this;
  26356. }
  26357. /**
  26358. * A convenience method for performing {@link SphericalHarmonics3#add} and
  26359. * {@link SphericalHarmonics3#scale} at once.
  26360. *
  26361. * @param {SphericalHarmonics3} sh - The SH to add.
  26362. * @param {number} s - The scale factor.
  26363. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26364. */
  26365. addScaledSH( sh, s ) {
  26366. for ( let i = 0; i < 9; i ++ ) {
  26367. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26368. }
  26369. return this;
  26370. }
  26371. /**
  26372. * Scales this SH by the given scale factor.
  26373. *
  26374. * @param {number} s - The scale factor.
  26375. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26376. */
  26377. scale( s ) {
  26378. for ( let i = 0; i < 9; i ++ ) {
  26379. this.coefficients[ i ].multiplyScalar( s );
  26380. }
  26381. return this;
  26382. }
  26383. /**
  26384. * Linear interpolates between the given SH and this instance by the given
  26385. * alpha factor.
  26386. *
  26387. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  26388. * @param {number} alpha - The alpha factor.
  26389. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26390. */
  26391. lerp( sh, alpha ) {
  26392. for ( let i = 0; i < 9; i ++ ) {
  26393. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26394. }
  26395. return this;
  26396. }
  26397. /**
  26398. * Returns `true` if this spherical harmonics is equal with the given one.
  26399. *
  26400. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  26401. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  26402. */
  26403. equals( sh ) {
  26404. for ( let i = 0; i < 9; i ++ ) {
  26405. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26406. return false;
  26407. }
  26408. }
  26409. return true;
  26410. }
  26411. /**
  26412. * Copies the values of the given spherical harmonics to this instance.
  26413. *
  26414. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  26415. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  26416. */
  26417. copy( sh ) {
  26418. return this.set( sh.coefficients );
  26419. }
  26420. /**
  26421. * Returns a new spherical harmonics with copied values from this instance.
  26422. *
  26423. * @return {SphericalHarmonics3} A clone of this instance.
  26424. */
  26425. clone() {
  26426. return new this.constructor().copy( this );
  26427. }
  26428. /**
  26429. * Sets the SH coefficients of this instance from the given array.
  26430. *
  26431. * @param {Array<number>} array - An array holding the SH coefficients.
  26432. * @param {number} [offset=0] - The array offset where to start copying.
  26433. * @return {SphericalHarmonics3} A clone of this instance.
  26434. */
  26435. fromArray( array, offset = 0 ) {
  26436. const coefficients = this.coefficients;
  26437. for ( let i = 0; i < 9; i ++ ) {
  26438. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26439. }
  26440. return this;
  26441. }
  26442. /**
  26443. * Returns an array with the SH coefficients, or copies them into the provided
  26444. * array. The coefficients are represented as numbers.
  26445. *
  26446. * @param {Array<number>} [array=[]] - The target array.
  26447. * @param {number} [offset=0] - The array offset where to start copying.
  26448. * @return {Array<number>} An array with flat SH coefficients.
  26449. */
  26450. toArray( array = [], offset = 0 ) {
  26451. const coefficients = this.coefficients;
  26452. for ( let i = 0; i < 9; i ++ ) {
  26453. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26454. }
  26455. return array;
  26456. }
  26457. /**
  26458. * Computes the SH basis for the given normal vector.
  26459. *
  26460. * @param {Vector3} normal - The normal.
  26461. * @param {Array<number>} shBasis - The target array holding the SH basis.
  26462. */
  26463. static getBasisAt( normal, shBasis ) {
  26464. // normal is assumed to be unit length
  26465. const x = normal.x, y = normal.y, z = normal.z;
  26466. // band 0
  26467. shBasis[ 0 ] = 0.282095;
  26468. // band 1
  26469. shBasis[ 1 ] = 0.488603 * y;
  26470. shBasis[ 2 ] = 0.488603 * z;
  26471. shBasis[ 3 ] = 0.488603 * x;
  26472. // band 2
  26473. shBasis[ 4 ] = 1.092548 * x * y;
  26474. shBasis[ 5 ] = 1.092548 * y * z;
  26475. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26476. shBasis[ 7 ] = 1.092548 * x * z;
  26477. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26478. }
  26479. }
  26480. /**
  26481. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  26482. * classical light sources (e.g. directional, point or spot lights), light
  26483. * probes do not emit light. Instead they store information about light
  26484. * passing through 3D space. During rendering, the light that hits a 3D
  26485. * object is approximated by using the data from the light probe.
  26486. *
  26487. * Light probes are usually created from (radiance) environment maps. The
  26488. * class {@link LightProbeGenerator} can be used to create light probes from
  26489. * cube textures or render targets. However, light estimation data could also
  26490. * be provided in other forms e.g. by WebXR. This enables the rendering of
  26491. * augmented reality content that reacts to real world lighting.
  26492. *
  26493. * The current probe implementation in three.js supports so-called diffuse
  26494. * light probes. This type of light probe is functionally equivalent to an
  26495. * irradiance environment map.
  26496. *
  26497. * @augments Light
  26498. */
  26499. class LightProbe extends Light {
  26500. /**
  26501. * Constructs a new light probe.
  26502. *
  26503. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  26504. * @param {number} [intensity=1] - The light's strength/intensity.
  26505. */
  26506. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26507. super( undefined, intensity );
  26508. /**
  26509. * This flag can be used for type testing.
  26510. *
  26511. * @type {boolean}
  26512. * @readonly
  26513. * @default true
  26514. */
  26515. this.isLightProbe = true;
  26516. /**
  26517. * A light probe uses spherical harmonics to encode lighting information.
  26518. *
  26519. * @type {SphericalHarmonics3}
  26520. */
  26521. this.sh = sh;
  26522. }
  26523. copy( source ) {
  26524. super.copy( source );
  26525. this.sh.copy( source.sh );
  26526. return this;
  26527. }
  26528. /**
  26529. * Deserializes the light prove from the given JSON.
  26530. *
  26531. * @param {Object} json - The JSON holding the serialized light probe.
  26532. * @return {LightProbe} A reference to this light probe.
  26533. */
  26534. fromJSON( json ) {
  26535. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26536. this.sh.fromArray( json.sh );
  26537. return this;
  26538. }
  26539. toJSON( meta ) {
  26540. const data = super.toJSON( meta );
  26541. data.object.sh = this.sh.toArray();
  26542. return data;
  26543. }
  26544. }
  26545. class MaterialLoader extends Loader {
  26546. constructor( manager ) {
  26547. super( manager );
  26548. this.textures = {};
  26549. }
  26550. load( url, onLoad, onProgress, onError ) {
  26551. const scope = this;
  26552. const loader = new FileLoader( scope.manager );
  26553. loader.setPath( scope.path );
  26554. loader.setRequestHeader( scope.requestHeader );
  26555. loader.setWithCredentials( scope.withCredentials );
  26556. loader.load( url, function ( text ) {
  26557. try {
  26558. onLoad( scope.parse( JSON.parse( text ) ) );
  26559. } catch ( e ) {
  26560. if ( onError ) {
  26561. onError( e );
  26562. } else {
  26563. console.error( e );
  26564. }
  26565. scope.manager.itemError( url );
  26566. }
  26567. }, onProgress, onError );
  26568. }
  26569. parse( json ) {
  26570. const textures = this.textures;
  26571. function getTexture( name ) {
  26572. if ( textures[ name ] === undefined ) {
  26573. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26574. }
  26575. return textures[ name ];
  26576. }
  26577. const material = this.createMaterialFromType( json.type );
  26578. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26579. if ( json.name !== undefined ) material.name = json.name;
  26580. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26581. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26582. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26583. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26584. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26585. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26586. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26587. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26588. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26589. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26590. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26591. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26592. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26593. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  26594. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  26595. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  26596. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  26597. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  26598. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  26599. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  26600. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  26601. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  26602. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  26603. if ( json.fog !== undefined ) material.fog = json.fog;
  26604. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26605. if ( json.blending !== undefined ) material.blending = json.blending;
  26606. if ( json.combine !== undefined ) material.combine = json.combine;
  26607. if ( json.side !== undefined ) material.side = json.side;
  26608. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  26609. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26610. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26611. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26612. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  26613. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  26614. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26615. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26616. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26617. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  26618. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  26619. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  26620. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  26621. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  26622. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  26623. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  26624. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  26625. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  26626. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  26627. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  26628. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  26629. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  26630. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  26631. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  26632. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  26633. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26634. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26635. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26636. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26637. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26638. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  26639. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26640. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26641. if ( json.scale !== undefined ) material.scale = json.scale;
  26642. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26643. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26644. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26645. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26646. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  26647. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  26648. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  26649. if ( json.visible !== undefined ) material.visible = json.visible;
  26650. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  26651. if ( json.userData !== undefined ) material.userData = json.userData;
  26652. if ( json.vertexColors !== undefined ) {
  26653. if ( typeof json.vertexColors === 'number' ) {
  26654. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  26655. } else {
  26656. material.vertexColors = json.vertexColors;
  26657. }
  26658. }
  26659. // Shader Material
  26660. if ( json.uniforms !== undefined ) {
  26661. for ( const name in json.uniforms ) {
  26662. const uniform = json.uniforms[ name ];
  26663. material.uniforms[ name ] = {};
  26664. switch ( uniform.type ) {
  26665. case 't':
  26666. material.uniforms[ name ].value = getTexture( uniform.value );
  26667. break;
  26668. case 'c':
  26669. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26670. break;
  26671. case 'v2':
  26672. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26673. break;
  26674. case 'v3':
  26675. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26676. break;
  26677. case 'v4':
  26678. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26679. break;
  26680. case 'm3':
  26681. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  26682. break;
  26683. case 'm4':
  26684. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26685. break;
  26686. default:
  26687. material.uniforms[ name ].value = uniform.value;
  26688. }
  26689. }
  26690. }
  26691. if ( json.defines !== undefined ) material.defines = json.defines;
  26692. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26693. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26694. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  26695. if ( json.extensions !== undefined ) {
  26696. for ( const key in json.extensions ) {
  26697. material.extensions[ key ] = json.extensions[ key ];
  26698. }
  26699. }
  26700. if ( json.lights !== undefined ) material.lights = json.lights;
  26701. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  26702. // for PointsMaterial
  26703. if ( json.size !== undefined ) material.size = json.size;
  26704. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26705. // maps
  26706. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26707. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  26708. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  26709. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26710. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26711. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26712. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26713. if ( json.normalScale !== undefined ) {
  26714. let normalScale = json.normalScale;
  26715. if ( Array.isArray( normalScale ) === false ) {
  26716. // Blender exporter used to export a scalar. See #7459
  26717. normalScale = [ normalScale, normalScale ];
  26718. }
  26719. material.normalScale = new Vector2().fromArray( normalScale );
  26720. }
  26721. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  26722. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  26723. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  26724. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  26725. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  26726. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  26727. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  26728. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  26729. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  26730. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  26731. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  26732. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  26733. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  26734. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  26735. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  26736. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  26737. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  26738. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  26739. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  26740. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  26741. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  26742. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  26743. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  26744. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  26745. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  26746. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  26747. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  26748. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  26749. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  26750. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  26751. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  26752. return material;
  26753. }
  26754. setTextures( value ) {
  26755. this.textures = value;
  26756. return this;
  26757. }
  26758. createMaterialFromType( type ) {
  26759. return MaterialLoader.createMaterialFromType( type );
  26760. }
  26761. static createMaterialFromType( type ) {
  26762. const materialLib = {
  26763. ShadowMaterial,
  26764. SpriteMaterial,
  26765. RawShaderMaterial,
  26766. ShaderMaterial,
  26767. PointsMaterial,
  26768. MeshPhysicalMaterial,
  26769. MeshStandardMaterial,
  26770. MeshPhongMaterial,
  26771. MeshToonMaterial,
  26772. MeshNormalMaterial,
  26773. MeshLambertMaterial,
  26774. MeshDepthMaterial,
  26775. MeshDistanceMaterial,
  26776. MeshBasicMaterial,
  26777. MeshMatcapMaterial,
  26778. LineDashedMaterial,
  26779. LineBasicMaterial,
  26780. Material
  26781. };
  26782. return new materialLib[ type ]();
  26783. }
  26784. }
  26785. class LoaderUtils {
  26786. static decodeText( array ) { // @deprecated, r165
  26787. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  26788. if ( typeof TextDecoder !== 'undefined' ) {
  26789. return new TextDecoder().decode( array );
  26790. }
  26791. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26792. // throws a "maximum call stack size exceeded" error for large arrays.
  26793. let s = '';
  26794. for ( let i = 0, il = array.length; i < il; i ++ ) {
  26795. // Implicitly assumes little-endian.
  26796. s += String.fromCharCode( array[ i ] );
  26797. }
  26798. try {
  26799. // merges multi-byte utf-8 characters.
  26800. return decodeURIComponent( escape( s ) );
  26801. } catch ( e ) { // see #16358
  26802. return s;
  26803. }
  26804. }
  26805. static extractUrlBase( url ) {
  26806. const index = url.lastIndexOf( '/' );
  26807. if ( index === -1 ) return './';
  26808. return url.slice( 0, index + 1 );
  26809. }
  26810. static resolveURL( url, path ) {
  26811. // Invalid URL
  26812. if ( typeof url !== 'string' || url === '' ) return '';
  26813. // Host Relative URL
  26814. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  26815. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  26816. }
  26817. // Absolute URL http://,https://,//
  26818. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  26819. // Data URI
  26820. if ( /^data:.*,.*$/i.test( url ) ) return url;
  26821. // Blob URL
  26822. if ( /^blob:.*$/i.test( url ) ) return url;
  26823. // Relative URL
  26824. return path + url;
  26825. }
  26826. }
  26827. class InstancedBufferGeometry extends BufferGeometry {
  26828. constructor() {
  26829. super();
  26830. this.isInstancedBufferGeometry = true;
  26831. this.type = 'InstancedBufferGeometry';
  26832. this.instanceCount = Infinity;
  26833. }
  26834. copy( source ) {
  26835. super.copy( source );
  26836. this.instanceCount = source.instanceCount;
  26837. return this;
  26838. }
  26839. toJSON() {
  26840. const data = super.toJSON();
  26841. data.instanceCount = this.instanceCount;
  26842. data.isInstancedBufferGeometry = true;
  26843. return data;
  26844. }
  26845. }
  26846. class BufferGeometryLoader extends Loader {
  26847. constructor( manager ) {
  26848. super( manager );
  26849. }
  26850. load( url, onLoad, onProgress, onError ) {
  26851. const scope = this;
  26852. const loader = new FileLoader( scope.manager );
  26853. loader.setPath( scope.path );
  26854. loader.setRequestHeader( scope.requestHeader );
  26855. loader.setWithCredentials( scope.withCredentials );
  26856. loader.load( url, function ( text ) {
  26857. try {
  26858. onLoad( scope.parse( JSON.parse( text ) ) );
  26859. } catch ( e ) {
  26860. if ( onError ) {
  26861. onError( e );
  26862. } else {
  26863. console.error( e );
  26864. }
  26865. scope.manager.itemError( url );
  26866. }
  26867. }, onProgress, onError );
  26868. }
  26869. parse( json ) {
  26870. const interleavedBufferMap = {};
  26871. const arrayBufferMap = {};
  26872. function getInterleavedBuffer( json, uuid ) {
  26873. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  26874. const interleavedBuffers = json.interleavedBuffers;
  26875. const interleavedBuffer = interleavedBuffers[ uuid ];
  26876. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  26877. const array = getTypedArray( interleavedBuffer.type, buffer );
  26878. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  26879. ib.uuid = interleavedBuffer.uuid;
  26880. interleavedBufferMap[ uuid ] = ib;
  26881. return ib;
  26882. }
  26883. function getArrayBuffer( json, uuid ) {
  26884. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  26885. const arrayBuffers = json.arrayBuffers;
  26886. const arrayBuffer = arrayBuffers[ uuid ];
  26887. const ab = new Uint32Array( arrayBuffer ).buffer;
  26888. arrayBufferMap[ uuid ] = ab;
  26889. return ab;
  26890. }
  26891. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  26892. const index = json.data.index;
  26893. if ( index !== undefined ) {
  26894. const typedArray = getTypedArray( index.type, index.array );
  26895. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  26896. }
  26897. const attributes = json.data.attributes;
  26898. for ( const key in attributes ) {
  26899. const attribute = attributes[ key ];
  26900. let bufferAttribute;
  26901. if ( attribute.isInterleavedBufferAttribute ) {
  26902. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26903. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26904. } else {
  26905. const typedArray = getTypedArray( attribute.type, attribute.array );
  26906. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  26907. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  26908. }
  26909. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26910. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  26911. geometry.setAttribute( key, bufferAttribute );
  26912. }
  26913. const morphAttributes = json.data.morphAttributes;
  26914. if ( morphAttributes ) {
  26915. for ( const key in morphAttributes ) {
  26916. const attributeArray = morphAttributes[ key ];
  26917. const array = [];
  26918. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  26919. const attribute = attributeArray[ i ];
  26920. let bufferAttribute;
  26921. if ( attribute.isInterleavedBufferAttribute ) {
  26922. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26923. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26924. } else {
  26925. const typedArray = getTypedArray( attribute.type, attribute.array );
  26926. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  26927. }
  26928. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26929. array.push( bufferAttribute );
  26930. }
  26931. geometry.morphAttributes[ key ] = array;
  26932. }
  26933. }
  26934. const morphTargetsRelative = json.data.morphTargetsRelative;
  26935. if ( morphTargetsRelative ) {
  26936. geometry.morphTargetsRelative = true;
  26937. }
  26938. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  26939. if ( groups !== undefined ) {
  26940. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  26941. const group = groups[ i ];
  26942. geometry.addGroup( group.start, group.count, group.materialIndex );
  26943. }
  26944. }
  26945. const boundingSphere = json.data.boundingSphere;
  26946. if ( boundingSphere !== undefined ) {
  26947. const center = new Vector3();
  26948. if ( boundingSphere.center !== undefined ) {
  26949. center.fromArray( boundingSphere.center );
  26950. }
  26951. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26952. }
  26953. if ( json.name ) geometry.name = json.name;
  26954. if ( json.userData ) geometry.userData = json.userData;
  26955. return geometry;
  26956. }
  26957. }
  26958. class ObjectLoader extends Loader {
  26959. constructor( manager ) {
  26960. super( manager );
  26961. }
  26962. load( url, onLoad, onProgress, onError ) {
  26963. const scope = this;
  26964. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26965. this.resourcePath = this.resourcePath || path;
  26966. const loader = new FileLoader( this.manager );
  26967. loader.setPath( this.path );
  26968. loader.setRequestHeader( this.requestHeader );
  26969. loader.setWithCredentials( this.withCredentials );
  26970. loader.load( url, function ( text ) {
  26971. let json = null;
  26972. try {
  26973. json = JSON.parse( text );
  26974. } catch ( error ) {
  26975. if ( onError !== undefined ) onError( error );
  26976. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26977. return;
  26978. }
  26979. const metadata = json.metadata;
  26980. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26981. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26982. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26983. return;
  26984. }
  26985. scope.parse( json, onLoad );
  26986. }, onProgress, onError );
  26987. }
  26988. async loadAsync( url, onProgress ) {
  26989. const scope = this;
  26990. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26991. this.resourcePath = this.resourcePath || path;
  26992. const loader = new FileLoader( this.manager );
  26993. loader.setPath( this.path );
  26994. loader.setRequestHeader( this.requestHeader );
  26995. loader.setWithCredentials( this.withCredentials );
  26996. const text = await loader.loadAsync( url, onProgress );
  26997. const json = JSON.parse( text );
  26998. const metadata = json.metadata;
  26999. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27000. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27001. }
  27002. return await scope.parseAsync( json );
  27003. }
  27004. parse( json, onLoad ) {
  27005. const animations = this.parseAnimations( json.animations );
  27006. const shapes = this.parseShapes( json.shapes );
  27007. const geometries = this.parseGeometries( json.geometries, shapes );
  27008. const images = this.parseImages( json.images, function () {
  27009. if ( onLoad !== undefined ) onLoad( object );
  27010. } );
  27011. const textures = this.parseTextures( json.textures, images );
  27012. const materials = this.parseMaterials( json.materials, textures );
  27013. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27014. const skeletons = this.parseSkeletons( json.skeletons, object );
  27015. this.bindSkeletons( object, skeletons );
  27016. this.bindLightTargets( object );
  27017. //
  27018. if ( onLoad !== undefined ) {
  27019. let hasImages = false;
  27020. for ( const uuid in images ) {
  27021. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27022. hasImages = true;
  27023. break;
  27024. }
  27025. }
  27026. if ( hasImages === false ) onLoad( object );
  27027. }
  27028. return object;
  27029. }
  27030. async parseAsync( json ) {
  27031. const animations = this.parseAnimations( json.animations );
  27032. const shapes = this.parseShapes( json.shapes );
  27033. const geometries = this.parseGeometries( json.geometries, shapes );
  27034. const images = await this.parseImagesAsync( json.images );
  27035. const textures = this.parseTextures( json.textures, images );
  27036. const materials = this.parseMaterials( json.materials, textures );
  27037. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27038. const skeletons = this.parseSkeletons( json.skeletons, object );
  27039. this.bindSkeletons( object, skeletons );
  27040. this.bindLightTargets( object );
  27041. return object;
  27042. }
  27043. parseShapes( json ) {
  27044. const shapes = {};
  27045. if ( json !== undefined ) {
  27046. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27047. const shape = new Shape().fromJSON( json[ i ] );
  27048. shapes[ shape.uuid ] = shape;
  27049. }
  27050. }
  27051. return shapes;
  27052. }
  27053. parseSkeletons( json, object ) {
  27054. const skeletons = {};
  27055. const bones = {};
  27056. // generate bone lookup table
  27057. object.traverse( function ( child ) {
  27058. if ( child.isBone ) bones[ child.uuid ] = child;
  27059. } );
  27060. // create skeletons
  27061. if ( json !== undefined ) {
  27062. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27063. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27064. skeletons[ skeleton.uuid ] = skeleton;
  27065. }
  27066. }
  27067. return skeletons;
  27068. }
  27069. parseGeometries( json, shapes ) {
  27070. const geometries = {};
  27071. if ( json !== undefined ) {
  27072. const bufferGeometryLoader = new BufferGeometryLoader();
  27073. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27074. let geometry;
  27075. const data = json[ i ];
  27076. switch ( data.type ) {
  27077. case 'BufferGeometry':
  27078. case 'InstancedBufferGeometry':
  27079. geometry = bufferGeometryLoader.parse( data );
  27080. break;
  27081. default:
  27082. if ( data.type in Geometries ) {
  27083. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27084. } else {
  27085. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27086. }
  27087. }
  27088. geometry.uuid = data.uuid;
  27089. if ( data.name !== undefined ) geometry.name = data.name;
  27090. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27091. geometries[ data.uuid ] = geometry;
  27092. }
  27093. }
  27094. return geometries;
  27095. }
  27096. parseMaterials( json, textures ) {
  27097. const cache = {}; // MultiMaterial
  27098. const materials = {};
  27099. if ( json !== undefined ) {
  27100. const loader = new MaterialLoader();
  27101. loader.setTextures( textures );
  27102. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27103. const data = json[ i ];
  27104. if ( cache[ data.uuid ] === undefined ) {
  27105. cache[ data.uuid ] = loader.parse( data );
  27106. }
  27107. materials[ data.uuid ] = cache[ data.uuid ];
  27108. }
  27109. }
  27110. return materials;
  27111. }
  27112. parseAnimations( json ) {
  27113. const animations = {};
  27114. if ( json !== undefined ) {
  27115. for ( let i = 0; i < json.length; i ++ ) {
  27116. const data = json[ i ];
  27117. const clip = AnimationClip.parse( data );
  27118. animations[ clip.uuid ] = clip;
  27119. }
  27120. }
  27121. return animations;
  27122. }
  27123. parseImages( json, onLoad ) {
  27124. const scope = this;
  27125. const images = {};
  27126. let loader;
  27127. function loadImage( url ) {
  27128. scope.manager.itemStart( url );
  27129. return loader.load( url, function () {
  27130. scope.manager.itemEnd( url );
  27131. }, undefined, function () {
  27132. scope.manager.itemError( url );
  27133. scope.manager.itemEnd( url );
  27134. } );
  27135. }
  27136. function deserializeImage( image ) {
  27137. if ( typeof image === 'string' ) {
  27138. const url = image;
  27139. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27140. return loadImage( path );
  27141. } else {
  27142. if ( image.data ) {
  27143. return {
  27144. data: getTypedArray( image.type, image.data ),
  27145. width: image.width,
  27146. height: image.height
  27147. };
  27148. } else {
  27149. return null;
  27150. }
  27151. }
  27152. }
  27153. if ( json !== undefined && json.length > 0 ) {
  27154. const manager = new LoadingManager( onLoad );
  27155. loader = new ImageLoader( manager );
  27156. loader.setCrossOrigin( this.crossOrigin );
  27157. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27158. const image = json[ i ];
  27159. const url = image.url;
  27160. if ( Array.isArray( url ) ) {
  27161. // load array of images e.g CubeTexture
  27162. const imageArray = [];
  27163. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27164. const currentUrl = url[ j ];
  27165. const deserializedImage = deserializeImage( currentUrl );
  27166. if ( deserializedImage !== null ) {
  27167. if ( deserializedImage instanceof HTMLImageElement ) {
  27168. imageArray.push( deserializedImage );
  27169. } else {
  27170. // special case: handle array of data textures for cube textures
  27171. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27172. }
  27173. }
  27174. }
  27175. images[ image.uuid ] = new Source( imageArray );
  27176. } else {
  27177. // load single image
  27178. const deserializedImage = deserializeImage( image.url );
  27179. images[ image.uuid ] = new Source( deserializedImage );
  27180. }
  27181. }
  27182. }
  27183. return images;
  27184. }
  27185. async parseImagesAsync( json ) {
  27186. const scope = this;
  27187. const images = {};
  27188. let loader;
  27189. async function deserializeImage( image ) {
  27190. if ( typeof image === 'string' ) {
  27191. const url = image;
  27192. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27193. return await loader.loadAsync( path );
  27194. } else {
  27195. if ( image.data ) {
  27196. return {
  27197. data: getTypedArray( image.type, image.data ),
  27198. width: image.width,
  27199. height: image.height
  27200. };
  27201. } else {
  27202. return null;
  27203. }
  27204. }
  27205. }
  27206. if ( json !== undefined && json.length > 0 ) {
  27207. loader = new ImageLoader( this.manager );
  27208. loader.setCrossOrigin( this.crossOrigin );
  27209. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27210. const image = json[ i ];
  27211. const url = image.url;
  27212. if ( Array.isArray( url ) ) {
  27213. // load array of images e.g CubeTexture
  27214. const imageArray = [];
  27215. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27216. const currentUrl = url[ j ];
  27217. const deserializedImage = await deserializeImage( currentUrl );
  27218. if ( deserializedImage !== null ) {
  27219. if ( deserializedImage instanceof HTMLImageElement ) {
  27220. imageArray.push( deserializedImage );
  27221. } else {
  27222. // special case: handle array of data textures for cube textures
  27223. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27224. }
  27225. }
  27226. }
  27227. images[ image.uuid ] = new Source( imageArray );
  27228. } else {
  27229. // load single image
  27230. const deserializedImage = await deserializeImage( image.url );
  27231. images[ image.uuid ] = new Source( deserializedImage );
  27232. }
  27233. }
  27234. }
  27235. return images;
  27236. }
  27237. parseTextures( json, images ) {
  27238. function parseConstant( value, type ) {
  27239. if ( typeof value === 'number' ) return value;
  27240. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27241. return type[ value ];
  27242. }
  27243. const textures = {};
  27244. if ( json !== undefined ) {
  27245. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27246. const data = json[ i ];
  27247. if ( data.image === undefined ) {
  27248. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27249. }
  27250. if ( images[ data.image ] === undefined ) {
  27251. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27252. }
  27253. const source = images[ data.image ];
  27254. const image = source.data;
  27255. let texture;
  27256. if ( Array.isArray( image ) ) {
  27257. texture = new CubeTexture();
  27258. if ( image.length === 6 ) texture.needsUpdate = true;
  27259. } else {
  27260. if ( image && image.data ) {
  27261. texture = new DataTexture();
  27262. } else {
  27263. texture = new Texture();
  27264. }
  27265. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27266. }
  27267. texture.source = source;
  27268. texture.uuid = data.uuid;
  27269. if ( data.name !== undefined ) texture.name = data.name;
  27270. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27271. if ( data.channel !== undefined ) texture.channel = data.channel;
  27272. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27273. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27274. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27275. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27276. if ( data.wrap !== undefined ) {
  27277. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27278. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27279. }
  27280. if ( data.format !== undefined ) texture.format = data.format;
  27281. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27282. if ( data.type !== undefined ) texture.type = data.type;
  27283. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27284. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27285. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27286. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27287. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27288. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27289. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27290. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27291. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27292. if ( data.userData !== undefined ) texture.userData = data.userData;
  27293. textures[ data.uuid ] = texture;
  27294. }
  27295. }
  27296. return textures;
  27297. }
  27298. parseObject( data, geometries, materials, textures, animations ) {
  27299. let object;
  27300. function getGeometry( name ) {
  27301. if ( geometries[ name ] === undefined ) {
  27302. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27303. }
  27304. return geometries[ name ];
  27305. }
  27306. function getMaterial( name ) {
  27307. if ( name === undefined ) return undefined;
  27308. if ( Array.isArray( name ) ) {
  27309. const array = [];
  27310. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27311. const uuid = name[ i ];
  27312. if ( materials[ uuid ] === undefined ) {
  27313. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27314. }
  27315. array.push( materials[ uuid ] );
  27316. }
  27317. return array;
  27318. }
  27319. if ( materials[ name ] === undefined ) {
  27320. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27321. }
  27322. return materials[ name ];
  27323. }
  27324. function getTexture( uuid ) {
  27325. if ( textures[ uuid ] === undefined ) {
  27326. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27327. }
  27328. return textures[ uuid ];
  27329. }
  27330. let geometry, material;
  27331. switch ( data.type ) {
  27332. case 'Scene':
  27333. object = new Scene();
  27334. if ( data.background !== undefined ) {
  27335. if ( Number.isInteger( data.background ) ) {
  27336. object.background = new Color( data.background );
  27337. } else {
  27338. object.background = getTexture( data.background );
  27339. }
  27340. }
  27341. if ( data.environment !== undefined ) {
  27342. object.environment = getTexture( data.environment );
  27343. }
  27344. if ( data.fog !== undefined ) {
  27345. if ( data.fog.type === 'Fog' ) {
  27346. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27347. } else if ( data.fog.type === 'FogExp2' ) {
  27348. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27349. }
  27350. if ( data.fog.name !== '' ) {
  27351. object.fog.name = data.fog.name;
  27352. }
  27353. }
  27354. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27355. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27356. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  27357. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  27358. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  27359. break;
  27360. case 'PerspectiveCamera':
  27361. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27362. if ( data.focus !== undefined ) object.focus = data.focus;
  27363. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27364. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27365. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27366. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27367. break;
  27368. case 'OrthographicCamera':
  27369. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27370. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27371. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27372. break;
  27373. case 'AmbientLight':
  27374. object = new AmbientLight( data.color, data.intensity );
  27375. break;
  27376. case 'DirectionalLight':
  27377. object = new DirectionalLight( data.color, data.intensity );
  27378. object.target = data.target || '';
  27379. break;
  27380. case 'PointLight':
  27381. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27382. break;
  27383. case 'RectAreaLight':
  27384. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27385. break;
  27386. case 'SpotLight':
  27387. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27388. object.target = data.target || '';
  27389. break;
  27390. case 'HemisphereLight':
  27391. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27392. break;
  27393. case 'LightProbe':
  27394. object = new LightProbe().fromJSON( data );
  27395. break;
  27396. case 'SkinnedMesh':
  27397. geometry = getGeometry( data.geometry );
  27398. material = getMaterial( data.material );
  27399. object = new SkinnedMesh( geometry, material );
  27400. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27401. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27402. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27403. break;
  27404. case 'Mesh':
  27405. geometry = getGeometry( data.geometry );
  27406. material = getMaterial( data.material );
  27407. object = new Mesh( geometry, material );
  27408. break;
  27409. case 'InstancedMesh':
  27410. geometry = getGeometry( data.geometry );
  27411. material = getMaterial( data.material );
  27412. const count = data.count;
  27413. const instanceMatrix = data.instanceMatrix;
  27414. const instanceColor = data.instanceColor;
  27415. object = new InstancedMesh( geometry, material, count );
  27416. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27417. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27418. break;
  27419. case 'BatchedMesh':
  27420. geometry = getGeometry( data.geometry );
  27421. material = getMaterial( data.material );
  27422. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  27423. object.geometry = geometry;
  27424. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27425. object.sortObjects = data.sortObjects;
  27426. object._drawRanges = data.drawRanges;
  27427. object._reservedRanges = data.reservedRanges;
  27428. object._visibility = data.visibility;
  27429. object._active = data.active;
  27430. object._bounds = data.bounds.map( bound => {
  27431. const box = new Box3();
  27432. box.min.fromArray( bound.boxMin );
  27433. box.max.fromArray( bound.boxMax );
  27434. const sphere = new Sphere();
  27435. sphere.radius = bound.sphereRadius;
  27436. sphere.center.fromArray( bound.sphereCenter );
  27437. return {
  27438. boxInitialized: bound.boxInitialized,
  27439. box: box,
  27440. sphereInitialized: bound.sphereInitialized,
  27441. sphere: sphere
  27442. };
  27443. } );
  27444. object._maxInstanceCount = data.maxInstanceCount;
  27445. object._maxVertexCount = data.maxVertexCount;
  27446. object._maxIndexCount = data.maxIndexCount;
  27447. object._geometryInitialized = data.geometryInitialized;
  27448. object._geometryCount = data.geometryCount;
  27449. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27450. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  27451. break;
  27452. case 'LOD':
  27453. object = new LOD();
  27454. break;
  27455. case 'Line':
  27456. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27457. break;
  27458. case 'LineLoop':
  27459. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27460. break;
  27461. case 'LineSegments':
  27462. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27463. break;
  27464. case 'PointCloud':
  27465. case 'Points':
  27466. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27467. break;
  27468. case 'Sprite':
  27469. object = new Sprite( getMaterial( data.material ) );
  27470. break;
  27471. case 'Group':
  27472. object = new Group();
  27473. break;
  27474. case 'Bone':
  27475. object = new Bone();
  27476. break;
  27477. default:
  27478. object = new Object3D();
  27479. }
  27480. object.uuid = data.uuid;
  27481. if ( data.name !== undefined ) object.name = data.name;
  27482. if ( data.matrix !== undefined ) {
  27483. object.matrix.fromArray( data.matrix );
  27484. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27485. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27486. } else {
  27487. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27488. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27489. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27490. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27491. }
  27492. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27493. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27494. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27495. if ( data.shadow ) {
  27496. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  27497. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27498. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27499. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27500. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27501. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27502. }
  27503. if ( data.visible !== undefined ) object.visible = data.visible;
  27504. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27505. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27506. if ( data.userData !== undefined ) object.userData = data.userData;
  27507. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27508. if ( data.children !== undefined ) {
  27509. const children = data.children;
  27510. for ( let i = 0; i < children.length; i ++ ) {
  27511. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27512. }
  27513. }
  27514. if ( data.animations !== undefined ) {
  27515. const objectAnimations = data.animations;
  27516. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27517. const uuid = objectAnimations[ i ];
  27518. object.animations.push( animations[ uuid ] );
  27519. }
  27520. }
  27521. if ( data.type === 'LOD' ) {
  27522. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27523. const levels = data.levels;
  27524. for ( let l = 0; l < levels.length; l ++ ) {
  27525. const level = levels[ l ];
  27526. const child = object.getObjectByProperty( 'uuid', level.object );
  27527. if ( child !== undefined ) {
  27528. object.addLevel( child, level.distance, level.hysteresis );
  27529. }
  27530. }
  27531. }
  27532. return object;
  27533. }
  27534. bindSkeletons( object, skeletons ) {
  27535. if ( Object.keys( skeletons ).length === 0 ) return;
  27536. object.traverse( function ( child ) {
  27537. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27538. const skeleton = skeletons[ child.skeleton ];
  27539. if ( skeleton === undefined ) {
  27540. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27541. } else {
  27542. child.bind( skeleton, child.bindMatrix );
  27543. }
  27544. }
  27545. } );
  27546. }
  27547. bindLightTargets( object ) {
  27548. object.traverse( function ( child ) {
  27549. if ( child.isDirectionalLight || child.isSpotLight ) {
  27550. const uuid = child.target;
  27551. const target = object.getObjectByProperty( 'uuid', uuid );
  27552. if ( target !== undefined ) {
  27553. child.target = target;
  27554. } else {
  27555. child.target = new Object3D();
  27556. }
  27557. }
  27558. } );
  27559. }
  27560. }
  27561. const TEXTURE_MAPPING = {
  27562. UVMapping: UVMapping,
  27563. CubeReflectionMapping: CubeReflectionMapping,
  27564. CubeRefractionMapping: CubeRefractionMapping,
  27565. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27566. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27567. CubeUVReflectionMapping: CubeUVReflectionMapping
  27568. };
  27569. const TEXTURE_WRAPPING = {
  27570. RepeatWrapping: RepeatWrapping,
  27571. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27572. MirroredRepeatWrapping: MirroredRepeatWrapping
  27573. };
  27574. const TEXTURE_FILTER = {
  27575. NearestFilter: NearestFilter,
  27576. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27577. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27578. LinearFilter: LinearFilter,
  27579. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27580. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27581. };
  27582. class ImageBitmapLoader extends Loader {
  27583. constructor( manager ) {
  27584. super( manager );
  27585. this.isImageBitmapLoader = true;
  27586. if ( typeof createImageBitmap === 'undefined' ) {
  27587. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27588. }
  27589. if ( typeof fetch === 'undefined' ) {
  27590. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27591. }
  27592. this.options = { premultiplyAlpha: 'none' };
  27593. }
  27594. setOptions( options ) {
  27595. this.options = options;
  27596. return this;
  27597. }
  27598. load( url, onLoad, onProgress, onError ) {
  27599. if ( url === undefined ) url = '';
  27600. if ( this.path !== undefined ) url = this.path + url;
  27601. url = this.manager.resolveURL( url );
  27602. const scope = this;
  27603. const cached = Cache.get( url );
  27604. if ( cached !== undefined ) {
  27605. scope.manager.itemStart( url );
  27606. // If cached is a promise, wait for it to resolve
  27607. if ( cached.then ) {
  27608. cached.then( imageBitmap => {
  27609. if ( onLoad ) onLoad( imageBitmap );
  27610. scope.manager.itemEnd( url );
  27611. } ).catch( e => {
  27612. if ( onError ) onError( e );
  27613. } );
  27614. return;
  27615. }
  27616. // If cached is not a promise (i.e., it's already an imageBitmap)
  27617. setTimeout( function () {
  27618. if ( onLoad ) onLoad( cached );
  27619. scope.manager.itemEnd( url );
  27620. }, 0 );
  27621. return cached;
  27622. }
  27623. const fetchOptions = {};
  27624. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  27625. fetchOptions.headers = this.requestHeader;
  27626. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  27627. return res.blob();
  27628. } ).then( function ( blob ) {
  27629. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  27630. } ).then( function ( imageBitmap ) {
  27631. Cache.add( url, imageBitmap );
  27632. if ( onLoad ) onLoad( imageBitmap );
  27633. scope.manager.itemEnd( url );
  27634. return imageBitmap;
  27635. } ).catch( function ( e ) {
  27636. if ( onError ) onError( e );
  27637. Cache.remove( url );
  27638. scope.manager.itemError( url );
  27639. scope.manager.itemEnd( url );
  27640. } );
  27641. Cache.add( url, promise );
  27642. scope.manager.itemStart( url );
  27643. }
  27644. }
  27645. let _context;
  27646. /**
  27647. * Manages the global audio context in the engine.
  27648. *
  27649. * @hideconstructor
  27650. */
  27651. class AudioContext {
  27652. /**
  27653. * Returns the global native audio context.
  27654. *
  27655. * @return {AudioContext} The native audio context.
  27656. */
  27657. static getContext() {
  27658. if ( _context === undefined ) {
  27659. _context = new ( window.AudioContext || window.webkitAudioContext )();
  27660. }
  27661. return _context;
  27662. }
  27663. /**
  27664. * Allows to set the global native audio context from outside.
  27665. *
  27666. * @param {AudioContext} value - The native context to set.
  27667. */
  27668. static setContext( value ) {
  27669. _context = value;
  27670. }
  27671. }
  27672. class AudioLoader extends Loader {
  27673. constructor( manager ) {
  27674. super( manager );
  27675. }
  27676. load( url, onLoad, onProgress, onError ) {
  27677. const scope = this;
  27678. const loader = new FileLoader( this.manager );
  27679. loader.setResponseType( 'arraybuffer' );
  27680. loader.setPath( this.path );
  27681. loader.setRequestHeader( this.requestHeader );
  27682. loader.setWithCredentials( this.withCredentials );
  27683. loader.load( url, function ( buffer ) {
  27684. try {
  27685. // Create a copy of the buffer. The `decodeAudioData` method
  27686. // detaches the buffer when complete, preventing reuse.
  27687. const bufferCopy = buffer.slice( 0 );
  27688. const context = AudioContext.getContext();
  27689. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27690. onLoad( audioBuffer );
  27691. } ).catch( handleError );
  27692. } catch ( e ) {
  27693. handleError( e );
  27694. }
  27695. }, onProgress, onError );
  27696. function handleError( e ) {
  27697. if ( onError ) {
  27698. onError( e );
  27699. } else {
  27700. console.error( e );
  27701. }
  27702. scope.manager.itemError( url );
  27703. }
  27704. }
  27705. }
  27706. const _eyeRight = /*@__PURE__*/ new Matrix4();
  27707. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  27708. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  27709. /**
  27710. * A special type of camera that uses two perspective cameras with
  27711. * stereoscopic projection. Can be used for rendering stereo effects
  27712. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  27713. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  27714. */
  27715. class StereoCamera {
  27716. /**
  27717. * Constructs a new stereo camera.
  27718. */
  27719. constructor() {
  27720. /**
  27721. * The type property is used for detecting the object type
  27722. * in context of serialization/deserialization.
  27723. *
  27724. * @type {string}
  27725. * @readonly
  27726. */
  27727. this.type = 'StereoCamera';
  27728. /**
  27729. * The aspect.
  27730. *
  27731. * @type {number}
  27732. * @default 1
  27733. */
  27734. this.aspect = 1;
  27735. /**
  27736. * The eye separation which represents the distance
  27737. * between the left and right camera.
  27738. *
  27739. * @type {number}
  27740. * @default 0.064
  27741. */
  27742. this.eyeSep = 0.064;
  27743. /**
  27744. * The camera representing the left eye. This is added to layer `1` so objects to be
  27745. * rendered by the left camera must also be added to this layer.
  27746. *
  27747. * @type {PerspectiveCamera}
  27748. */
  27749. this.cameraL = new PerspectiveCamera();
  27750. this.cameraL.layers.enable( 1 );
  27751. this.cameraL.matrixAutoUpdate = false;
  27752. /**
  27753. * The camera representing the right eye. This is added to layer `2` so objects to be
  27754. * rendered by the right camera must also be added to this layer.
  27755. *
  27756. * @type {PerspectiveCamera}
  27757. */
  27758. this.cameraR = new PerspectiveCamera();
  27759. this.cameraR.layers.enable( 2 );
  27760. this.cameraR.matrixAutoUpdate = false;
  27761. this._cache = {
  27762. focus: null,
  27763. fov: null,
  27764. aspect: null,
  27765. near: null,
  27766. far: null,
  27767. zoom: null,
  27768. eyeSep: null
  27769. };
  27770. }
  27771. /**
  27772. * Updates the stereo camera based on the given perspective camera.
  27773. *
  27774. * @param {PerspectiveCamera} camera - The perspective camera.
  27775. */
  27776. update( camera ) {
  27777. const cache = this._cache;
  27778. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  27779. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  27780. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  27781. if ( needsUpdate ) {
  27782. cache.focus = camera.focus;
  27783. cache.fov = camera.fov;
  27784. cache.aspect = camera.aspect * this.aspect;
  27785. cache.near = camera.near;
  27786. cache.far = camera.far;
  27787. cache.zoom = camera.zoom;
  27788. cache.eyeSep = this.eyeSep;
  27789. // Off-axis stereoscopic effect based on
  27790. // http://paulbourke.net/stereographics/stereorender/
  27791. _projectionMatrix.copy( camera.projectionMatrix );
  27792. const eyeSepHalf = cache.eyeSep / 2;
  27793. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  27794. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  27795. let xmin, xmax;
  27796. // translate xOffset
  27797. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  27798. _eyeRight.elements[ 12 ] = eyeSepHalf;
  27799. // for left eye
  27800. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  27801. xmax = ymax * cache.aspect + eyeSepOnProjection;
  27802. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27803. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27804. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  27805. // for right eye
  27806. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  27807. xmax = ymax * cache.aspect - eyeSepOnProjection;
  27808. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27809. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27810. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  27811. }
  27812. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  27813. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  27814. }
  27815. }
  27816. /**
  27817. * This type of camera can be used in order to efficiently render a scene with a
  27818. * predefined set of cameras. This is an important performance aspect for
  27819. * rendering VR scenes.
  27820. *
  27821. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  27822. * to define for each sub camera the `viewport` property which determines the
  27823. * part of the viewport that is rendered with this camera.
  27824. *
  27825. * @augments PerspectiveCamera
  27826. */
  27827. class ArrayCamera extends PerspectiveCamera {
  27828. /**
  27829. * Constructs a new array camera.
  27830. *
  27831. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  27832. */
  27833. constructor( array = [] ) {
  27834. super();
  27835. /**
  27836. * This flag can be used for type testing.
  27837. *
  27838. * @type {boolean}
  27839. * @readonly
  27840. * @default true
  27841. */
  27842. this.isArrayCamera = true;
  27843. /**
  27844. * An array of perspective sub cameras.
  27845. *
  27846. * @type {Array<PerspectiveCamera>}
  27847. */
  27848. this.cameras = array;
  27849. this.index = 0;
  27850. }
  27851. }
  27852. class Clock {
  27853. constructor( autoStart = true ) {
  27854. this.autoStart = autoStart;
  27855. this.startTime = 0;
  27856. this.oldTime = 0;
  27857. this.elapsedTime = 0;
  27858. this.running = false;
  27859. }
  27860. start() {
  27861. this.startTime = now();
  27862. this.oldTime = this.startTime;
  27863. this.elapsedTime = 0;
  27864. this.running = true;
  27865. }
  27866. stop() {
  27867. this.getElapsedTime();
  27868. this.running = false;
  27869. this.autoStart = false;
  27870. }
  27871. getElapsedTime() {
  27872. this.getDelta();
  27873. return this.elapsedTime;
  27874. }
  27875. getDelta() {
  27876. let diff = 0;
  27877. if ( this.autoStart && ! this.running ) {
  27878. this.start();
  27879. return 0;
  27880. }
  27881. if ( this.running ) {
  27882. const newTime = now();
  27883. diff = ( newTime - this.oldTime ) / 1000;
  27884. this.oldTime = newTime;
  27885. this.elapsedTime += diff;
  27886. }
  27887. return diff;
  27888. }
  27889. }
  27890. function now() {
  27891. return performance.now();
  27892. }
  27893. const _position$1 = /*@__PURE__*/ new Vector3();
  27894. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  27895. const _scale$1 = /*@__PURE__*/ new Vector3();
  27896. const _orientation$1 = /*@__PURE__*/ new Vector3();
  27897. /**
  27898. * The class represents a virtual listener of the all positional and non-positional audio effects
  27899. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  27900. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  27901. *
  27902. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  27903. * camera represents the 3D transformation of the listener.
  27904. *
  27905. * @augments Object3D
  27906. */
  27907. class AudioListener extends Object3D {
  27908. /**
  27909. * Constructs a new audio listener.
  27910. */
  27911. constructor() {
  27912. super();
  27913. this.type = 'AudioListener';
  27914. /**
  27915. * The native audio context.
  27916. *
  27917. * @type {AudioContext}
  27918. * @readonly
  27919. */
  27920. this.context = AudioContext.getContext();
  27921. /**
  27922. * The gain node used for volume control.
  27923. *
  27924. * @type {GainNode}
  27925. * @readonly
  27926. */
  27927. this.gain = this.context.createGain();
  27928. this.gain.connect( this.context.destination );
  27929. /**
  27930. * An optional filter.
  27931. *
  27932. * Defined via {@AudioListener#setFilter}.
  27933. *
  27934. * @type {?AudioNode}
  27935. * @default null
  27936. * @readonly
  27937. */
  27938. this.filter = null;
  27939. /**
  27940. * Time delta values required for `linearRampToValueAtTime()` usage.
  27941. *
  27942. * @type {number}
  27943. * @default 0
  27944. * @readonly
  27945. */
  27946. this.timeDelta = 0;
  27947. // private
  27948. this._clock = new Clock();
  27949. }
  27950. /**
  27951. * Returns the listener's input node.
  27952. *
  27953. * This method is used by other audio nodes to connect to this listener.
  27954. *
  27955. * @return {GainNode} The input node.
  27956. */
  27957. getInput() {
  27958. return this.gain;
  27959. }
  27960. /**
  27961. * Removes the current filter from this listener.
  27962. *
  27963. * @return {AudioListener} A reference to this listener.
  27964. */
  27965. removeFilter() {
  27966. if ( this.filter !== null ) {
  27967. this.gain.disconnect( this.filter );
  27968. this.filter.disconnect( this.context.destination );
  27969. this.gain.connect( this.context.destination );
  27970. this.filter = null;
  27971. }
  27972. return this;
  27973. }
  27974. /**
  27975. * Returns the current set filter.
  27976. *
  27977. * @return {AudioNode} The filter.
  27978. */
  27979. getFilter() {
  27980. return this.filter;
  27981. }
  27982. /**
  27983. * Sets the given filter to this listener.
  27984. *
  27985. * @param {AudioNode} value - The filter to set.
  27986. * @return {AudioListener} A reference to this listener.
  27987. */
  27988. setFilter( value ) {
  27989. if ( this.filter !== null ) {
  27990. this.gain.disconnect( this.filter );
  27991. this.filter.disconnect( this.context.destination );
  27992. } else {
  27993. this.gain.disconnect( this.context.destination );
  27994. }
  27995. this.filter = value;
  27996. this.gain.connect( this.filter );
  27997. this.filter.connect( this.context.destination );
  27998. return this;
  27999. }
  28000. /**
  28001. * Returns the applications master volume.
  28002. *
  28003. * @return {number} The master volume.
  28004. */
  28005. getMasterVolume() {
  28006. return this.gain.gain.value;
  28007. }
  28008. /**
  28009. * Sets the applications master volume. This volume setting affects
  28010. * all audio nodes in the scene.
  28011. *
  28012. * @param {number} value - The master volume to set.
  28013. * @return {AudioListener} A reference to this listener.
  28014. */
  28015. setMasterVolume( value ) {
  28016. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28017. return this;
  28018. }
  28019. updateMatrixWorld( force ) {
  28020. super.updateMatrixWorld( force );
  28021. const listener = this.context.listener;
  28022. const up = this.up;
  28023. this.timeDelta = this._clock.getDelta();
  28024. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  28025. _orientation$1.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  28026. if ( listener.positionX ) {
  28027. // code path for Chrome (see #14393)
  28028. const endTime = this.context.currentTime + this.timeDelta;
  28029. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  28030. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  28031. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  28032. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  28033. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  28034. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  28035. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28036. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28037. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28038. } else {
  28039. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  28040. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  28041. }
  28042. }
  28043. }
  28044. /**
  28045. * Represents a non-positional ( global ) audio object.
  28046. *
  28047. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  28048. *
  28049. * ```js
  28050. * // create an AudioListener and add it to the camera
  28051. * const listener = new THREE.AudioListener();
  28052. * camera.add( listener );
  28053. *
  28054. * // create a global audio source
  28055. * const sound = new THREE.Audio( listener );
  28056. *
  28057. * // load a sound and set it as the Audio object's buffer
  28058. * const audioLoader = new THREE.AudioLoader();
  28059. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  28060. * sound.setBuffer( buffer );
  28061. * sound.setLoop( true );
  28062. * sound.setVolume( 0.5 );
  28063. * sound.play();
  28064. * });
  28065. * ```
  28066. *
  28067. * @augments Object3D
  28068. */
  28069. class Audio extends Object3D {
  28070. /**
  28071. * Constructs a new audio.
  28072. *
  28073. * @param {AudioListener} listener - The global audio listener.
  28074. */
  28075. constructor( listener ) {
  28076. super();
  28077. this.type = 'Audio';
  28078. /**
  28079. * The global audio listener.
  28080. *
  28081. * @type {AudioListener}
  28082. * @readonly
  28083. */
  28084. this.listener = listener;
  28085. /**
  28086. * The audio context.
  28087. *
  28088. * @type {AudioContext}
  28089. * @readonly
  28090. */
  28091. this.context = listener.context;
  28092. /**
  28093. * The gain node used for volume control.
  28094. *
  28095. * @type {GainNode}
  28096. * @readonly
  28097. */
  28098. this.gain = this.context.createGain();
  28099. this.gain.connect( listener.getInput() );
  28100. /**
  28101. * Whether to start playback automatically or not.
  28102. *
  28103. * @type {boolean}
  28104. * @default false
  28105. */
  28106. this.autoplay = false;
  28107. /**
  28108. * A reference to an audio buffer.
  28109. *
  28110. * Defined via {@link Audio#setBuffer}.
  28111. *
  28112. * @type {?AudioBuffer}
  28113. * @default null
  28114. * @readonly
  28115. */
  28116. this.buffer = null;
  28117. /**
  28118. * Modify pitch, measured in cents. +/- 100 is a semitone.
  28119. * +/- 1200 is an octave.
  28120. *
  28121. * Defined via {@link Audio#setDetune}.
  28122. *
  28123. * @type {number}
  28124. * @default 0
  28125. * @readonly
  28126. */
  28127. this.detune = 0;
  28128. /**
  28129. * Whether the audio should loop or not.
  28130. *
  28131. * Defined via {@link Audio#setLoop}.
  28132. *
  28133. * @type {boolean}
  28134. * @default false
  28135. * @readonly
  28136. */
  28137. this.loop = false;
  28138. /**
  28139. * Defines where in the audio buffer the replay should
  28140. * start, in seconds.
  28141. *
  28142. * @type {number}
  28143. * @default 0
  28144. */
  28145. this.loopStart = 0;
  28146. /**
  28147. * Defines where in the audio buffer the replay should
  28148. * stop, in seconds.
  28149. *
  28150. * @type {number}
  28151. * @default 0
  28152. */
  28153. this.loopEnd = 0;
  28154. /**
  28155. * An offset to the time within the audio buffer the playback
  28156. * should begin, in seconds.
  28157. *
  28158. * @type {number}
  28159. * @default 0
  28160. */
  28161. this.offset = 0;
  28162. /**
  28163. * Overrides the default duration of the audio.
  28164. *
  28165. * @type {undefined|number}
  28166. * @default undefined
  28167. */
  28168. this.duration = undefined;
  28169. /**
  28170. * The playback speed.
  28171. *
  28172. * Defined via {@link Audio#setPlaybackRate}.
  28173. *
  28174. * @type {number}
  28175. * @readonly
  28176. * @default 1
  28177. */
  28178. this.playbackRate = 1;
  28179. /**
  28180. * Indicates whether the audio is playing or not.
  28181. *
  28182. * This flag will be automatically set when using {@link Audio#play},
  28183. * {@link Audio#pause}, {@link Audio#stop}.
  28184. *
  28185. * @type {boolean}
  28186. * @readonly
  28187. * @default false
  28188. */
  28189. this.isPlaying = false;
  28190. /**
  28191. * Indicates whether the audio playback can be controlled
  28192. * with method like {@link Audio#play} or {@link Audio#pause}.
  28193. *
  28194. * This flag will be automatically set when audio sources are
  28195. * defined.
  28196. *
  28197. * @type {boolean}
  28198. * @readonly
  28199. * @default true
  28200. */
  28201. this.hasPlaybackControl = true;
  28202. /**
  28203. * Holds a reference to the current audio source.
  28204. *
  28205. * The property is automatically by one of the `set*()` methods.
  28206. *
  28207. * @type {?AudioNode}
  28208. * @readonly
  28209. * @default null
  28210. */
  28211. this.source = null;
  28212. /**
  28213. * Defines the source type.
  28214. *
  28215. * The property is automatically by one of the `set*()` methods.
  28216. *
  28217. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  28218. * @readonly
  28219. * @default 'empty'
  28220. */
  28221. this.sourceType = 'empty';
  28222. this._startedAt = 0;
  28223. this._progress = 0;
  28224. this._connected = false;
  28225. /**
  28226. * Can be used to apply a variety of low-order filters to create
  28227. * more complex sound effects e.g. via `BiquadFilterNode`.
  28228. *
  28229. * The property is automatically set by {@link Audio#setFilters}.
  28230. *
  28231. * @type {Array<AudioNode>}
  28232. * @readonly
  28233. */
  28234. this.filters = [];
  28235. }
  28236. /**
  28237. * Returns the output audio node.
  28238. *
  28239. * @return {GainNode} The output node.
  28240. */
  28241. getOutput() {
  28242. return this.gain;
  28243. }
  28244. /**
  28245. * Sets the given audio node as the source of this instance.
  28246. *
  28247. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  28248. *
  28249. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  28250. * @return {Audio} A reference to this instance.
  28251. */
  28252. setNodeSource( audioNode ) {
  28253. this.hasPlaybackControl = false;
  28254. this.sourceType = 'audioNode';
  28255. this.source = audioNode;
  28256. this.connect();
  28257. return this;
  28258. }
  28259. /**
  28260. * Sets the given media element as the source of this instance.
  28261. *
  28262. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  28263. *
  28264. * @param {HTMLMediaElement} mediaElement - The media element.
  28265. * @return {Audio} A reference to this instance.
  28266. */
  28267. setMediaElementSource( mediaElement ) {
  28268. this.hasPlaybackControl = false;
  28269. this.sourceType = 'mediaNode';
  28270. this.source = this.context.createMediaElementSource( mediaElement );
  28271. this.connect();
  28272. return this;
  28273. }
  28274. /**
  28275. * Sets the given media stream as the source of this instance.
  28276. *
  28277. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  28278. *
  28279. * @param {MediaStream} mediaStream - The media stream.
  28280. * @return {Audio} A reference to this instance.
  28281. */
  28282. setMediaStreamSource( mediaStream ) {
  28283. this.hasPlaybackControl = false;
  28284. this.sourceType = 'mediaStreamNode';
  28285. this.source = this.context.createMediaStreamSource( mediaStream );
  28286. this.connect();
  28287. return this;
  28288. }
  28289. /**
  28290. * Sets the given audio buffer as the source of this instance.
  28291. *
  28292. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  28293. *
  28294. * @param {AudioBuffer} audioBuffer - The audio buffer.
  28295. * @return {Audio} A reference to this instance.
  28296. */
  28297. setBuffer( audioBuffer ) {
  28298. this.buffer = audioBuffer;
  28299. this.sourceType = 'buffer';
  28300. if ( this.autoplay ) this.play();
  28301. return this;
  28302. }
  28303. /**
  28304. * Starts the playback of the audio.
  28305. *
  28306. * Can only be used with compatible audio sources that allow playback control.
  28307. *
  28308. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  28309. * @return {Audio|undefined} A reference to this instance.
  28310. */
  28311. play( delay = 0 ) {
  28312. if ( this.isPlaying === true ) {
  28313. console.warn( 'THREE.Audio: Audio is already playing.' );
  28314. return;
  28315. }
  28316. if ( this.hasPlaybackControl === false ) {
  28317. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28318. return;
  28319. }
  28320. this._startedAt = this.context.currentTime + delay;
  28321. const source = this.context.createBufferSource();
  28322. source.buffer = this.buffer;
  28323. source.loop = this.loop;
  28324. source.loopStart = this.loopStart;
  28325. source.loopEnd = this.loopEnd;
  28326. source.onended = this.onEnded.bind( this );
  28327. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28328. this.isPlaying = true;
  28329. this.source = source;
  28330. this.setDetune( this.detune );
  28331. this.setPlaybackRate( this.playbackRate );
  28332. return this.connect();
  28333. }
  28334. /**
  28335. * Pauses the playback of the audio.
  28336. *
  28337. * Can only be used with compatible audio sources that allow playback control.
  28338. *
  28339. * @return {Audio|undefined} A reference to this instance.
  28340. */
  28341. pause() {
  28342. if ( this.hasPlaybackControl === false ) {
  28343. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28344. return;
  28345. }
  28346. if ( this.isPlaying === true ) {
  28347. // update current progress
  28348. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28349. if ( this.loop === true ) {
  28350. // ensure _progress does not exceed duration with looped audios
  28351. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28352. }
  28353. this.source.stop();
  28354. this.source.onended = null;
  28355. this.isPlaying = false;
  28356. }
  28357. return this;
  28358. }
  28359. /**
  28360. * Stops the playback of the audio.
  28361. *
  28362. * Can only be used with compatible audio sources that allow playback control.
  28363. *
  28364. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  28365. * @return {Audio|undefined} A reference to this instance.
  28366. */
  28367. stop( delay = 0 ) {
  28368. if ( this.hasPlaybackControl === false ) {
  28369. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28370. return;
  28371. }
  28372. this._progress = 0;
  28373. if ( this.source !== null ) {
  28374. this.source.stop( this.context.currentTime + delay );
  28375. this.source.onended = null;
  28376. }
  28377. this.isPlaying = false;
  28378. return this;
  28379. }
  28380. /**
  28381. * Connects to the audio source. This is used internally on
  28382. * initialisation and when setting / removing filters.
  28383. *
  28384. * @return {Audio} A reference to this instance.
  28385. */
  28386. connect() {
  28387. if ( this.filters.length > 0 ) {
  28388. this.source.connect( this.filters[ 0 ] );
  28389. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28390. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28391. }
  28392. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28393. } else {
  28394. this.source.connect( this.getOutput() );
  28395. }
  28396. this._connected = true;
  28397. return this;
  28398. }
  28399. /**
  28400. * Disconnects to the audio source. This is used internally on
  28401. * initialisation and when setting / removing filters.
  28402. *
  28403. * @return {Audio|undefined} A reference to this instance.
  28404. */
  28405. disconnect() {
  28406. if ( this._connected === false ) {
  28407. return;
  28408. }
  28409. if ( this.filters.length > 0 ) {
  28410. this.source.disconnect( this.filters[ 0 ] );
  28411. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28412. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28413. }
  28414. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28415. } else {
  28416. this.source.disconnect( this.getOutput() );
  28417. }
  28418. this._connected = false;
  28419. return this;
  28420. }
  28421. /**
  28422. * Returns the current set filters.
  28423. *
  28424. * @return {Array<AudioNode>} The list of filters.
  28425. */
  28426. getFilters() {
  28427. return this.filters;
  28428. }
  28429. /**
  28430. * Sets an array of filters and connects them with the audio source.
  28431. *
  28432. * @param {Array<AudioNode>} [value] - A list of filters.
  28433. * @return {Audio} A reference to this instance.
  28434. */
  28435. setFilters( value ) {
  28436. if ( ! value ) value = [];
  28437. if ( this._connected === true ) {
  28438. this.disconnect();
  28439. this.filters = value.slice();
  28440. this.connect();
  28441. } else {
  28442. this.filters = value.slice();
  28443. }
  28444. return this;
  28445. }
  28446. /**
  28447. * Defines the detuning of oscillation in cents.
  28448. *
  28449. * @param {number} value - The detuning of oscillation in cents.
  28450. * @return {Audio} A reference to this instance.
  28451. */
  28452. setDetune( value ) {
  28453. this.detune = value;
  28454. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28455. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28456. }
  28457. return this;
  28458. }
  28459. /**
  28460. * Returns the detuning of oscillation in cents.
  28461. *
  28462. * @return {number} The detuning of oscillation in cents.
  28463. */
  28464. getDetune() {
  28465. return this.detune;
  28466. }
  28467. /**
  28468. * Returns the first filter in the list of filters.
  28469. *
  28470. * @return {AudioNode|undefined} The first filter in the list of filters.
  28471. */
  28472. getFilter() {
  28473. return this.getFilters()[ 0 ];
  28474. }
  28475. /**
  28476. * Applies a single filter node to the audio.
  28477. *
  28478. * @param {AudioNode} [filter] - The filter to set.
  28479. * @return {Audio} A reference to this instance.
  28480. */
  28481. setFilter( filter ) {
  28482. return this.setFilters( filter ? [ filter ] : [] );
  28483. }
  28484. /**
  28485. * Sets the playback rate.
  28486. *
  28487. * Can only be used with compatible audio sources that allow playback control.
  28488. *
  28489. * @param {number} [value] - The playback rate to set.
  28490. * @return {Audio|undefined} A reference to this instance.
  28491. */
  28492. setPlaybackRate( value ) {
  28493. if ( this.hasPlaybackControl === false ) {
  28494. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28495. return;
  28496. }
  28497. this.playbackRate = value;
  28498. if ( this.isPlaying === true ) {
  28499. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28500. }
  28501. return this;
  28502. }
  28503. /**
  28504. * Returns the current playback rate.
  28505. * @return {number} The playback rate.
  28506. */
  28507. getPlaybackRate() {
  28508. return this.playbackRate;
  28509. }
  28510. /**
  28511. * Automatically called when playback finished.
  28512. */
  28513. onEnded() {
  28514. this.isPlaying = false;
  28515. this._progress = 0;
  28516. }
  28517. /**
  28518. * Returns the loop flag.
  28519. *
  28520. * Can only be used with compatible audio sources that allow playback control.
  28521. *
  28522. * @return {boolean} Whether the audio should loop or not.
  28523. */
  28524. getLoop() {
  28525. if ( this.hasPlaybackControl === false ) {
  28526. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28527. return false;
  28528. }
  28529. return this.loop;
  28530. }
  28531. /**
  28532. * Sets the loop flag.
  28533. *
  28534. * Can only be used with compatible audio sources that allow playback control.
  28535. *
  28536. * @param {boolean} value - Whether the audio should loop or not.
  28537. * @return {Audio|undefined} A reference to this instance.
  28538. */
  28539. setLoop( value ) {
  28540. if ( this.hasPlaybackControl === false ) {
  28541. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28542. return;
  28543. }
  28544. this.loop = value;
  28545. if ( this.isPlaying === true ) {
  28546. this.source.loop = this.loop;
  28547. }
  28548. return this;
  28549. }
  28550. /**
  28551. * Sets the loop start value which defines where in the audio buffer the replay should
  28552. * start, in seconds.
  28553. *
  28554. * @param {number} value - The loop start value.
  28555. * @return {Audio} A reference to this instance.
  28556. */
  28557. setLoopStart( value ) {
  28558. this.loopStart = value;
  28559. return this;
  28560. }
  28561. /**
  28562. * Sets the loop end value which defines where in the audio buffer the replay should
  28563. * stop, in seconds.
  28564. *
  28565. * @param {number} value - The loop end value.
  28566. * @return {Audio} A reference to this instance.
  28567. */
  28568. setLoopEnd( value ) {
  28569. this.loopEnd = value;
  28570. return this;
  28571. }
  28572. /**
  28573. * Returns the volume.
  28574. *
  28575. * @return {number} The volume.
  28576. */
  28577. getVolume() {
  28578. return this.gain.gain.value;
  28579. }
  28580. /**
  28581. * Sets the volume.
  28582. *
  28583. * @param {number} value - The volume to set.
  28584. * @return {Audio} A reference to this instance.
  28585. */
  28586. setVolume( value ) {
  28587. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28588. return this;
  28589. }
  28590. copy( source, recursive ) {
  28591. super.copy( source, recursive );
  28592. if ( source.sourceType !== 'buffer' ) {
  28593. console.warn( 'THREE.Audio: Audio source type cannot be copied.' );
  28594. return this;
  28595. }
  28596. this.autoplay = source.autoplay;
  28597. this.buffer = source.buffer;
  28598. this.detune = source.detune;
  28599. this.loop = source.loop;
  28600. this.loopStart = source.loopStart;
  28601. this.loopEnd = source.loopEnd;
  28602. this.offset = source.offset;
  28603. this.duration = source.duration;
  28604. this.playbackRate = source.playbackRate;
  28605. this.hasPlaybackControl = source.hasPlaybackControl;
  28606. this.sourceType = source.sourceType;
  28607. this.filters = source.filters.slice();
  28608. return this;
  28609. }
  28610. clone( recursive ) {
  28611. return new this.constructor( this.listener ).copy( this, recursive );
  28612. }
  28613. }
  28614. const _position = /*@__PURE__*/ new Vector3();
  28615. const _quaternion = /*@__PURE__*/ new Quaternion();
  28616. const _scale = /*@__PURE__*/ new Vector3();
  28617. const _orientation = /*@__PURE__*/ new Vector3();
  28618. /**
  28619. * Represents a positional audio object.
  28620. *
  28621. * ```js
  28622. * // create an AudioListener and add it to the camera
  28623. * const listener = new THREE.AudioListener();
  28624. * camera.add( listener );
  28625. *
  28626. * // create the PositionalAudio object (passing in the listener)
  28627. * const sound = new THREE.PositionalAudio( listener );
  28628. *
  28629. * // load a sound and set it as the PositionalAudio object's buffer
  28630. * const audioLoader = new THREE.AudioLoader();
  28631. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  28632. * sound.setBuffer( buffer );
  28633. * sound.setRefDistance( 20 );
  28634. * sound.play();
  28635. * });
  28636. *
  28637. * // create an object for the sound to play from
  28638. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  28639. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  28640. * const mesh = new THREE.Mesh( sphere, material );
  28641. * scene.add( mesh );
  28642. *
  28643. * // finally add the sound to the mesh
  28644. * mesh.add( sound );
  28645. *
  28646. * @augments Audio
  28647. */
  28648. class PositionalAudio extends Audio {
  28649. /**
  28650. * Constructs a positional audio.
  28651. *
  28652. * @param {AudioListener} listener - The global audio listener.
  28653. */
  28654. constructor( listener ) {
  28655. super( listener );
  28656. /**
  28657. * The panner node represents the location, direction, and behavior of an audio
  28658. * source in 3D space.
  28659. *
  28660. * @type {PannerNode}
  28661. * @readonly
  28662. */
  28663. this.panner = this.context.createPanner();
  28664. this.panner.panningModel = 'HRTF';
  28665. this.panner.connect( this.gain );
  28666. }
  28667. connect() {
  28668. super.connect();
  28669. this.panner.connect( this.gain );
  28670. return this;
  28671. }
  28672. disconnect() {
  28673. super.disconnect();
  28674. this.panner.disconnect( this.gain );
  28675. return this;
  28676. }
  28677. getOutput() {
  28678. return this.panner;
  28679. }
  28680. /**
  28681. * Returns the current reference distance.
  28682. *
  28683. * @return {number} The reference distance.
  28684. */
  28685. getRefDistance() {
  28686. return this.panner.refDistance;
  28687. }
  28688. /**
  28689. * Defines the reference distance for reducing volume as the audio source moves
  28690. * further from the listener – i.e. the distance at which the volume reduction
  28691. * starts taking effect.
  28692. *
  28693. * @param {number} value - The reference distance to set.
  28694. * @return {Audio} A reference to this instance.
  28695. */
  28696. setRefDistance( value ) {
  28697. this.panner.refDistance = value;
  28698. return this;
  28699. }
  28700. /**
  28701. * Returns the current rolloff factor.
  28702. *
  28703. * @return {number} The rolloff factor.
  28704. */
  28705. getRolloffFactor() {
  28706. return this.panner.rolloffFactor;
  28707. }
  28708. /**
  28709. * Defines how quickly the volume is reduced as the source moves away from the listener.
  28710. *
  28711. * @param {number} value - The rolloff factor.
  28712. * @return {Audio} A reference to this instance.
  28713. */
  28714. setRolloffFactor( value ) {
  28715. this.panner.rolloffFactor = value;
  28716. return this;
  28717. }
  28718. /**
  28719. * Returns the current distance model.
  28720. *
  28721. * @return {('linear'|'inverse'|'exponential')} The distance model.
  28722. */
  28723. getDistanceModel() {
  28724. return this.panner.distanceModel;
  28725. }
  28726. /**
  28727. * Defines which algorithm to use to reduce the volume of the audio source
  28728. * as it moves away from the listener.
  28729. *
  28730. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  28731. * for more details.
  28732. *
  28733. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  28734. * @return {Audio} A reference to this instance.
  28735. */
  28736. setDistanceModel( value ) {
  28737. this.panner.distanceModel = value;
  28738. return this;
  28739. }
  28740. /**
  28741. * Returns the current max distance.
  28742. *
  28743. * @return {number} The max distance.
  28744. */
  28745. getMaxDistance() {
  28746. return this.panner.maxDistance;
  28747. }
  28748. /**
  28749. * Defines the maximum distance between the audio source and the listener,
  28750. * after which the volume is not reduced any further.
  28751. *
  28752. * This value is used only by the `linear` distance model.
  28753. *
  28754. * @param {number} value - The max distance.
  28755. * @return {Audio} A reference to this instance.
  28756. */
  28757. setMaxDistance( value ) {
  28758. this.panner.maxDistance = value;
  28759. return this;
  28760. }
  28761. /**
  28762. * Sets the directional cone in which the audio can be listened.
  28763. *
  28764. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  28765. * @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.
  28766. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  28767. * @return {Audio} A reference to this instance.
  28768. */
  28769. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28770. this.panner.coneInnerAngle = coneInnerAngle;
  28771. this.panner.coneOuterAngle = coneOuterAngle;
  28772. this.panner.coneOuterGain = coneOuterGain;
  28773. return this;
  28774. }
  28775. updateMatrixWorld( force ) {
  28776. super.updateMatrixWorld( force );
  28777. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28778. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28779. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28780. const panner = this.panner;
  28781. if ( panner.positionX ) {
  28782. // code path for Chrome and Firefox (see #14393)
  28783. const endTime = this.context.currentTime + this.listener.timeDelta;
  28784. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28785. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28786. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28787. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28788. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28789. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28790. } else {
  28791. panner.setPosition( _position.x, _position.y, _position.z );
  28792. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28793. }
  28794. }
  28795. }
  28796. /**
  28797. * This class can be used to analyse audio data.
  28798. *
  28799. * ```js
  28800. * // create an AudioListener and add it to the camera
  28801. * const listener = new THREE.AudioListener();
  28802. * camera.add( listener );
  28803. *
  28804. * // create an Audio source
  28805. * const sound = new THREE.Audio( listener );
  28806. *
  28807. * // load a sound and set it as the Audio object's buffer
  28808. * const audioLoader = new THREE.AudioLoader();
  28809. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  28810. * sound.setBuffer( buffer );
  28811. * sound.setLoop(true);
  28812. * sound.setVolume(0.5);
  28813. * sound.play();
  28814. * });
  28815. *
  28816. * // create an AudioAnalyser, passing in the sound and desired fftSize
  28817. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  28818. *
  28819. * // get the average frequency of the sound
  28820. * const data = analyser.getAverageFrequency();
  28821. * ```
  28822. */
  28823. class AudioAnalyser {
  28824. /**
  28825. * Constructs a new audio analyzer.
  28826. *
  28827. * @param {Audio} audio - The audio to analyze.
  28828. * @param {Audio} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  28829. */
  28830. constructor( audio, fftSize = 2048 ) {
  28831. /**
  28832. * The global audio listener.
  28833. *
  28834. * @type {AnalyserNode}
  28835. */
  28836. this.analyser = audio.context.createAnalyser();
  28837. this.analyser.fftSize = fftSize;
  28838. /**
  28839. * Holds the analyzed data.
  28840. *
  28841. * @type {Uint8Array}
  28842. */
  28843. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28844. audio.getOutput().connect( this.analyser );
  28845. }
  28846. /**
  28847. * Returns an array with frequency data of the audio.
  28848. *
  28849. * Each item in the array represents the decibel value for a specific frequency.
  28850. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  28851. * For example, for 48000 sample rate, the last item of the array will represent
  28852. * the decibel value for 24000 Hz.
  28853. *
  28854. * @return {Uint8Array} The frequency data.
  28855. */
  28856. getFrequencyData() {
  28857. this.analyser.getByteFrequencyData( this.data );
  28858. return this.data;
  28859. }
  28860. /**
  28861. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  28862. *
  28863. * @return {number} The average frequency.
  28864. */
  28865. getAverageFrequency() {
  28866. let value = 0;
  28867. const data = this.getFrequencyData();
  28868. for ( let i = 0; i < data.length; i ++ ) {
  28869. value += data[ i ];
  28870. }
  28871. return value / data.length;
  28872. }
  28873. }
  28874. class PropertyMixer {
  28875. constructor( binding, typeName, valueSize ) {
  28876. this.binding = binding;
  28877. this.valueSize = valueSize;
  28878. let mixFunction,
  28879. mixFunctionAdditive,
  28880. setIdentity;
  28881. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28882. //
  28883. // interpolators can use .buffer as their .result
  28884. // the data then goes to 'incoming'
  28885. //
  28886. // 'accu0' and 'accu1' are used frame-interleaved for
  28887. // the cumulative result and are compared to detect
  28888. // changes
  28889. //
  28890. // 'orig' stores the original state of the property
  28891. //
  28892. // 'add' is used for additive cumulative results
  28893. //
  28894. // 'work' is optional and is only present for quaternion types. It is used
  28895. // to store intermediate quaternion multiplication results
  28896. switch ( typeName ) {
  28897. case 'quaternion':
  28898. mixFunction = this._slerp;
  28899. mixFunctionAdditive = this._slerpAdditive;
  28900. setIdentity = this._setAdditiveIdentityQuaternion;
  28901. this.buffer = new Float64Array( valueSize * 6 );
  28902. this._workIndex = 5;
  28903. break;
  28904. case 'string':
  28905. case 'bool':
  28906. mixFunction = this._select;
  28907. // Use the regular mix function and for additive on these types,
  28908. // additive is not relevant for non-numeric types
  28909. mixFunctionAdditive = this._select;
  28910. setIdentity = this._setAdditiveIdentityOther;
  28911. this.buffer = new Array( valueSize * 5 );
  28912. break;
  28913. default:
  28914. mixFunction = this._lerp;
  28915. mixFunctionAdditive = this._lerpAdditive;
  28916. setIdentity = this._setAdditiveIdentityNumeric;
  28917. this.buffer = new Float64Array( valueSize * 5 );
  28918. }
  28919. this._mixBufferRegion = mixFunction;
  28920. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28921. this._setIdentity = setIdentity;
  28922. this._origIndex = 3;
  28923. this._addIndex = 4;
  28924. this.cumulativeWeight = 0;
  28925. this.cumulativeWeightAdditive = 0;
  28926. this.useCount = 0;
  28927. this.referenceCount = 0;
  28928. }
  28929. // accumulate data in the 'incoming' region into 'accu<i>'
  28930. accumulate( accuIndex, weight ) {
  28931. // note: happily accumulating nothing when weight = 0, the caller knows
  28932. // the weight and shouldn't have made the call in the first place
  28933. const buffer = this.buffer,
  28934. stride = this.valueSize,
  28935. offset = accuIndex * stride + stride;
  28936. let currentWeight = this.cumulativeWeight;
  28937. if ( currentWeight === 0 ) {
  28938. // accuN := incoming * weight
  28939. for ( let i = 0; i !== stride; ++ i ) {
  28940. buffer[ offset + i ] = buffer[ i ];
  28941. }
  28942. currentWeight = weight;
  28943. } else {
  28944. // accuN := accuN + incoming * weight
  28945. currentWeight += weight;
  28946. const mix = weight / currentWeight;
  28947. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28948. }
  28949. this.cumulativeWeight = currentWeight;
  28950. }
  28951. // accumulate data in the 'incoming' region into 'add'
  28952. accumulateAdditive( weight ) {
  28953. const buffer = this.buffer,
  28954. stride = this.valueSize,
  28955. offset = stride * this._addIndex;
  28956. if ( this.cumulativeWeightAdditive === 0 ) {
  28957. // add = identity
  28958. this._setIdentity();
  28959. }
  28960. // add := add + incoming * weight
  28961. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28962. this.cumulativeWeightAdditive += weight;
  28963. }
  28964. // apply the state of 'accu<i>' to the binding when accus differ
  28965. apply( accuIndex ) {
  28966. const stride = this.valueSize,
  28967. buffer = this.buffer,
  28968. offset = accuIndex * stride + stride,
  28969. weight = this.cumulativeWeight,
  28970. weightAdditive = this.cumulativeWeightAdditive,
  28971. binding = this.binding;
  28972. this.cumulativeWeight = 0;
  28973. this.cumulativeWeightAdditive = 0;
  28974. if ( weight < 1 ) {
  28975. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28976. const originalValueOffset = stride * this._origIndex;
  28977. this._mixBufferRegion(
  28978. buffer, offset, originalValueOffset, 1 - weight, stride );
  28979. }
  28980. if ( weightAdditive > 0 ) {
  28981. // accuN := accuN + additive accuN
  28982. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28983. }
  28984. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28985. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28986. // value has changed -> update scene graph
  28987. binding.setValue( buffer, offset );
  28988. break;
  28989. }
  28990. }
  28991. }
  28992. // remember the state of the bound property and copy it to both accus
  28993. saveOriginalState() {
  28994. const binding = this.binding;
  28995. const buffer = this.buffer,
  28996. stride = this.valueSize,
  28997. originalValueOffset = stride * this._origIndex;
  28998. binding.getValue( buffer, originalValueOffset );
  28999. // accu[0..1] := orig -- initially detect changes against the original
  29000. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  29001. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  29002. }
  29003. // Add to identity for additive
  29004. this._setIdentity();
  29005. this.cumulativeWeight = 0;
  29006. this.cumulativeWeightAdditive = 0;
  29007. }
  29008. // apply the state previously taken via 'saveOriginalState' to the binding
  29009. restoreOriginalState() {
  29010. const originalValueOffset = this.valueSize * 3;
  29011. this.binding.setValue( this.buffer, originalValueOffset );
  29012. }
  29013. _setAdditiveIdentityNumeric() {
  29014. const startIndex = this._addIndex * this.valueSize;
  29015. const endIndex = startIndex + this.valueSize;
  29016. for ( let i = startIndex; i < endIndex; i ++ ) {
  29017. this.buffer[ i ] = 0;
  29018. }
  29019. }
  29020. _setAdditiveIdentityQuaternion() {
  29021. this._setAdditiveIdentityNumeric();
  29022. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  29023. }
  29024. _setAdditiveIdentityOther() {
  29025. const startIndex = this._origIndex * this.valueSize;
  29026. const targetIndex = this._addIndex * this.valueSize;
  29027. for ( let i = 0; i < this.valueSize; i ++ ) {
  29028. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  29029. }
  29030. }
  29031. // mix functions
  29032. _select( buffer, dstOffset, srcOffset, t, stride ) {
  29033. if ( t >= 0.5 ) {
  29034. for ( let i = 0; i !== stride; ++ i ) {
  29035. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  29036. }
  29037. }
  29038. }
  29039. _slerp( buffer, dstOffset, srcOffset, t ) {
  29040. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  29041. }
  29042. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  29043. const workOffset = this._workIndex * stride;
  29044. // Store result in intermediate buffer offset
  29045. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  29046. // Slerp to the intermediate result
  29047. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  29048. }
  29049. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  29050. const s = 1 - t;
  29051. for ( let i = 0; i !== stride; ++ i ) {
  29052. const j = dstOffset + i;
  29053. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  29054. }
  29055. }
  29056. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  29057. for ( let i = 0; i !== stride; ++ i ) {
  29058. const j = dstOffset + i;
  29059. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  29060. }
  29061. }
  29062. }
  29063. // Characters [].:/ are reserved for track binding syntax.
  29064. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  29065. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  29066. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  29067. // only latin characters, and the unicode \p{L} is not yet supported. So
  29068. // instead, we exclude reserved characters and match everything else.
  29069. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  29070. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  29071. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  29072. // be matched to parse the rest of the track name.
  29073. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  29074. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  29075. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  29076. // Object on target node, and accessor. May not contain reserved
  29077. // characters. Accessor may contain any character except closing bracket.
  29078. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  29079. // Property and accessor. May not contain reserved characters. Accessor may
  29080. // contain any non-bracket characters.
  29081. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  29082. const _trackRe = new RegExp( ''
  29083. + '^'
  29084. + _directoryRe
  29085. + _nodeRe
  29086. + _objectRe
  29087. + _propertyRe
  29088. + '$'
  29089. );
  29090. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  29091. class Composite {
  29092. constructor( targetGroup, path, optionalParsedPath ) {
  29093. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  29094. this._targetGroup = targetGroup;
  29095. this._bindings = targetGroup.subscribe_( path, parsedPath );
  29096. }
  29097. getValue( array, offset ) {
  29098. this.bind(); // bind all binding
  29099. const firstValidIndex = this._targetGroup.nCachedObjects_,
  29100. binding = this._bindings[ firstValidIndex ];
  29101. // and only call .getValue on the first
  29102. if ( binding !== undefined ) binding.getValue( array, offset );
  29103. }
  29104. setValue( array, offset ) {
  29105. const bindings = this._bindings;
  29106. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29107. bindings[ i ].setValue( array, offset );
  29108. }
  29109. }
  29110. bind() {
  29111. const bindings = this._bindings;
  29112. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29113. bindings[ i ].bind();
  29114. }
  29115. }
  29116. unbind() {
  29117. const bindings = this._bindings;
  29118. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  29119. bindings[ i ].unbind();
  29120. }
  29121. }
  29122. }
  29123. // Note: This class uses a State pattern on a per-method basis:
  29124. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  29125. // prototype version of these methods with one that represents
  29126. // the bound state. When the property is not found, the methods
  29127. // become no-ops.
  29128. class PropertyBinding {
  29129. constructor( rootNode, path, parsedPath ) {
  29130. this.path = path;
  29131. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  29132. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  29133. this.rootNode = rootNode;
  29134. // initial state of these methods that calls 'bind'
  29135. this.getValue = this._getValue_unbound;
  29136. this.setValue = this._setValue_unbound;
  29137. }
  29138. static create( root, path, parsedPath ) {
  29139. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  29140. return new PropertyBinding( root, path, parsedPath );
  29141. } else {
  29142. return new PropertyBinding.Composite( root, path, parsedPath );
  29143. }
  29144. }
  29145. /**
  29146. * Replaces spaces with underscores and removes unsupported characters from
  29147. * node names, to ensure compatibility with parseTrackName().
  29148. *
  29149. * @param {string} name Node name to be sanitized.
  29150. * @return {string}
  29151. */
  29152. static sanitizeNodeName( name ) {
  29153. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  29154. }
  29155. static parseTrackName( trackName ) {
  29156. const matches = _trackRe.exec( trackName );
  29157. if ( matches === null ) {
  29158. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  29159. }
  29160. const results = {
  29161. // directoryName: matches[ 1 ], // (tschw) currently unused
  29162. nodeName: matches[ 2 ],
  29163. objectName: matches[ 3 ],
  29164. objectIndex: matches[ 4 ],
  29165. propertyName: matches[ 5 ], // required
  29166. propertyIndex: matches[ 6 ]
  29167. };
  29168. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  29169. if ( lastDot !== undefined && lastDot !== -1 ) {
  29170. const objectName = results.nodeName.substring( lastDot + 1 );
  29171. // Object names must be checked against an allowlist. Otherwise, there
  29172. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  29173. // 'bar' could be the objectName, or part of a nodeName (which can
  29174. // include '.' characters).
  29175. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  29176. results.nodeName = results.nodeName.substring( 0, lastDot );
  29177. results.objectName = objectName;
  29178. }
  29179. }
  29180. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  29181. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  29182. }
  29183. return results;
  29184. }
  29185. static findNode( root, nodeName ) {
  29186. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  29187. return root;
  29188. }
  29189. // search into skeleton bones.
  29190. if ( root.skeleton ) {
  29191. const bone = root.skeleton.getBoneByName( nodeName );
  29192. if ( bone !== undefined ) {
  29193. return bone;
  29194. }
  29195. }
  29196. // search into node subtree.
  29197. if ( root.children ) {
  29198. const searchNodeSubtree = function ( children ) {
  29199. for ( let i = 0; i < children.length; i ++ ) {
  29200. const childNode = children[ i ];
  29201. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  29202. return childNode;
  29203. }
  29204. const result = searchNodeSubtree( childNode.children );
  29205. if ( result ) return result;
  29206. }
  29207. return null;
  29208. };
  29209. const subTreeNode = searchNodeSubtree( root.children );
  29210. if ( subTreeNode ) {
  29211. return subTreeNode;
  29212. }
  29213. }
  29214. return null;
  29215. }
  29216. // these are used to "bind" a nonexistent property
  29217. _getValue_unavailable() {}
  29218. _setValue_unavailable() {}
  29219. // Getters
  29220. _getValue_direct( buffer, offset ) {
  29221. buffer[ offset ] = this.targetObject[ this.propertyName ];
  29222. }
  29223. _getValue_array( buffer, offset ) {
  29224. const source = this.resolvedProperty;
  29225. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  29226. buffer[ offset ++ ] = source[ i ];
  29227. }
  29228. }
  29229. _getValue_arrayElement( buffer, offset ) {
  29230. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  29231. }
  29232. _getValue_toArray( buffer, offset ) {
  29233. this.resolvedProperty.toArray( buffer, offset );
  29234. }
  29235. // Direct
  29236. _setValue_direct( buffer, offset ) {
  29237. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29238. }
  29239. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  29240. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29241. this.targetObject.needsUpdate = true;
  29242. }
  29243. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29244. this.targetObject[ this.propertyName ] = buffer[ offset ];
  29245. this.targetObject.matrixWorldNeedsUpdate = true;
  29246. }
  29247. // EntireArray
  29248. _setValue_array( buffer, offset ) {
  29249. const dest = this.resolvedProperty;
  29250. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29251. dest[ i ] = buffer[ offset ++ ];
  29252. }
  29253. }
  29254. _setValue_array_setNeedsUpdate( buffer, offset ) {
  29255. const dest = this.resolvedProperty;
  29256. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29257. dest[ i ] = buffer[ offset ++ ];
  29258. }
  29259. this.targetObject.needsUpdate = true;
  29260. }
  29261. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29262. const dest = this.resolvedProperty;
  29263. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  29264. dest[ i ] = buffer[ offset ++ ];
  29265. }
  29266. this.targetObject.matrixWorldNeedsUpdate = true;
  29267. }
  29268. // ArrayElement
  29269. _setValue_arrayElement( buffer, offset ) {
  29270. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29271. }
  29272. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  29273. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29274. this.targetObject.needsUpdate = true;
  29275. }
  29276. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29277. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  29278. this.targetObject.matrixWorldNeedsUpdate = true;
  29279. }
  29280. // HasToFromArray
  29281. _setValue_fromArray( buffer, offset ) {
  29282. this.resolvedProperty.fromArray( buffer, offset );
  29283. }
  29284. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  29285. this.resolvedProperty.fromArray( buffer, offset );
  29286. this.targetObject.needsUpdate = true;
  29287. }
  29288. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  29289. this.resolvedProperty.fromArray( buffer, offset );
  29290. this.targetObject.matrixWorldNeedsUpdate = true;
  29291. }
  29292. _getValue_unbound( targetArray, offset ) {
  29293. this.bind();
  29294. this.getValue( targetArray, offset );
  29295. }
  29296. _setValue_unbound( sourceArray, offset ) {
  29297. this.bind();
  29298. this.setValue( sourceArray, offset );
  29299. }
  29300. // create getter / setter pair for a property in the scene graph
  29301. bind() {
  29302. let targetObject = this.node;
  29303. const parsedPath = this.parsedPath;
  29304. const objectName = parsedPath.objectName;
  29305. const propertyName = parsedPath.propertyName;
  29306. let propertyIndex = parsedPath.propertyIndex;
  29307. if ( ! targetObject ) {
  29308. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  29309. this.node = targetObject;
  29310. }
  29311. // set fail state so we can just 'return' on error
  29312. this.getValue = this._getValue_unavailable;
  29313. this.setValue = this._setValue_unavailable;
  29314. // ensure there is a value node
  29315. if ( ! targetObject ) {
  29316. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  29317. return;
  29318. }
  29319. if ( objectName ) {
  29320. let objectIndex = parsedPath.objectIndex;
  29321. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29322. switch ( objectName ) {
  29323. case 'materials':
  29324. if ( ! targetObject.material ) {
  29325. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29326. return;
  29327. }
  29328. if ( ! targetObject.material.materials ) {
  29329. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29330. return;
  29331. }
  29332. targetObject = targetObject.material.materials;
  29333. break;
  29334. case 'bones':
  29335. if ( ! targetObject.skeleton ) {
  29336. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29337. return;
  29338. }
  29339. // potential future optimization: skip this if propertyIndex is already an integer
  29340. // and convert the integer string to a true integer.
  29341. targetObject = targetObject.skeleton.bones;
  29342. // support resolving morphTarget names into indices.
  29343. for ( let i = 0; i < targetObject.length; i ++ ) {
  29344. if ( targetObject[ i ].name === objectIndex ) {
  29345. objectIndex = i;
  29346. break;
  29347. }
  29348. }
  29349. break;
  29350. case 'map':
  29351. if ( 'map' in targetObject ) {
  29352. targetObject = targetObject.map;
  29353. break;
  29354. }
  29355. if ( ! targetObject.material ) {
  29356. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29357. return;
  29358. }
  29359. if ( ! targetObject.material.map ) {
  29360. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  29361. return;
  29362. }
  29363. targetObject = targetObject.material.map;
  29364. break;
  29365. default:
  29366. if ( targetObject[ objectName ] === undefined ) {
  29367. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29368. return;
  29369. }
  29370. targetObject = targetObject[ objectName ];
  29371. }
  29372. if ( objectIndex !== undefined ) {
  29373. if ( targetObject[ objectIndex ] === undefined ) {
  29374. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29375. return;
  29376. }
  29377. targetObject = targetObject[ objectIndex ];
  29378. }
  29379. }
  29380. // resolve property
  29381. const nodeProperty = targetObject[ propertyName ];
  29382. if ( nodeProperty === undefined ) {
  29383. const nodeName = parsedPath.nodeName;
  29384. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29385. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29386. return;
  29387. }
  29388. // determine versioning scheme
  29389. let versioning = this.Versioning.None;
  29390. this.targetObject = targetObject;
  29391. if ( targetObject.isMaterial === true ) {
  29392. versioning = this.Versioning.NeedsUpdate;
  29393. } else if ( targetObject.isObject3D === true ) {
  29394. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29395. }
  29396. // determine how the property gets bound
  29397. let bindingType = this.BindingType.Direct;
  29398. if ( propertyIndex !== undefined ) {
  29399. // access a sub element of the property array (only primitives are supported right now)
  29400. if ( propertyName === 'morphTargetInfluences' ) {
  29401. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29402. // support resolving morphTarget names into indices.
  29403. if ( ! targetObject.geometry ) {
  29404. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29405. return;
  29406. }
  29407. if ( ! targetObject.geometry.morphAttributes ) {
  29408. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29409. return;
  29410. }
  29411. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  29412. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  29413. }
  29414. }
  29415. bindingType = this.BindingType.ArrayElement;
  29416. this.resolvedProperty = nodeProperty;
  29417. this.propertyIndex = propertyIndex;
  29418. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29419. // must use copy for Object3D.Euler/Quaternion
  29420. bindingType = this.BindingType.HasFromToArray;
  29421. this.resolvedProperty = nodeProperty;
  29422. } else if ( Array.isArray( nodeProperty ) ) {
  29423. bindingType = this.BindingType.EntireArray;
  29424. this.resolvedProperty = nodeProperty;
  29425. } else {
  29426. this.propertyName = propertyName;
  29427. }
  29428. // select getter / setter
  29429. this.getValue = this.GetterByBindingType[ bindingType ];
  29430. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29431. }
  29432. unbind() {
  29433. this.node = null;
  29434. // back to the prototype version of getValue / setValue
  29435. // note: avoiding to mutate the shape of 'this' via 'delete'
  29436. this.getValue = this._getValue_unbound;
  29437. this.setValue = this._setValue_unbound;
  29438. }
  29439. }
  29440. PropertyBinding.Composite = Composite;
  29441. PropertyBinding.prototype.BindingType = {
  29442. Direct: 0,
  29443. EntireArray: 1,
  29444. ArrayElement: 2,
  29445. HasFromToArray: 3
  29446. };
  29447. PropertyBinding.prototype.Versioning = {
  29448. None: 0,
  29449. NeedsUpdate: 1,
  29450. MatrixWorldNeedsUpdate: 2
  29451. };
  29452. PropertyBinding.prototype.GetterByBindingType = [
  29453. PropertyBinding.prototype._getValue_direct,
  29454. PropertyBinding.prototype._getValue_array,
  29455. PropertyBinding.prototype._getValue_arrayElement,
  29456. PropertyBinding.prototype._getValue_toArray,
  29457. ];
  29458. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  29459. [
  29460. // Direct
  29461. PropertyBinding.prototype._setValue_direct,
  29462. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  29463. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  29464. ], [
  29465. // EntireArray
  29466. PropertyBinding.prototype._setValue_array,
  29467. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  29468. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  29469. ], [
  29470. // ArrayElement
  29471. PropertyBinding.prototype._setValue_arrayElement,
  29472. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  29473. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  29474. ], [
  29475. // HasToFromArray
  29476. PropertyBinding.prototype._setValue_fromArray,
  29477. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  29478. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  29479. ]
  29480. ];
  29481. /**
  29482. *
  29483. * A group of objects that receives a shared animation state.
  29484. *
  29485. * Usage:
  29486. *
  29487. * - Add objects you would otherwise pass as 'root' to the
  29488. * constructor or the .clipAction method of AnimationMixer.
  29489. *
  29490. * - Instead pass this object as 'root'.
  29491. *
  29492. * - You can also add and remove objects later when the mixer
  29493. * is running.
  29494. *
  29495. * Note:
  29496. *
  29497. * Objects of this class appear as one object to the mixer,
  29498. * so cache control of the individual objects must be done
  29499. * on the group.
  29500. *
  29501. * Limitation:
  29502. *
  29503. * - The animated properties must be compatible among the
  29504. * all objects in the group.
  29505. *
  29506. * - A single property can either be controlled through a
  29507. * target group or directly, but not both.
  29508. */
  29509. class AnimationObjectGroup {
  29510. constructor() {
  29511. this.isAnimationObjectGroup = true;
  29512. this.uuid = generateUUID();
  29513. // cached objects followed by the active ones
  29514. this._objects = Array.prototype.slice.call( arguments );
  29515. this.nCachedObjects_ = 0; // threshold
  29516. // note: read by PropertyBinding.Composite
  29517. const indices = {};
  29518. this._indicesByUUID = indices; // for bookkeeping
  29519. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29520. indices[ arguments[ i ].uuid ] = i;
  29521. }
  29522. this._paths = []; // inside: string
  29523. this._parsedPaths = []; // inside: { we don't care, here }
  29524. this._bindings = []; // inside: Array< PropertyBinding >
  29525. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29526. const scope = this;
  29527. this.stats = {
  29528. objects: {
  29529. get total() {
  29530. return scope._objects.length;
  29531. },
  29532. get inUse() {
  29533. return this.total - scope.nCachedObjects_;
  29534. }
  29535. },
  29536. get bindingsPerObject() {
  29537. return scope._bindings.length;
  29538. }
  29539. };
  29540. }
  29541. add() {
  29542. const objects = this._objects,
  29543. indicesByUUID = this._indicesByUUID,
  29544. paths = this._paths,
  29545. parsedPaths = this._parsedPaths,
  29546. bindings = this._bindings,
  29547. nBindings = bindings.length;
  29548. let knownObject = undefined,
  29549. nObjects = objects.length,
  29550. nCachedObjects = this.nCachedObjects_;
  29551. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29552. const object = arguments[ i ],
  29553. uuid = object.uuid;
  29554. let index = indicesByUUID[ uuid ];
  29555. if ( index === undefined ) {
  29556. // unknown object -> add it to the ACTIVE region
  29557. index = nObjects ++;
  29558. indicesByUUID[ uuid ] = index;
  29559. objects.push( object );
  29560. // accounting is done, now do the same for all bindings
  29561. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29562. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29563. }
  29564. } else if ( index < nCachedObjects ) {
  29565. knownObject = objects[ index ];
  29566. // move existing object to the ACTIVE region
  29567. const firstActiveIndex = -- nCachedObjects,
  29568. lastCachedObject = objects[ firstActiveIndex ];
  29569. indicesByUUID[ lastCachedObject.uuid ] = index;
  29570. objects[ index ] = lastCachedObject;
  29571. indicesByUUID[ uuid ] = firstActiveIndex;
  29572. objects[ firstActiveIndex ] = object;
  29573. // accounting is done, now do the same for all bindings
  29574. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29575. const bindingsForPath = bindings[ j ],
  29576. lastCached = bindingsForPath[ firstActiveIndex ];
  29577. let binding = bindingsForPath[ index ];
  29578. bindingsForPath[ index ] = lastCached;
  29579. if ( binding === undefined ) {
  29580. // since we do not bother to create new bindings
  29581. // for objects that are cached, the binding may
  29582. // or may not exist
  29583. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29584. }
  29585. bindingsForPath[ firstActiveIndex ] = binding;
  29586. }
  29587. } else if ( objects[ index ] !== knownObject ) {
  29588. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29589. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29590. } // else the object is already where we want it to be
  29591. } // for arguments
  29592. this.nCachedObjects_ = nCachedObjects;
  29593. }
  29594. remove() {
  29595. const objects = this._objects,
  29596. indicesByUUID = this._indicesByUUID,
  29597. bindings = this._bindings,
  29598. nBindings = bindings.length;
  29599. let nCachedObjects = this.nCachedObjects_;
  29600. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29601. const object = arguments[ i ],
  29602. uuid = object.uuid,
  29603. index = indicesByUUID[ uuid ];
  29604. if ( index !== undefined && index >= nCachedObjects ) {
  29605. // move existing object into the CACHED region
  29606. const lastCachedIndex = nCachedObjects ++,
  29607. firstActiveObject = objects[ lastCachedIndex ];
  29608. indicesByUUID[ firstActiveObject.uuid ] = index;
  29609. objects[ index ] = firstActiveObject;
  29610. indicesByUUID[ uuid ] = lastCachedIndex;
  29611. objects[ lastCachedIndex ] = object;
  29612. // accounting is done, now do the same for all bindings
  29613. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29614. const bindingsForPath = bindings[ j ],
  29615. firstActive = bindingsForPath[ lastCachedIndex ],
  29616. binding = bindingsForPath[ index ];
  29617. bindingsForPath[ index ] = firstActive;
  29618. bindingsForPath[ lastCachedIndex ] = binding;
  29619. }
  29620. }
  29621. } // for arguments
  29622. this.nCachedObjects_ = nCachedObjects;
  29623. }
  29624. // remove & forget
  29625. uncache() {
  29626. const objects = this._objects,
  29627. indicesByUUID = this._indicesByUUID,
  29628. bindings = this._bindings,
  29629. nBindings = bindings.length;
  29630. let nCachedObjects = this.nCachedObjects_,
  29631. nObjects = objects.length;
  29632. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29633. const object = arguments[ i ],
  29634. uuid = object.uuid,
  29635. index = indicesByUUID[ uuid ];
  29636. if ( index !== undefined ) {
  29637. delete indicesByUUID[ uuid ];
  29638. if ( index < nCachedObjects ) {
  29639. // object is cached, shrink the CACHED region
  29640. const firstActiveIndex = -- nCachedObjects,
  29641. lastCachedObject = objects[ firstActiveIndex ],
  29642. lastIndex = -- nObjects,
  29643. lastObject = objects[ lastIndex ];
  29644. // last cached object takes this object's place
  29645. indicesByUUID[ lastCachedObject.uuid ] = index;
  29646. objects[ index ] = lastCachedObject;
  29647. // last object goes to the activated slot and pop
  29648. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29649. objects[ firstActiveIndex ] = lastObject;
  29650. objects.pop();
  29651. // accounting is done, now do the same for all bindings
  29652. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29653. const bindingsForPath = bindings[ j ],
  29654. lastCached = bindingsForPath[ firstActiveIndex ],
  29655. last = bindingsForPath[ lastIndex ];
  29656. bindingsForPath[ index ] = lastCached;
  29657. bindingsForPath[ firstActiveIndex ] = last;
  29658. bindingsForPath.pop();
  29659. }
  29660. } else {
  29661. // object is active, just swap with the last and pop
  29662. const lastIndex = -- nObjects,
  29663. lastObject = objects[ lastIndex ];
  29664. if ( lastIndex > 0 ) {
  29665. indicesByUUID[ lastObject.uuid ] = index;
  29666. }
  29667. objects[ index ] = lastObject;
  29668. objects.pop();
  29669. // accounting is done, now do the same for all bindings
  29670. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29671. const bindingsForPath = bindings[ j ];
  29672. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29673. bindingsForPath.pop();
  29674. }
  29675. } // cached or active
  29676. } // if object is known
  29677. } // for arguments
  29678. this.nCachedObjects_ = nCachedObjects;
  29679. }
  29680. // Internal interface used by befriended PropertyBinding.Composite:
  29681. subscribe_( path, parsedPath ) {
  29682. // returns an array of bindings for the given path that is changed
  29683. // according to the contained objects in the group
  29684. const indicesByPath = this._bindingsIndicesByPath;
  29685. let index = indicesByPath[ path ];
  29686. const bindings = this._bindings;
  29687. if ( index !== undefined ) return bindings[ index ];
  29688. const paths = this._paths,
  29689. parsedPaths = this._parsedPaths,
  29690. objects = this._objects,
  29691. nObjects = objects.length,
  29692. nCachedObjects = this.nCachedObjects_,
  29693. bindingsForPath = new Array( nObjects );
  29694. index = bindings.length;
  29695. indicesByPath[ path ] = index;
  29696. paths.push( path );
  29697. parsedPaths.push( parsedPath );
  29698. bindings.push( bindingsForPath );
  29699. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29700. const object = objects[ i ];
  29701. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29702. }
  29703. return bindingsForPath;
  29704. }
  29705. unsubscribe_( path ) {
  29706. // tells the group to forget about a property path and no longer
  29707. // update the array previously obtained with 'subscribe_'
  29708. const indicesByPath = this._bindingsIndicesByPath,
  29709. index = indicesByPath[ path ];
  29710. if ( index !== undefined ) {
  29711. const paths = this._paths,
  29712. parsedPaths = this._parsedPaths,
  29713. bindings = this._bindings,
  29714. lastBindingsIndex = bindings.length - 1,
  29715. lastBindings = bindings[ lastBindingsIndex ],
  29716. lastBindingsPath = path[ lastBindingsIndex ];
  29717. indicesByPath[ lastBindingsPath ] = index;
  29718. bindings[ index ] = lastBindings;
  29719. bindings.pop();
  29720. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29721. parsedPaths.pop();
  29722. paths[ index ] = paths[ lastBindingsIndex ];
  29723. paths.pop();
  29724. }
  29725. }
  29726. }
  29727. class AnimationAction {
  29728. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29729. this._mixer = mixer;
  29730. this._clip = clip;
  29731. this._localRoot = localRoot;
  29732. this.blendMode = blendMode;
  29733. const tracks = clip.tracks,
  29734. nTracks = tracks.length,
  29735. interpolants = new Array( nTracks );
  29736. const interpolantSettings = {
  29737. endingStart: ZeroCurvatureEnding,
  29738. endingEnd: ZeroCurvatureEnding
  29739. };
  29740. for ( let i = 0; i !== nTracks; ++ i ) {
  29741. const interpolant = tracks[ i ].createInterpolant( null );
  29742. interpolants[ i ] = interpolant;
  29743. interpolant.settings = interpolantSettings;
  29744. }
  29745. this._interpolantSettings = interpolantSettings;
  29746. this._interpolants = interpolants; // bound by the mixer
  29747. // inside: PropertyMixer (managed by the mixer)
  29748. this._propertyBindings = new Array( nTracks );
  29749. this._cacheIndex = null; // for the memory manager
  29750. this._byClipCacheIndex = null; // for the memory manager
  29751. this._timeScaleInterpolant = null;
  29752. this._weightInterpolant = null;
  29753. this.loop = LoopRepeat;
  29754. this._loopCount = -1;
  29755. // global mixer time when the action is to be started
  29756. // it's set back to 'null' upon start of the action
  29757. this._startTime = null;
  29758. // scaled local time of the action
  29759. // gets clamped or wrapped to 0..clip.duration according to loop
  29760. this.time = 0;
  29761. this.timeScale = 1;
  29762. this._effectiveTimeScale = 1;
  29763. this.weight = 1;
  29764. this._effectiveWeight = 1;
  29765. this.repetitions = Infinity; // no. of repetitions when looping
  29766. this.paused = false; // true -> zero effective time scale
  29767. this.enabled = true; // false -> zero effective weight
  29768. this.clampWhenFinished = false;// keep feeding the last frame?
  29769. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29770. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29771. }
  29772. // State & Scheduling
  29773. play() {
  29774. this._mixer._activateAction( this );
  29775. return this;
  29776. }
  29777. stop() {
  29778. this._mixer._deactivateAction( this );
  29779. return this.reset();
  29780. }
  29781. reset() {
  29782. this.paused = false;
  29783. this.enabled = true;
  29784. this.time = 0; // restart clip
  29785. this._loopCount = -1;// forget previous loops
  29786. this._startTime = null;// forget scheduling
  29787. return this.stopFading().stopWarping();
  29788. }
  29789. isRunning() {
  29790. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29791. this._startTime === null && this._mixer._isActiveAction( this );
  29792. }
  29793. // return true when play has been called
  29794. isScheduled() {
  29795. return this._mixer._isActiveAction( this );
  29796. }
  29797. startAt( time ) {
  29798. this._startTime = time;
  29799. return this;
  29800. }
  29801. setLoop( mode, repetitions ) {
  29802. this.loop = mode;
  29803. this.repetitions = repetitions;
  29804. return this;
  29805. }
  29806. // Weight
  29807. // set the weight stopping any scheduled fading
  29808. // although .enabled = false yields an effective weight of zero, this
  29809. // method does *not* change .enabled, because it would be confusing
  29810. setEffectiveWeight( weight ) {
  29811. this.weight = weight;
  29812. // note: same logic as when updated at runtime
  29813. this._effectiveWeight = this.enabled ? weight : 0;
  29814. return this.stopFading();
  29815. }
  29816. // return the weight considering fading and .enabled
  29817. getEffectiveWeight() {
  29818. return this._effectiveWeight;
  29819. }
  29820. fadeIn( duration ) {
  29821. return this._scheduleFading( duration, 0, 1 );
  29822. }
  29823. fadeOut( duration ) {
  29824. return this._scheduleFading( duration, 1, 0 );
  29825. }
  29826. crossFadeFrom( fadeOutAction, duration, warp ) {
  29827. fadeOutAction.fadeOut( duration );
  29828. this.fadeIn( duration );
  29829. if ( warp ) {
  29830. const fadeInDuration = this._clip.duration,
  29831. fadeOutDuration = fadeOutAction._clip.duration,
  29832. startEndRatio = fadeOutDuration / fadeInDuration,
  29833. endStartRatio = fadeInDuration / fadeOutDuration;
  29834. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29835. this.warp( endStartRatio, 1.0, duration );
  29836. }
  29837. return this;
  29838. }
  29839. crossFadeTo( fadeInAction, duration, warp ) {
  29840. return fadeInAction.crossFadeFrom( this, duration, warp );
  29841. }
  29842. stopFading() {
  29843. const weightInterpolant = this._weightInterpolant;
  29844. if ( weightInterpolant !== null ) {
  29845. this._weightInterpolant = null;
  29846. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29847. }
  29848. return this;
  29849. }
  29850. // Time Scale Control
  29851. // set the time scale stopping any scheduled warping
  29852. // although .paused = true yields an effective time scale of zero, this
  29853. // method does *not* change .paused, because it would be confusing
  29854. setEffectiveTimeScale( timeScale ) {
  29855. this.timeScale = timeScale;
  29856. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29857. return this.stopWarping();
  29858. }
  29859. // return the time scale considering warping and .paused
  29860. getEffectiveTimeScale() {
  29861. return this._effectiveTimeScale;
  29862. }
  29863. setDuration( duration ) {
  29864. this.timeScale = this._clip.duration / duration;
  29865. return this.stopWarping();
  29866. }
  29867. syncWith( action ) {
  29868. this.time = action.time;
  29869. this.timeScale = action.timeScale;
  29870. return this.stopWarping();
  29871. }
  29872. halt( duration ) {
  29873. return this.warp( this._effectiveTimeScale, 0, duration );
  29874. }
  29875. warp( startTimeScale, endTimeScale, duration ) {
  29876. const mixer = this._mixer,
  29877. now = mixer.time,
  29878. timeScale = this.timeScale;
  29879. let interpolant = this._timeScaleInterpolant;
  29880. if ( interpolant === null ) {
  29881. interpolant = mixer._lendControlInterpolant();
  29882. this._timeScaleInterpolant = interpolant;
  29883. }
  29884. const times = interpolant.parameterPositions,
  29885. values = interpolant.sampleValues;
  29886. times[ 0 ] = now;
  29887. times[ 1 ] = now + duration;
  29888. values[ 0 ] = startTimeScale / timeScale;
  29889. values[ 1 ] = endTimeScale / timeScale;
  29890. return this;
  29891. }
  29892. stopWarping() {
  29893. const timeScaleInterpolant = this._timeScaleInterpolant;
  29894. if ( timeScaleInterpolant !== null ) {
  29895. this._timeScaleInterpolant = null;
  29896. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29897. }
  29898. return this;
  29899. }
  29900. // Object Accessors
  29901. getMixer() {
  29902. return this._mixer;
  29903. }
  29904. getClip() {
  29905. return this._clip;
  29906. }
  29907. getRoot() {
  29908. return this._localRoot || this._mixer._root;
  29909. }
  29910. // Interna
  29911. _update( time, deltaTime, timeDirection, accuIndex ) {
  29912. // called by the mixer
  29913. if ( ! this.enabled ) {
  29914. // call ._updateWeight() to update ._effectiveWeight
  29915. this._updateWeight( time );
  29916. return;
  29917. }
  29918. const startTime = this._startTime;
  29919. if ( startTime !== null ) {
  29920. // check for scheduled start of action
  29921. const timeRunning = ( time - startTime ) * timeDirection;
  29922. if ( timeRunning < 0 || timeDirection === 0 ) {
  29923. deltaTime = 0;
  29924. } else {
  29925. this._startTime = null; // unschedule
  29926. deltaTime = timeDirection * timeRunning;
  29927. }
  29928. }
  29929. // apply time scale and advance time
  29930. deltaTime *= this._updateTimeScale( time );
  29931. const clipTime = this._updateTime( deltaTime );
  29932. // note: _updateTime may disable the action resulting in
  29933. // an effective weight of 0
  29934. const weight = this._updateWeight( time );
  29935. if ( weight > 0 ) {
  29936. const interpolants = this._interpolants;
  29937. const propertyMixers = this._propertyBindings;
  29938. switch ( this.blendMode ) {
  29939. case AdditiveAnimationBlendMode:
  29940. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29941. interpolants[ j ].evaluate( clipTime );
  29942. propertyMixers[ j ].accumulateAdditive( weight );
  29943. }
  29944. break;
  29945. case NormalAnimationBlendMode:
  29946. default:
  29947. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29948. interpolants[ j ].evaluate( clipTime );
  29949. propertyMixers[ j ].accumulate( accuIndex, weight );
  29950. }
  29951. }
  29952. }
  29953. }
  29954. _updateWeight( time ) {
  29955. let weight = 0;
  29956. if ( this.enabled ) {
  29957. weight = this.weight;
  29958. const interpolant = this._weightInterpolant;
  29959. if ( interpolant !== null ) {
  29960. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29961. weight *= interpolantValue;
  29962. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29963. this.stopFading();
  29964. if ( interpolantValue === 0 ) {
  29965. // faded out, disable
  29966. this.enabled = false;
  29967. }
  29968. }
  29969. }
  29970. }
  29971. this._effectiveWeight = weight;
  29972. return weight;
  29973. }
  29974. _updateTimeScale( time ) {
  29975. let timeScale = 0;
  29976. if ( ! this.paused ) {
  29977. timeScale = this.timeScale;
  29978. const interpolant = this._timeScaleInterpolant;
  29979. if ( interpolant !== null ) {
  29980. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29981. timeScale *= interpolantValue;
  29982. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29983. this.stopWarping();
  29984. if ( timeScale === 0 ) {
  29985. // motion has halted, pause
  29986. this.paused = true;
  29987. } else {
  29988. // warp done - apply final time scale
  29989. this.timeScale = timeScale;
  29990. }
  29991. }
  29992. }
  29993. }
  29994. this._effectiveTimeScale = timeScale;
  29995. return timeScale;
  29996. }
  29997. _updateTime( deltaTime ) {
  29998. const duration = this._clip.duration;
  29999. const loop = this.loop;
  30000. let time = this.time + deltaTime;
  30001. let loopCount = this._loopCount;
  30002. const pingPong = ( loop === LoopPingPong );
  30003. if ( deltaTime === 0 ) {
  30004. if ( loopCount === -1 ) return time;
  30005. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  30006. }
  30007. if ( loop === LoopOnce ) {
  30008. if ( loopCount === -1 ) {
  30009. // just started
  30010. this._loopCount = 0;
  30011. this._setEndings( true, true, false );
  30012. }
  30013. handle_stop: {
  30014. if ( time >= duration ) {
  30015. time = duration;
  30016. } else if ( time < 0 ) {
  30017. time = 0;
  30018. } else {
  30019. this.time = time;
  30020. break handle_stop;
  30021. }
  30022. if ( this.clampWhenFinished ) this.paused = true;
  30023. else this.enabled = false;
  30024. this.time = time;
  30025. this._mixer.dispatchEvent( {
  30026. type: 'finished', action: this,
  30027. direction: deltaTime < 0 ? -1 : 1
  30028. } );
  30029. }
  30030. } else { // repetitive Repeat or PingPong
  30031. if ( loopCount === -1 ) {
  30032. // just started
  30033. if ( deltaTime >= 0 ) {
  30034. loopCount = 0;
  30035. this._setEndings( true, this.repetitions === 0, pingPong );
  30036. } else {
  30037. // when looping in reverse direction, the initial
  30038. // transition through zero counts as a repetition,
  30039. // so leave loopCount at -1
  30040. this._setEndings( this.repetitions === 0, true, pingPong );
  30041. }
  30042. }
  30043. if ( time >= duration || time < 0 ) {
  30044. // wrap around
  30045. const loopDelta = Math.floor( time / duration ); // signed
  30046. time -= duration * loopDelta;
  30047. loopCount += Math.abs( loopDelta );
  30048. const pending = this.repetitions - loopCount;
  30049. if ( pending <= 0 ) {
  30050. // have to stop (switch state, clamp time, fire event)
  30051. if ( this.clampWhenFinished ) this.paused = true;
  30052. else this.enabled = false;
  30053. time = deltaTime > 0 ? duration : 0;
  30054. this.time = time;
  30055. this._mixer.dispatchEvent( {
  30056. type: 'finished', action: this,
  30057. direction: deltaTime > 0 ? 1 : -1
  30058. } );
  30059. } else {
  30060. // keep running
  30061. if ( pending === 1 ) {
  30062. // entering the last round
  30063. const atStart = deltaTime < 0;
  30064. this._setEndings( atStart, ! atStart, pingPong );
  30065. } else {
  30066. this._setEndings( false, false, pingPong );
  30067. }
  30068. this._loopCount = loopCount;
  30069. this.time = time;
  30070. this._mixer.dispatchEvent( {
  30071. type: 'loop', action: this, loopDelta: loopDelta
  30072. } );
  30073. }
  30074. } else {
  30075. this.time = time;
  30076. }
  30077. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  30078. // invert time for the "pong round"
  30079. return duration - time;
  30080. }
  30081. }
  30082. return time;
  30083. }
  30084. _setEndings( atStart, atEnd, pingPong ) {
  30085. const settings = this._interpolantSettings;
  30086. if ( pingPong ) {
  30087. settings.endingStart = ZeroSlopeEnding;
  30088. settings.endingEnd = ZeroSlopeEnding;
  30089. } else {
  30090. // assuming for LoopOnce atStart == atEnd == true
  30091. if ( atStart ) {
  30092. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30093. } else {
  30094. settings.endingStart = WrapAroundEnding;
  30095. }
  30096. if ( atEnd ) {
  30097. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  30098. } else {
  30099. settings.endingEnd = WrapAroundEnding;
  30100. }
  30101. }
  30102. }
  30103. _scheduleFading( duration, weightNow, weightThen ) {
  30104. const mixer = this._mixer, now = mixer.time;
  30105. let interpolant = this._weightInterpolant;
  30106. if ( interpolant === null ) {
  30107. interpolant = mixer._lendControlInterpolant();
  30108. this._weightInterpolant = interpolant;
  30109. }
  30110. const times = interpolant.parameterPositions,
  30111. values = interpolant.sampleValues;
  30112. times[ 0 ] = now;
  30113. values[ 0 ] = weightNow;
  30114. times[ 1 ] = now + duration;
  30115. values[ 1 ] = weightThen;
  30116. return this;
  30117. }
  30118. }
  30119. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  30120. class AnimationMixer extends EventDispatcher {
  30121. constructor( root ) {
  30122. super();
  30123. this._root = root;
  30124. this._initMemoryManager();
  30125. this._accuIndex = 0;
  30126. this.time = 0;
  30127. this.timeScale = 1.0;
  30128. }
  30129. _bindAction( action, prototypeAction ) {
  30130. const root = action._localRoot || this._root,
  30131. tracks = action._clip.tracks,
  30132. nTracks = tracks.length,
  30133. bindings = action._propertyBindings,
  30134. interpolants = action._interpolants,
  30135. rootUuid = root.uuid,
  30136. bindingsByRoot = this._bindingsByRootAndName;
  30137. let bindingsByName = bindingsByRoot[ rootUuid ];
  30138. if ( bindingsByName === undefined ) {
  30139. bindingsByName = {};
  30140. bindingsByRoot[ rootUuid ] = bindingsByName;
  30141. }
  30142. for ( let i = 0; i !== nTracks; ++ i ) {
  30143. const track = tracks[ i ],
  30144. trackName = track.name;
  30145. let binding = bindingsByName[ trackName ];
  30146. if ( binding !== undefined ) {
  30147. ++ binding.referenceCount;
  30148. bindings[ i ] = binding;
  30149. } else {
  30150. binding = bindings[ i ];
  30151. if ( binding !== undefined ) {
  30152. // existing binding, make sure the cache knows
  30153. if ( binding._cacheIndex === null ) {
  30154. ++ binding.referenceCount;
  30155. this._addInactiveBinding( binding, rootUuid, trackName );
  30156. }
  30157. continue;
  30158. }
  30159. const path = prototypeAction && prototypeAction.
  30160. _propertyBindings[ i ].binding.parsedPath;
  30161. binding = new PropertyMixer(
  30162. PropertyBinding.create( root, trackName, path ),
  30163. track.ValueTypeName, track.getValueSize() );
  30164. ++ binding.referenceCount;
  30165. this._addInactiveBinding( binding, rootUuid, trackName );
  30166. bindings[ i ] = binding;
  30167. }
  30168. interpolants[ i ].resultBuffer = binding.buffer;
  30169. }
  30170. }
  30171. _activateAction( action ) {
  30172. if ( ! this._isActiveAction( action ) ) {
  30173. if ( action._cacheIndex === null ) {
  30174. // this action has been forgotten by the cache, but the user
  30175. // appears to be still using it -> rebind
  30176. const rootUuid = ( action._localRoot || this._root ).uuid,
  30177. clipUuid = action._clip.uuid,
  30178. actionsForClip = this._actionsByClip[ clipUuid ];
  30179. this._bindAction( action,
  30180. actionsForClip && actionsForClip.knownActions[ 0 ] );
  30181. this._addInactiveAction( action, clipUuid, rootUuid );
  30182. }
  30183. const bindings = action._propertyBindings;
  30184. // increment reference counts / sort out state
  30185. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30186. const binding = bindings[ i ];
  30187. if ( binding.useCount ++ === 0 ) {
  30188. this._lendBinding( binding );
  30189. binding.saveOriginalState();
  30190. }
  30191. }
  30192. this._lendAction( action );
  30193. }
  30194. }
  30195. _deactivateAction( action ) {
  30196. if ( this._isActiveAction( action ) ) {
  30197. const bindings = action._propertyBindings;
  30198. // decrement reference counts / sort out state
  30199. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30200. const binding = bindings[ i ];
  30201. if ( -- binding.useCount === 0 ) {
  30202. binding.restoreOriginalState();
  30203. this._takeBackBinding( binding );
  30204. }
  30205. }
  30206. this._takeBackAction( action );
  30207. }
  30208. }
  30209. // Memory manager
  30210. _initMemoryManager() {
  30211. this._actions = []; // 'nActiveActions' followed by inactive ones
  30212. this._nActiveActions = 0;
  30213. this._actionsByClip = {};
  30214. // inside:
  30215. // {
  30216. // knownActions: Array< AnimationAction > - used as prototypes
  30217. // actionByRoot: AnimationAction - lookup
  30218. // }
  30219. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  30220. this._nActiveBindings = 0;
  30221. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  30222. this._controlInterpolants = []; // same game as above
  30223. this._nActiveControlInterpolants = 0;
  30224. const scope = this;
  30225. this.stats = {
  30226. actions: {
  30227. get total() {
  30228. return scope._actions.length;
  30229. },
  30230. get inUse() {
  30231. return scope._nActiveActions;
  30232. }
  30233. },
  30234. bindings: {
  30235. get total() {
  30236. return scope._bindings.length;
  30237. },
  30238. get inUse() {
  30239. return scope._nActiveBindings;
  30240. }
  30241. },
  30242. controlInterpolants: {
  30243. get total() {
  30244. return scope._controlInterpolants.length;
  30245. },
  30246. get inUse() {
  30247. return scope._nActiveControlInterpolants;
  30248. }
  30249. }
  30250. };
  30251. }
  30252. // Memory management for AnimationAction objects
  30253. _isActiveAction( action ) {
  30254. const index = action._cacheIndex;
  30255. return index !== null && index < this._nActiveActions;
  30256. }
  30257. _addInactiveAction( action, clipUuid, rootUuid ) {
  30258. const actions = this._actions,
  30259. actionsByClip = this._actionsByClip;
  30260. let actionsForClip = actionsByClip[ clipUuid ];
  30261. if ( actionsForClip === undefined ) {
  30262. actionsForClip = {
  30263. knownActions: [ action ],
  30264. actionByRoot: {}
  30265. };
  30266. action._byClipCacheIndex = 0;
  30267. actionsByClip[ clipUuid ] = actionsForClip;
  30268. } else {
  30269. const knownActions = actionsForClip.knownActions;
  30270. action._byClipCacheIndex = knownActions.length;
  30271. knownActions.push( action );
  30272. }
  30273. action._cacheIndex = actions.length;
  30274. actions.push( action );
  30275. actionsForClip.actionByRoot[ rootUuid ] = action;
  30276. }
  30277. _removeInactiveAction( action ) {
  30278. const actions = this._actions,
  30279. lastInactiveAction = actions[ actions.length - 1 ],
  30280. cacheIndex = action._cacheIndex;
  30281. lastInactiveAction._cacheIndex = cacheIndex;
  30282. actions[ cacheIndex ] = lastInactiveAction;
  30283. actions.pop();
  30284. action._cacheIndex = null;
  30285. const clipUuid = action._clip.uuid,
  30286. actionsByClip = this._actionsByClip,
  30287. actionsForClip = actionsByClip[ clipUuid ],
  30288. knownActionsForClip = actionsForClip.knownActions,
  30289. lastKnownAction =
  30290. knownActionsForClip[ knownActionsForClip.length - 1 ],
  30291. byClipCacheIndex = action._byClipCacheIndex;
  30292. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  30293. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  30294. knownActionsForClip.pop();
  30295. action._byClipCacheIndex = null;
  30296. const actionByRoot = actionsForClip.actionByRoot,
  30297. rootUuid = ( action._localRoot || this._root ).uuid;
  30298. delete actionByRoot[ rootUuid ];
  30299. if ( knownActionsForClip.length === 0 ) {
  30300. delete actionsByClip[ clipUuid ];
  30301. }
  30302. this._removeInactiveBindingsForAction( action );
  30303. }
  30304. _removeInactiveBindingsForAction( action ) {
  30305. const bindings = action._propertyBindings;
  30306. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30307. const binding = bindings[ i ];
  30308. if ( -- binding.referenceCount === 0 ) {
  30309. this._removeInactiveBinding( binding );
  30310. }
  30311. }
  30312. }
  30313. _lendAction( action ) {
  30314. // [ active actions | inactive actions ]
  30315. // [ active actions >| inactive actions ]
  30316. // s a
  30317. // <-swap->
  30318. // a s
  30319. const actions = this._actions,
  30320. prevIndex = action._cacheIndex,
  30321. lastActiveIndex = this._nActiveActions ++,
  30322. firstInactiveAction = actions[ lastActiveIndex ];
  30323. action._cacheIndex = lastActiveIndex;
  30324. actions[ lastActiveIndex ] = action;
  30325. firstInactiveAction._cacheIndex = prevIndex;
  30326. actions[ prevIndex ] = firstInactiveAction;
  30327. }
  30328. _takeBackAction( action ) {
  30329. // [ active actions | inactive actions ]
  30330. // [ active actions |< inactive actions ]
  30331. // a s
  30332. // <-swap->
  30333. // s a
  30334. const actions = this._actions,
  30335. prevIndex = action._cacheIndex,
  30336. firstInactiveIndex = -- this._nActiveActions,
  30337. lastActiveAction = actions[ firstInactiveIndex ];
  30338. action._cacheIndex = firstInactiveIndex;
  30339. actions[ firstInactiveIndex ] = action;
  30340. lastActiveAction._cacheIndex = prevIndex;
  30341. actions[ prevIndex ] = lastActiveAction;
  30342. }
  30343. // Memory management for PropertyMixer objects
  30344. _addInactiveBinding( binding, rootUuid, trackName ) {
  30345. const bindingsByRoot = this._bindingsByRootAndName,
  30346. bindings = this._bindings;
  30347. let bindingByName = bindingsByRoot[ rootUuid ];
  30348. if ( bindingByName === undefined ) {
  30349. bindingByName = {};
  30350. bindingsByRoot[ rootUuid ] = bindingByName;
  30351. }
  30352. bindingByName[ trackName ] = binding;
  30353. binding._cacheIndex = bindings.length;
  30354. bindings.push( binding );
  30355. }
  30356. _removeInactiveBinding( binding ) {
  30357. const bindings = this._bindings,
  30358. propBinding = binding.binding,
  30359. rootUuid = propBinding.rootNode.uuid,
  30360. trackName = propBinding.path,
  30361. bindingsByRoot = this._bindingsByRootAndName,
  30362. bindingByName = bindingsByRoot[ rootUuid ],
  30363. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30364. cacheIndex = binding._cacheIndex;
  30365. lastInactiveBinding._cacheIndex = cacheIndex;
  30366. bindings[ cacheIndex ] = lastInactiveBinding;
  30367. bindings.pop();
  30368. delete bindingByName[ trackName ];
  30369. if ( Object.keys( bindingByName ).length === 0 ) {
  30370. delete bindingsByRoot[ rootUuid ];
  30371. }
  30372. }
  30373. _lendBinding( binding ) {
  30374. const bindings = this._bindings,
  30375. prevIndex = binding._cacheIndex,
  30376. lastActiveIndex = this._nActiveBindings ++,
  30377. firstInactiveBinding = bindings[ lastActiveIndex ];
  30378. binding._cacheIndex = lastActiveIndex;
  30379. bindings[ lastActiveIndex ] = binding;
  30380. firstInactiveBinding._cacheIndex = prevIndex;
  30381. bindings[ prevIndex ] = firstInactiveBinding;
  30382. }
  30383. _takeBackBinding( binding ) {
  30384. const bindings = this._bindings,
  30385. prevIndex = binding._cacheIndex,
  30386. firstInactiveIndex = -- this._nActiveBindings,
  30387. lastActiveBinding = bindings[ firstInactiveIndex ];
  30388. binding._cacheIndex = firstInactiveIndex;
  30389. bindings[ firstInactiveIndex ] = binding;
  30390. lastActiveBinding._cacheIndex = prevIndex;
  30391. bindings[ prevIndex ] = lastActiveBinding;
  30392. }
  30393. // Memory management of Interpolants for weight and time scale
  30394. _lendControlInterpolant() {
  30395. const interpolants = this._controlInterpolants,
  30396. lastActiveIndex = this._nActiveControlInterpolants ++;
  30397. let interpolant = interpolants[ lastActiveIndex ];
  30398. if ( interpolant === undefined ) {
  30399. interpolant = new LinearInterpolant(
  30400. new Float32Array( 2 ), new Float32Array( 2 ),
  30401. 1, _controlInterpolantsResultBuffer );
  30402. interpolant.__cacheIndex = lastActiveIndex;
  30403. interpolants[ lastActiveIndex ] = interpolant;
  30404. }
  30405. return interpolant;
  30406. }
  30407. _takeBackControlInterpolant( interpolant ) {
  30408. const interpolants = this._controlInterpolants,
  30409. prevIndex = interpolant.__cacheIndex,
  30410. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30411. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30412. interpolant.__cacheIndex = firstInactiveIndex;
  30413. interpolants[ firstInactiveIndex ] = interpolant;
  30414. lastActiveInterpolant.__cacheIndex = prevIndex;
  30415. interpolants[ prevIndex ] = lastActiveInterpolant;
  30416. }
  30417. // return an action for a clip optionally using a custom root target
  30418. // object (this method allocates a lot of dynamic memory in case a
  30419. // previously unknown clip/root combination is specified)
  30420. clipAction( clip, optionalRoot, blendMode ) {
  30421. const root = optionalRoot || this._root,
  30422. rootUuid = root.uuid;
  30423. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  30424. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  30425. const actionsForClip = this._actionsByClip[ clipUuid ];
  30426. let prototypeAction = null;
  30427. if ( blendMode === undefined ) {
  30428. if ( clipObject !== null ) {
  30429. blendMode = clipObject.blendMode;
  30430. } else {
  30431. blendMode = NormalAnimationBlendMode;
  30432. }
  30433. }
  30434. if ( actionsForClip !== undefined ) {
  30435. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  30436. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  30437. return existingAction;
  30438. }
  30439. // we know the clip, so we don't have to parse all
  30440. // the bindings again but can just copy
  30441. prototypeAction = actionsForClip.knownActions[ 0 ];
  30442. // also, take the clip from the prototype action
  30443. if ( clipObject === null )
  30444. clipObject = prototypeAction._clip;
  30445. }
  30446. // clip must be known when specified via string
  30447. if ( clipObject === null ) return null;
  30448. // allocate all resources required to run it
  30449. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  30450. this._bindAction( newAction, prototypeAction );
  30451. // and make the action known to the memory manager
  30452. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30453. return newAction;
  30454. }
  30455. // get an existing action
  30456. existingAction( clip, optionalRoot ) {
  30457. const root = optionalRoot || this._root,
  30458. rootUuid = root.uuid,
  30459. clipObject = typeof clip === 'string' ?
  30460. AnimationClip.findByName( root, clip ) : clip,
  30461. clipUuid = clipObject ? clipObject.uuid : clip,
  30462. actionsForClip = this._actionsByClip[ clipUuid ];
  30463. if ( actionsForClip !== undefined ) {
  30464. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30465. }
  30466. return null;
  30467. }
  30468. // deactivates all previously scheduled actions
  30469. stopAllAction() {
  30470. const actions = this._actions,
  30471. nActions = this._nActiveActions;
  30472. for ( let i = nActions - 1; i >= 0; -- i ) {
  30473. actions[ i ].stop();
  30474. }
  30475. return this;
  30476. }
  30477. // advance the time and update apply the animation
  30478. update( deltaTime ) {
  30479. deltaTime *= this.timeScale;
  30480. const actions = this._actions,
  30481. nActions = this._nActiveActions,
  30482. time = this.time += deltaTime,
  30483. timeDirection = Math.sign( deltaTime ),
  30484. accuIndex = this._accuIndex ^= 1;
  30485. // run active actions
  30486. for ( let i = 0; i !== nActions; ++ i ) {
  30487. const action = actions[ i ];
  30488. action._update( time, deltaTime, timeDirection, accuIndex );
  30489. }
  30490. // update scene graph
  30491. const bindings = this._bindings,
  30492. nBindings = this._nActiveBindings;
  30493. for ( let i = 0; i !== nBindings; ++ i ) {
  30494. bindings[ i ].apply( accuIndex );
  30495. }
  30496. return this;
  30497. }
  30498. // Allows you to seek to a specific time in an animation.
  30499. setTime( timeInSeconds ) {
  30500. this.time = 0; // Zero out time attribute for AnimationMixer object;
  30501. for ( let i = 0; i < this._actions.length; i ++ ) {
  30502. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  30503. }
  30504. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  30505. }
  30506. // return this mixer's root target object
  30507. getRoot() {
  30508. return this._root;
  30509. }
  30510. // free all resources specific to a particular clip
  30511. uncacheClip( clip ) {
  30512. const actions = this._actions,
  30513. clipUuid = clip.uuid,
  30514. actionsByClip = this._actionsByClip,
  30515. actionsForClip = actionsByClip[ clipUuid ];
  30516. if ( actionsForClip !== undefined ) {
  30517. // note: just calling _removeInactiveAction would mess up the
  30518. // iteration state and also require updating the state we can
  30519. // just throw away
  30520. const actionsToRemove = actionsForClip.knownActions;
  30521. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30522. const action = actionsToRemove[ i ];
  30523. this._deactivateAction( action );
  30524. const cacheIndex = action._cacheIndex,
  30525. lastInactiveAction = actions[ actions.length - 1 ];
  30526. action._cacheIndex = null;
  30527. action._byClipCacheIndex = null;
  30528. lastInactiveAction._cacheIndex = cacheIndex;
  30529. actions[ cacheIndex ] = lastInactiveAction;
  30530. actions.pop();
  30531. this._removeInactiveBindingsForAction( action );
  30532. }
  30533. delete actionsByClip[ clipUuid ];
  30534. }
  30535. }
  30536. // free all resources specific to a particular root target object
  30537. uncacheRoot( root ) {
  30538. const rootUuid = root.uuid,
  30539. actionsByClip = this._actionsByClip;
  30540. for ( const clipUuid in actionsByClip ) {
  30541. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30542. action = actionByRoot[ rootUuid ];
  30543. if ( action !== undefined ) {
  30544. this._deactivateAction( action );
  30545. this._removeInactiveAction( action );
  30546. }
  30547. }
  30548. const bindingsByRoot = this._bindingsByRootAndName,
  30549. bindingByName = bindingsByRoot[ rootUuid ];
  30550. if ( bindingByName !== undefined ) {
  30551. for ( const trackName in bindingByName ) {
  30552. const binding = bindingByName[ trackName ];
  30553. binding.restoreOriginalState();
  30554. this._removeInactiveBinding( binding );
  30555. }
  30556. }
  30557. }
  30558. // remove a targeted clip from the cache
  30559. uncacheAction( clip, optionalRoot ) {
  30560. const action = this.existingAction( clip, optionalRoot );
  30561. if ( action !== null ) {
  30562. this._deactivateAction( action );
  30563. this._removeInactiveAction( action );
  30564. }
  30565. }
  30566. }
  30567. class RenderTarget3D extends RenderTarget {
  30568. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  30569. super( width, height, options );
  30570. this.isRenderTarget3D = true;
  30571. this.depth = depth;
  30572. this.texture = new Data3DTexture( null, width, height, depth );
  30573. this.texture.isRenderTargetTexture = true;
  30574. }
  30575. }
  30576. class RenderTargetArray extends RenderTarget {
  30577. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  30578. super( width, height, options );
  30579. this.isRenderTargetArray = true;
  30580. this.depth = depth;
  30581. this.texture = new DataArrayTexture( null, width, height, depth );
  30582. this.texture.isRenderTargetTexture = true;
  30583. }
  30584. }
  30585. class Uniform {
  30586. constructor( value ) {
  30587. this.value = value;
  30588. }
  30589. clone() {
  30590. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30591. }
  30592. }
  30593. let _id = 0;
  30594. class UniformsGroup extends EventDispatcher {
  30595. constructor() {
  30596. super();
  30597. this.isUniformsGroup = true;
  30598. Object.defineProperty( this, 'id', { value: _id ++ } );
  30599. this.name = '';
  30600. this.usage = StaticDrawUsage;
  30601. this.uniforms = [];
  30602. }
  30603. add( uniform ) {
  30604. this.uniforms.push( uniform );
  30605. return this;
  30606. }
  30607. remove( uniform ) {
  30608. const index = this.uniforms.indexOf( uniform );
  30609. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  30610. return this;
  30611. }
  30612. setName( name ) {
  30613. this.name = name;
  30614. return this;
  30615. }
  30616. setUsage( value ) {
  30617. this.usage = value;
  30618. return this;
  30619. }
  30620. dispose() {
  30621. this.dispatchEvent( { type: 'dispose' } );
  30622. return this;
  30623. }
  30624. copy( source ) {
  30625. this.name = source.name;
  30626. this.usage = source.usage;
  30627. const uniformsSource = source.uniforms;
  30628. this.uniforms.length = 0;
  30629. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30630. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30631. for ( let j = 0; j < uniforms.length; j ++ ) {
  30632. this.uniforms.push( uniforms[ j ].clone() );
  30633. }
  30634. }
  30635. return this;
  30636. }
  30637. clone() {
  30638. return new this.constructor().copy( this );
  30639. }
  30640. }
  30641. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30642. constructor( array, stride, meshPerAttribute = 1 ) {
  30643. super( array, stride );
  30644. this.isInstancedInterleavedBuffer = true;
  30645. this.meshPerAttribute = meshPerAttribute;
  30646. }
  30647. copy( source ) {
  30648. super.copy( source );
  30649. this.meshPerAttribute = source.meshPerAttribute;
  30650. return this;
  30651. }
  30652. clone( data ) {
  30653. const ib = super.clone( data );
  30654. ib.meshPerAttribute = this.meshPerAttribute;
  30655. return ib;
  30656. }
  30657. toJSON( data ) {
  30658. const json = super.toJSON( data );
  30659. json.isInstancedInterleavedBuffer = true;
  30660. json.meshPerAttribute = this.meshPerAttribute;
  30661. return json;
  30662. }
  30663. }
  30664. class GLBufferAttribute {
  30665. constructor( buffer, type, itemSize, elementSize, count ) {
  30666. this.isGLBufferAttribute = true;
  30667. this.name = '';
  30668. this.buffer = buffer;
  30669. this.type = type;
  30670. this.itemSize = itemSize;
  30671. this.elementSize = elementSize;
  30672. this.count = count;
  30673. this.version = 0;
  30674. }
  30675. set needsUpdate( value ) {
  30676. if ( value === true ) this.version ++;
  30677. }
  30678. setBuffer( buffer ) {
  30679. this.buffer = buffer;
  30680. return this;
  30681. }
  30682. setType( type, elementSize ) {
  30683. this.type = type;
  30684. this.elementSize = elementSize;
  30685. return this;
  30686. }
  30687. setItemSize( itemSize ) {
  30688. this.itemSize = itemSize;
  30689. return this;
  30690. }
  30691. setCount( count ) {
  30692. this.count = count;
  30693. return this;
  30694. }
  30695. }
  30696. const _matrix = /*@__PURE__*/ new Matrix4();
  30697. class Raycaster {
  30698. constructor( origin, direction, near = 0, far = Infinity ) {
  30699. this.ray = new Ray( origin, direction );
  30700. // direction is assumed to be normalized (for accurate distance calculations)
  30701. this.near = near;
  30702. this.far = far;
  30703. this.camera = null;
  30704. this.layers = new Layers();
  30705. this.params = {
  30706. Mesh: {},
  30707. Line: { threshold: 1 },
  30708. LOD: {},
  30709. Points: { threshold: 1 },
  30710. Sprite: {}
  30711. };
  30712. }
  30713. set( origin, direction ) {
  30714. // direction is assumed to be normalized (for accurate distance calculations)
  30715. this.ray.set( origin, direction );
  30716. }
  30717. setFromCamera( coords, camera ) {
  30718. if ( camera.isPerspectiveCamera ) {
  30719. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30720. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30721. this.camera = camera;
  30722. } else if ( camera.isOrthographicCamera ) {
  30723. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30724. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  30725. this.camera = camera;
  30726. } else {
  30727. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30728. }
  30729. }
  30730. setFromXRController( controller ) {
  30731. _matrix.identity().extractRotation( controller.matrixWorld );
  30732. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30733. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  30734. return this;
  30735. }
  30736. intersectObject( object, recursive = true, intersects = [] ) {
  30737. intersect( object, this, intersects, recursive );
  30738. intersects.sort( ascSort );
  30739. return intersects;
  30740. }
  30741. intersectObjects( objects, recursive = true, intersects = [] ) {
  30742. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30743. intersect( objects[ i ], this, intersects, recursive );
  30744. }
  30745. intersects.sort( ascSort );
  30746. return intersects;
  30747. }
  30748. }
  30749. function ascSort( a, b ) {
  30750. return a.distance - b.distance;
  30751. }
  30752. function intersect( object, raycaster, intersects, recursive ) {
  30753. let propagate = true;
  30754. if ( object.layers.test( raycaster.layers ) ) {
  30755. const result = object.raycast( raycaster, intersects );
  30756. if ( result === false ) propagate = false;
  30757. }
  30758. if ( propagate === true && recursive === true ) {
  30759. const children = object.children;
  30760. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30761. intersect( children[ i ], raycaster, intersects, true );
  30762. }
  30763. }
  30764. }
  30765. /**
  30766. * This class can be used to represent points in 3D space as
  30767. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  30768. */
  30769. class Spherical {
  30770. /**
  30771. * Constructs a new spherical.
  30772. *
  30773. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  30774. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  30775. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  30776. */
  30777. constructor( radius = 1, phi = 0, theta = 0 ) {
  30778. /**
  30779. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  30780. *
  30781. * @type {number}
  30782. * @default 1
  30783. */
  30784. this.radius = radius;
  30785. /**
  30786. * The polar angle in radians from the y (up) axis.
  30787. *
  30788. * @type {number}
  30789. * @default 0
  30790. */
  30791. this.phi = phi;
  30792. /**
  30793. * The equator/azimuthal angle in radians around the y (up) axis.
  30794. *
  30795. * @type {number}
  30796. * @default 0
  30797. */
  30798. this.theta = theta;
  30799. }
  30800. /**
  30801. * Sets the spherical components by copying the given values.
  30802. *
  30803. * @param {number} radius - The radius.
  30804. * @param {number} phi - The polar angle.
  30805. * @param {number} theta - The azimuthal angle.
  30806. * @return {Spherical} A reference to this spherical.
  30807. */
  30808. set( radius, phi, theta ) {
  30809. this.radius = radius;
  30810. this.phi = phi;
  30811. this.theta = theta;
  30812. return this;
  30813. }
  30814. /**
  30815. * Copies the values of the given spherical to this instance.
  30816. *
  30817. * @param {Spherical} other - The spherical to copy.
  30818. * @return {Spherical} A reference to this spherical.
  30819. */
  30820. copy( other ) {
  30821. this.radius = other.radius;
  30822. this.phi = other.phi;
  30823. this.theta = other.theta;
  30824. return this;
  30825. }
  30826. /**
  30827. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  30828. * `0.000001`.
  30829. *
  30830. * @return {Spherical} A reference to this spherical.
  30831. */
  30832. makeSafe() {
  30833. const EPS = 0.000001;
  30834. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  30835. return this;
  30836. }
  30837. /**
  30838. * Sets the spherical components from the given vector which is assumed to hold
  30839. * Cartesian coordinates.
  30840. *
  30841. * @param {Vector3} v - The vector to set.
  30842. * @return {Spherical} A reference to this spherical.
  30843. */
  30844. setFromVector3( v ) {
  30845. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30846. }
  30847. /**
  30848. * Sets the spherical components from the given Cartesian coordinates.
  30849. *
  30850. * @param {number} x - The x value.
  30851. * @param {number} y - The x value.
  30852. * @param {number} z - The x value.
  30853. * @return {Spherical} A reference to this spherical.
  30854. */
  30855. setFromCartesianCoords( x, y, z ) {
  30856. this.radius = Math.sqrt( x * x + y * y + z * z );
  30857. if ( this.radius === 0 ) {
  30858. this.theta = 0;
  30859. this.phi = 0;
  30860. } else {
  30861. this.theta = Math.atan2( x, z );
  30862. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  30863. }
  30864. return this;
  30865. }
  30866. /**
  30867. * Returns a new spherical with copied values from this instance.
  30868. *
  30869. * @return {Spherical} A clone of this instance.
  30870. */
  30871. clone() {
  30872. return new this.constructor().copy( this );
  30873. }
  30874. }
  30875. /**
  30876. * This class can be used to represent points in 3D space as
  30877. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  30878. */
  30879. class Cylindrical {
  30880. /**
  30881. * Constructs a new cylindrical.
  30882. *
  30883. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  30884. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  30885. * @param {number} [y=0] - The height above the x-z plane.
  30886. */
  30887. constructor( radius = 1, theta = 0, y = 0 ) {
  30888. /**
  30889. * The distance from the origin to a point in the x-z plane.
  30890. *
  30891. * @type {number}
  30892. * @default 1
  30893. */
  30894. this.radius = radius;
  30895. /**
  30896. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  30897. *
  30898. * @type {number}
  30899. * @default 0
  30900. */
  30901. this.theta = theta;
  30902. /**
  30903. * The height above the x-z plane.
  30904. *
  30905. * @type {number}
  30906. * @default 0
  30907. */
  30908. this.y = y;
  30909. }
  30910. /**
  30911. * Sets the cylindrical components by copying the given values.
  30912. *
  30913. * @param {number} radius - The radius.
  30914. * @param {number} theta - The theta angle.
  30915. * @param {number} y - The height value.
  30916. * @return {Cylindrical} A reference to this cylindrical.
  30917. */
  30918. set( radius, theta, y ) {
  30919. this.radius = radius;
  30920. this.theta = theta;
  30921. this.y = y;
  30922. return this;
  30923. }
  30924. /**
  30925. * Copies the values of the given cylindrical to this instance.
  30926. *
  30927. * @param {Cylindrical} other - The cylindrical to copy.
  30928. * @return {Cylindrical} A reference to this cylindrical.
  30929. */
  30930. copy( other ) {
  30931. this.radius = other.radius;
  30932. this.theta = other.theta;
  30933. this.y = other.y;
  30934. return this;
  30935. }
  30936. /**
  30937. * Sets the cylindrical components from the given vector which is assumed to hold
  30938. * Cartesian coordinates.
  30939. *
  30940. * @param {Vector3} v - The vector to set.
  30941. * @return {Cylindrical} A reference to this cylindrical.
  30942. */
  30943. setFromVector3( v ) {
  30944. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30945. }
  30946. /**
  30947. * Sets the cylindrical components from the given Cartesian coordinates.
  30948. *
  30949. * @param {number} x - The x value.
  30950. * @param {number} y - The x value.
  30951. * @param {number} z - The x value.
  30952. * @return {Cylindrical} A reference to this cylindrical.
  30953. */
  30954. setFromCartesianCoords( x, y, z ) {
  30955. this.radius = Math.sqrt( x * x + z * z );
  30956. this.theta = Math.atan2( x, z );
  30957. this.y = y;
  30958. return this;
  30959. }
  30960. /**
  30961. * Returns a new cylindrical with copied values from this instance.
  30962. *
  30963. * @return {Cylindrical} A clone of this instance.
  30964. */
  30965. clone() {
  30966. return new this.constructor().copy( this );
  30967. }
  30968. }
  30969. /**
  30970. * Represents a 2x2 matrix.
  30971. *
  30972. * A Note on Row-Major and Column-Major Ordering:
  30973. *
  30974. * The constructor and {@link Matrix2#set} method take arguments in
  30975. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  30976. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  30977. * This means that calling:
  30978. * ```js
  30979. * const m = new THREE.Matrix2();
  30980. * m.set( 11, 12,
  30981. * 21, 22 );
  30982. * ```
  30983. * will result in the elements array containing:
  30984. * ```js
  30985. * m.elements = [ 11, 21,
  30986. * 12, 22 ];
  30987. * ```
  30988. * and internally all calculations are performed using column-major ordering.
  30989. * However, as the actual ordering makes no difference mathematically and
  30990. * most people are used to thinking about matrices in row-major order, the
  30991. * three.js documentation shows matrices in row-major order. Just bear in
  30992. * mind that if you are reading the source code, you'll have to take the
  30993. * transpose of any matrices outlined here to make sense of the calculations.
  30994. */
  30995. class Matrix2 {
  30996. /**
  30997. * Constructs a new 2x2 matrix. The arguments are supposed to be
  30998. * in row-major order. If no arguments are provided, the constructor
  30999. * initializes the matrix as an identity matrix.
  31000. *
  31001. * @param {number} [n11] - 1-1 matrix element.
  31002. * @param {number} [n12] - 1-2 matrix element.
  31003. * @param {number} [n21] - 2-1 matrix element.
  31004. * @param {number} [n22] - 2-2 matrix element.
  31005. */
  31006. constructor( n11, n12, n21, n22 ) {
  31007. /**
  31008. * This flag can be used for type testing.
  31009. *
  31010. * @type {boolean}
  31011. * @readonly
  31012. * @default true
  31013. */
  31014. Matrix2.prototype.isMatrix2 = true;
  31015. /**
  31016. * A column-major list of matrix values.
  31017. *
  31018. * @type {Array<number>}
  31019. */
  31020. this.elements = [
  31021. 1, 0,
  31022. 0, 1,
  31023. ];
  31024. if ( n11 !== undefined ) {
  31025. this.set( n11, n12, n21, n22 );
  31026. }
  31027. }
  31028. /**
  31029. * Sets this matrix to the 2x2 identity matrix.
  31030. *
  31031. * @return {Matrix2} A reference to this matrix.
  31032. */
  31033. identity() {
  31034. this.set(
  31035. 1, 0,
  31036. 0, 1,
  31037. );
  31038. return this;
  31039. }
  31040. /**
  31041. * Sets the elements of the matrix from the given array.
  31042. *
  31043. * @param {Array<number>} array - The matrix elements in column-major order.
  31044. * @param {number} [offset=0] - Index of the first element in the array.
  31045. * @return {Matrix2} A reference to this matrix.
  31046. */
  31047. fromArray( array, offset = 0 ) {
  31048. for ( let i = 0; i < 4; i ++ ) {
  31049. this.elements[ i ] = array[ i + offset ];
  31050. }
  31051. return this;
  31052. }
  31053. /**
  31054. * Sets the elements of the matrix.The arguments are supposed to be
  31055. * in row-major order.
  31056. *
  31057. * @param {number} n11 - 1-1 matrix element.
  31058. * @param {number} n12 - 1-2 matrix element.
  31059. * @param {number} n21 - 2-1 matrix element.
  31060. * @param {number} n22 - 2-2 matrix element.
  31061. * @return {Matrix2} A reference to this matrix.
  31062. */
  31063. set( n11, n12, n21, n22 ) {
  31064. const te = this.elements;
  31065. te[ 0 ] = n11; te[ 2 ] = n12;
  31066. te[ 1 ] = n21; te[ 3 ] = n22;
  31067. return this;
  31068. }
  31069. }
  31070. const _vector$4 = /*@__PURE__*/ new Vector2();
  31071. /**
  31072. * Represents an axis-aligned bounding box (AABB) in 2D space.
  31073. */
  31074. class Box2 {
  31075. /**
  31076. * Constructs a new bounding box.
  31077. *
  31078. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  31079. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  31080. */
  31081. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  31082. /**
  31083. * This flag can be used for type testing.
  31084. *
  31085. * @type {boolean}
  31086. * @readonly
  31087. * @default true
  31088. */
  31089. this.isBox2 = true;
  31090. /**
  31091. * The lower boundary of the box.
  31092. *
  31093. * @type {Vector2}
  31094. */
  31095. this.min = min;
  31096. /**
  31097. * The upper boundary of the box.
  31098. *
  31099. * @type {Vector2}
  31100. */
  31101. this.max = max;
  31102. }
  31103. /**
  31104. * Sets the lower and upper boundaries of this box.
  31105. * Please note that this method only copies the values from the given objects.
  31106. *
  31107. * @param {Vector2} min - The lower boundary of the box.
  31108. * @param {Vector2} max - The upper boundary of the box.
  31109. * @return {Box2} A reference to this bounding box.
  31110. */
  31111. set( min, max ) {
  31112. this.min.copy( min );
  31113. this.max.copy( max );
  31114. return this;
  31115. }
  31116. /**
  31117. * Sets the upper and lower bounds of this box so it encloses the position data
  31118. * in the given array.
  31119. *
  31120. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  31121. * @return {Box2} A reference to this bounding box.
  31122. */
  31123. setFromPoints( points ) {
  31124. this.makeEmpty();
  31125. for ( let i = 0, il = points.length; i < il; i ++ ) {
  31126. this.expandByPoint( points[ i ] );
  31127. }
  31128. return this;
  31129. }
  31130. /**
  31131. * Centers this box on the given center vector and sets this box's width, height and
  31132. * depth to the given size values.
  31133. *
  31134. * @param {Vector2} center - The center of the box.
  31135. * @param {Vector2} size - The x and y dimensions of the box.
  31136. * @return {Box2} A reference to this bounding box.
  31137. */
  31138. setFromCenterAndSize( center, size ) {
  31139. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  31140. this.min.copy( center ).sub( halfSize );
  31141. this.max.copy( center ).add( halfSize );
  31142. return this;
  31143. }
  31144. /**
  31145. * Returns a new box with copied values from this instance.
  31146. *
  31147. * @return {Box2} A clone of this instance.
  31148. */
  31149. clone() {
  31150. return new this.constructor().copy( this );
  31151. }
  31152. /**
  31153. * Copies the values of the given box to this instance.
  31154. *
  31155. * @param {Box2} box - The box to copy.
  31156. * @return {Box2} A reference to this bounding box.
  31157. */
  31158. copy( box ) {
  31159. this.min.copy( box.min );
  31160. this.max.copy( box.max );
  31161. return this;
  31162. }
  31163. /**
  31164. * Makes this box empty which means in encloses a zero space in 2D.
  31165. *
  31166. * @return {Box2} A reference to this bounding box.
  31167. */
  31168. makeEmpty() {
  31169. this.min.x = this.min.y = + Infinity;
  31170. this.max.x = this.max.y = - Infinity;
  31171. return this;
  31172. }
  31173. /**
  31174. * Returns true if this box includes zero points within its bounds.
  31175. * Note that a box with equal lower and upper bounds still includes one
  31176. * point, the one both bounds share.
  31177. *
  31178. * @return {boolean} Whether this box is empty or not.
  31179. */
  31180. isEmpty() {
  31181. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  31182. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  31183. }
  31184. /**
  31185. * Returns the center point of this box.
  31186. *
  31187. * @param {Vector2} target - The target vector that is used to store the method's result.
  31188. * @return {Vector2} The center point.
  31189. */
  31190. getCenter( target ) {
  31191. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  31192. }
  31193. /**
  31194. * Returns the dimensions of this box.
  31195. *
  31196. * @param {Vector2} target - The target vector that is used to store the method's result.
  31197. * @return {Vector2} The size.
  31198. */
  31199. getSize( target ) {
  31200. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  31201. }
  31202. /**
  31203. * Expands the boundaries of this box to include the given point.
  31204. *
  31205. * @param {Vector2} point - The point that should be included by the bounding box.
  31206. * @return {Box2} A reference to this bounding box.
  31207. */
  31208. expandByPoint( point ) {
  31209. this.min.min( point );
  31210. this.max.max( point );
  31211. return this;
  31212. }
  31213. /**
  31214. * Expands this box equilaterally by the given vector. The width of this
  31215. * box will be expanded by the x component of the vector in both
  31216. * directions. The height of this box will be expanded by the y component of
  31217. * the vector in both directions.
  31218. *
  31219. * @param {Vector2} vector - The vector that should expand the bounding box.
  31220. * @return {Box2} A reference to this bounding box.
  31221. */
  31222. expandByVector( vector ) {
  31223. this.min.sub( vector );
  31224. this.max.add( vector );
  31225. return this;
  31226. }
  31227. /**
  31228. * Expands each dimension of the box by the given scalar. If negative, the
  31229. * dimensions of the box will be contracted.
  31230. *
  31231. * @param {number} scalar - The scalar value that should expand the bounding box.
  31232. * @return {Box2} A reference to this bounding box.
  31233. */
  31234. expandByScalar( scalar ) {
  31235. this.min.addScalar( - scalar );
  31236. this.max.addScalar( scalar );
  31237. return this;
  31238. }
  31239. /**
  31240. * Returns `true` if the given point lies within or on the boundaries of this box.
  31241. *
  31242. * @param {Vector2} point - The point to test.
  31243. * @return {boolean} Whether the bounding box contains the given point or not.
  31244. */
  31245. containsPoint( point ) {
  31246. return point.x >= this.min.x && point.x <= this.max.x &&
  31247. point.y >= this.min.y && point.y <= this.max.y;
  31248. }
  31249. /**
  31250. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  31251. * If this box and the given one are identical, this function also returns `true`.
  31252. *
  31253. * @param {Box2} box - The bounding box to test.
  31254. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  31255. */
  31256. containsBox( box ) {
  31257. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  31258. this.min.y <= box.min.y && box.max.y <= this.max.y;
  31259. }
  31260. /**
  31261. * Returns a point as a proportion of this box's width and height.
  31262. *
  31263. * @param {Vector2} point - A point in 2D space.
  31264. * @param {Vector2} target - The target vector that is used to store the method's result.
  31265. * @return {Vector2} A point as a proportion of this box's width and height.
  31266. */
  31267. getParameter( point, target ) {
  31268. // This can potentially have a divide by zero if the box
  31269. // has a size dimension of 0.
  31270. return target.set(
  31271. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  31272. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  31273. );
  31274. }
  31275. /**
  31276. * Returns `true` if the given bounding box intersects with this bounding box.
  31277. *
  31278. * @param {Box2} box - The bounding box to test.
  31279. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  31280. */
  31281. intersectsBox( box ) {
  31282. // using 4 splitting planes to rule out intersections
  31283. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  31284. box.max.y >= this.min.y && box.min.y <= this.max.y;
  31285. }
  31286. /**
  31287. * Clamps the given point within the bounds of this box.
  31288. *
  31289. * @param {Vector2} point - The point to clamp.
  31290. * @param {Vector2} target - The target vector that is used to store the method's result.
  31291. * @return {Vector2} The clamped point.
  31292. */
  31293. clampPoint( point, target ) {
  31294. return target.copy( point ).clamp( this.min, this.max );
  31295. }
  31296. /**
  31297. * Returns the euclidean distance from any edge of this box to the specified point. If
  31298. * the given point lies inside of this box, the distance will be `0`.
  31299. *
  31300. * @param {Vector2} point - The point to compute the distance to.
  31301. * @return {number} The euclidean distance.
  31302. */
  31303. distanceToPoint( point ) {
  31304. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  31305. }
  31306. /**
  31307. * Computes the intersection of this bounding box and the given one, setting the upper
  31308. * bound of this box to the lesser of the two boxes' upper bounds and the
  31309. * lower bound of this box to the greater of the two boxes' lower bounds. If
  31310. * there's no overlap, makes this box empty.
  31311. *
  31312. * @param {Box2} box - The bounding box to intersect with.
  31313. * @return {Box2} A reference to this bounding box.
  31314. */
  31315. intersect( box ) {
  31316. this.min.max( box.min );
  31317. this.max.min( box.max );
  31318. if ( this.isEmpty() ) this.makeEmpty();
  31319. return this;
  31320. }
  31321. /**
  31322. * Computes the union of this box and another and the given one, setting the upper
  31323. * bound of this box to the greater of the two boxes' upper bounds and the
  31324. * lower bound of this box to the lesser of the two boxes' lower bounds.
  31325. *
  31326. * @param {Box2} box - The bounding box that will be unioned with this instance.
  31327. * @return {Box2} A reference to this bounding box.
  31328. */
  31329. union( box ) {
  31330. this.min.min( box.min );
  31331. this.max.max( box.max );
  31332. return this;
  31333. }
  31334. /**
  31335. * Adds the given offset to both the upper and lower bounds of this bounding box,
  31336. * effectively moving it in 2D space.
  31337. *
  31338. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  31339. * @return {Box2} A reference to this bounding box.
  31340. */
  31341. translate( offset ) {
  31342. this.min.add( offset );
  31343. this.max.add( offset );
  31344. return this;
  31345. }
  31346. /**
  31347. * Returns `true` if this bounding box is equal with the given one.
  31348. *
  31349. * @param {Box2} box - The box to test for equality.
  31350. * @return {boolean} Whether this bounding box is equal with the given one.
  31351. */
  31352. equals( box ) {
  31353. return box.min.equals( this.min ) && box.max.equals( this.max );
  31354. }
  31355. }
  31356. const _startP = /*@__PURE__*/ new Vector3();
  31357. const _startEnd = /*@__PURE__*/ new Vector3();
  31358. /**
  31359. * An analytical line segment in 3D space represented by a start and end point.
  31360. */
  31361. class Line3 {
  31362. /**
  31363. * Constructs a new line segment.
  31364. *
  31365. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  31366. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  31367. */
  31368. constructor( start = new Vector3(), end = new Vector3() ) {
  31369. /**
  31370. * Start of the line segment.
  31371. *
  31372. * @type {Vector3}
  31373. */
  31374. this.start = start;
  31375. /**
  31376. * End of the line segment.
  31377. *
  31378. * @type {Vector3}
  31379. */
  31380. this.end = end;
  31381. }
  31382. /**
  31383. * Sets the start and end values by copying the given vectors.
  31384. *
  31385. * @param {Vector3} start - The start point.
  31386. * @param {Vector3} end - The end point.
  31387. * @return {Line3} A reference to this line segment.
  31388. */
  31389. set( start, end ) {
  31390. this.start.copy( start );
  31391. this.end.copy( end );
  31392. return this;
  31393. }
  31394. /**
  31395. * Copies the values of the given line segment to this instance.
  31396. *
  31397. * @param {Line3} line - The line segment to copy.
  31398. * @return {Line3} A reference to this line segment.
  31399. */
  31400. copy( line ) {
  31401. this.start.copy( line.start );
  31402. this.end.copy( line.end );
  31403. return this;
  31404. }
  31405. /**
  31406. * Returns the center of the line segment.
  31407. *
  31408. * @param {Vector3} target - The target vector that is used to store the method's result.
  31409. * @return {Vector3} The center point.
  31410. */
  31411. getCenter( target ) {
  31412. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  31413. }
  31414. /**
  31415. * Returns the delta vector of the line segment's start and end point.
  31416. *
  31417. * @param {Vector3} target - The target vector that is used to store the method's result.
  31418. * @return {Vector3} The delta vector.
  31419. */
  31420. delta( target ) {
  31421. return target.subVectors( this.end, this.start );
  31422. }
  31423. /**
  31424. * Returns the squared Euclidean distance between the line' start and end point.
  31425. *
  31426. * @return {number} The squared Euclidean distance.
  31427. */
  31428. distanceSq() {
  31429. return this.start.distanceToSquared( this.end );
  31430. }
  31431. /**
  31432. * Returns the Euclidean distance between the line' start and end point.
  31433. *
  31434. * @return {number} The Euclidean distance.
  31435. */
  31436. distance() {
  31437. return this.start.distanceTo( this.end );
  31438. }
  31439. /**
  31440. * Returns a vector at a certain position along the line segment.
  31441. *
  31442. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  31443. * @param {Vector3} target - The target vector that is used to store the method's result.
  31444. * @return {Vector3} The delta vector.
  31445. */
  31446. at( t, target ) {
  31447. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31448. }
  31449. /**
  31450. * Returns a point parameter based on the closest point as projected on the line segment.
  31451. *
  31452. * @param {Vector3} point - The point for which to return a point parameter.
  31453. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  31454. * @return {number} The point parameter.
  31455. */
  31456. closestPointToPointParameter( point, clampToLine ) {
  31457. _startP.subVectors( point, this.start );
  31458. _startEnd.subVectors( this.end, this.start );
  31459. const startEnd2 = _startEnd.dot( _startEnd );
  31460. const startEnd_startP = _startEnd.dot( _startP );
  31461. let t = startEnd_startP / startEnd2;
  31462. if ( clampToLine ) {
  31463. t = clamp( t, 0, 1 );
  31464. }
  31465. return t;
  31466. }
  31467. /**
  31468. * Returns the closets point on the line for a given point.
  31469. *
  31470. * @param {Vector3} point - The point to compute the closest point on the line for.
  31471. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  31472. * @param {Vector3} target - The target vector that is used to store the method's result.
  31473. * @return {Vector3} The closest point on the line.
  31474. */
  31475. closestPointToPoint( point, clampToLine, target ) {
  31476. const t = this.closestPointToPointParameter( point, clampToLine );
  31477. return this.delta( target ).multiplyScalar( t ).add( this.start );
  31478. }
  31479. /**
  31480. * Applies a 4x4 transformation matrix to this line segment.
  31481. *
  31482. * @param {Matrix4} matrix - The transformation matrix.
  31483. * @return {Line3} A reference to this line segment.
  31484. */
  31485. applyMatrix4( matrix ) {
  31486. this.start.applyMatrix4( matrix );
  31487. this.end.applyMatrix4( matrix );
  31488. return this;
  31489. }
  31490. /**
  31491. * Returns `true` if this line segment is equal with the given one.
  31492. *
  31493. * @param {Line3} line - The line segment to test for equality.
  31494. * @return {boolean} Whether this line segment is equal with the given one.
  31495. */
  31496. equals( line ) {
  31497. return line.start.equals( this.start ) && line.end.equals( this.end );
  31498. }
  31499. /**
  31500. * Returns a new line segment with copied values from this instance.
  31501. *
  31502. * @return {Line3} A clone of this instance.
  31503. */
  31504. clone() {
  31505. return new this.constructor().copy( this );
  31506. }
  31507. }
  31508. const _vector$3 = /*@__PURE__*/ new Vector3();
  31509. /**
  31510. * This displays a cone shaped helper object for a {@link SpotLight}.
  31511. *
  31512. * ```js
  31513. * const spotLight = new THREE.SpotLight( 0xffffff );
  31514. * spotLight.position.set( 10, 10, 10 );
  31515. * scene.add( spotLight );
  31516. *
  31517. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  31518. * scene.add( spotLightHelper );
  31519. * ```
  31520. *
  31521. * @augments Object3D
  31522. */
  31523. class SpotLightHelper extends Object3D {
  31524. /**
  31525. * Constructs a new spot light helper.
  31526. *
  31527. * @param {HemisphereLight} light - The light to be visualized.
  31528. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  31529. * the color of the light.
  31530. */
  31531. constructor( light, color ) {
  31532. super();
  31533. /**
  31534. * The light being visualized.
  31535. *
  31536. * @type {SpotLight}
  31537. */
  31538. this.light = light;
  31539. this.matrixAutoUpdate = false;
  31540. /**
  31541. * The color parameter passed in the constructor.
  31542. * If not set, the helper will take the color of the light.
  31543. *
  31544. * @type {number|Color|string}
  31545. */
  31546. this.color = color;
  31547. this.type = 'SpotLightHelper';
  31548. const geometry = new BufferGeometry();
  31549. const positions = [
  31550. 0, 0, 0, 0, 0, 1,
  31551. 0, 0, 0, 1, 0, 1,
  31552. 0, 0, 0, -1, 0, 1,
  31553. 0, 0, 0, 0, 1, 1,
  31554. 0, 0, 0, 0, -1, 1
  31555. ];
  31556. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  31557. const p1 = ( i / l ) * Math.PI * 2;
  31558. const p2 = ( j / l ) * Math.PI * 2;
  31559. positions.push(
  31560. Math.cos( p1 ), Math.sin( p1 ), 1,
  31561. Math.cos( p2 ), Math.sin( p2 ), 1
  31562. );
  31563. }
  31564. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31565. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  31566. this.cone = new LineSegments( geometry, material );
  31567. this.add( this.cone );
  31568. this.update();
  31569. }
  31570. /**
  31571. * Frees the GPU-related resources allocated by this instance. Call this
  31572. * method whenever this instance is no longer used in your app.
  31573. */
  31574. dispose() {
  31575. this.cone.geometry.dispose();
  31576. this.cone.material.dispose();
  31577. }
  31578. /**
  31579. * Updates the helper to match the position and direction of the
  31580. * light being visualized.
  31581. */
  31582. update() {
  31583. this.light.updateWorldMatrix( true, false );
  31584. this.light.target.updateWorldMatrix( true, false );
  31585. // update the local matrix based on the parent and light target transforms
  31586. if ( this.parent ) {
  31587. this.parent.updateWorldMatrix( true );
  31588. this.matrix
  31589. .copy( this.parent.matrixWorld )
  31590. .invert()
  31591. .multiply( this.light.matrixWorld );
  31592. } else {
  31593. this.matrix.copy( this.light.matrixWorld );
  31594. }
  31595. this.matrixWorld.copy( this.light.matrixWorld );
  31596. const coneLength = this.light.distance ? this.light.distance : 1000;
  31597. const coneWidth = coneLength * Math.tan( this.light.angle );
  31598. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  31599. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  31600. this.cone.lookAt( _vector$3 );
  31601. if ( this.color !== undefined ) {
  31602. this.cone.material.color.set( this.color );
  31603. } else {
  31604. this.cone.material.color.copy( this.light.color );
  31605. }
  31606. }
  31607. }
  31608. const _vector$2 = /*@__PURE__*/ new Vector3();
  31609. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  31610. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  31611. /**
  31612. * A helper object to assist with visualizing a {@link Skeleton}.
  31613. *
  31614. * ```js
  31615. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  31616. * scene.add( helper );
  31617. * ```
  31618. *
  31619. * @augments LineSegments
  31620. */
  31621. class SkeletonHelper extends LineSegments {
  31622. /**
  31623. * Constructs a new hemisphere light helper.
  31624. *
  31625. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  31626. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  31627. */
  31628. constructor( object ) {
  31629. const bones = getBoneList( object );
  31630. const geometry = new BufferGeometry();
  31631. const vertices = [];
  31632. const colors = [];
  31633. const color1 = new Color( 0, 0, 1 );
  31634. const color2 = new Color( 0, 1, 0 );
  31635. for ( let i = 0; i < bones.length; i ++ ) {
  31636. const bone = bones[ i ];
  31637. if ( bone.parent && bone.parent.isBone ) {
  31638. vertices.push( 0, 0, 0 );
  31639. vertices.push( 0, 0, 0 );
  31640. colors.push( color1.r, color1.g, color1.b );
  31641. colors.push( color2.r, color2.g, color2.b );
  31642. }
  31643. }
  31644. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31645. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31646. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  31647. super( geometry, material );
  31648. /**
  31649. * This flag can be used for type testing.
  31650. *
  31651. * @type {boolean}
  31652. * @readonly
  31653. * @default true
  31654. */
  31655. this.isSkeletonHelper = true;
  31656. this.type = 'SkeletonHelper';
  31657. /**
  31658. * The object being visualized.
  31659. *
  31660. * @type {Object3D}
  31661. */
  31662. this.root = object;
  31663. /**
  31664. * he list of bones that the helper visualizes.
  31665. *
  31666. * @type {Array<Bone>}
  31667. */
  31668. this.bones = bones;
  31669. this.matrix = object.matrixWorld;
  31670. this.matrixAutoUpdate = false;
  31671. }
  31672. updateMatrixWorld( force ) {
  31673. const bones = this.bones;
  31674. const geometry = this.geometry;
  31675. const position = geometry.getAttribute( 'position' );
  31676. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  31677. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  31678. const bone = bones[ i ];
  31679. if ( bone.parent && bone.parent.isBone ) {
  31680. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  31681. _vector$2.setFromMatrixPosition( _boneMatrix );
  31682. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  31683. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  31684. _vector$2.setFromMatrixPosition( _boneMatrix );
  31685. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  31686. j += 2;
  31687. }
  31688. }
  31689. geometry.getAttribute( 'position' ).needsUpdate = true;
  31690. super.updateMatrixWorld( force );
  31691. }
  31692. /**
  31693. * Frees the GPU-related resources allocated by this instance. Call this
  31694. * method whenever this instance is no longer used in your app.
  31695. */
  31696. dispose() {
  31697. this.geometry.dispose();
  31698. this.material.dispose();
  31699. }
  31700. }
  31701. function getBoneList( object ) {
  31702. const boneList = [];
  31703. if ( object.isBone === true ) {
  31704. boneList.push( object );
  31705. }
  31706. for ( let i = 0; i < object.children.length; i ++ ) {
  31707. boneList.push( ...getBoneList( object.children[ i ] ) );
  31708. }
  31709. return boneList;
  31710. }
  31711. /**
  31712. * This displays a helper object consisting of a spherical mesh for
  31713. * visualizing an instance of {@link PointLight}.
  31714. *
  31715. * ```js
  31716. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  31717. * pointLight.position.set( 10, 10, 10 );
  31718. * scene.add( pointLight );
  31719. *
  31720. * const sphereSize = 1;
  31721. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  31722. * scene.add( pointLightHelper );
  31723. * ```
  31724. *
  31725. * @augments Mesh
  31726. */
  31727. class PointLightHelper extends Mesh {
  31728. /**
  31729. * Constructs a new point light helper.
  31730. *
  31731. * @param {PointLight} light - The light to be visualized.
  31732. * @param {number} [sphereSize=1] - The size of the sphere helper.
  31733. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  31734. * the color of the light.
  31735. */
  31736. constructor( light, sphereSize, color ) {
  31737. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  31738. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31739. super( geometry, material );
  31740. /**
  31741. * The light being visualized.
  31742. *
  31743. * @type {HemisphereLight}
  31744. */
  31745. this.light = light;
  31746. /**
  31747. * The color parameter passed in the constructor.
  31748. * If not set, the helper will take the color of the light.
  31749. *
  31750. * @type {number|Color|string}
  31751. */
  31752. this.color = color;
  31753. this.type = 'PointLightHelper';
  31754. this.matrix = this.light.matrixWorld;
  31755. this.matrixAutoUpdate = false;
  31756. this.update();
  31757. /*
  31758. // TODO: delete this comment?
  31759. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  31760. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  31761. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  31762. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  31763. const d = light.distance;
  31764. if ( d === 0.0 ) {
  31765. this.lightDistance.visible = false;
  31766. } else {
  31767. this.lightDistance.scale.set( d, d, d );
  31768. }
  31769. this.add( this.lightDistance );
  31770. */
  31771. }
  31772. /**
  31773. * Frees the GPU-related resources allocated by this instance. Call this
  31774. * method whenever this instance is no longer used in your app.
  31775. */
  31776. dispose() {
  31777. this.geometry.dispose();
  31778. this.material.dispose();
  31779. }
  31780. /**
  31781. * Updates the helper to match the position of the
  31782. * light being visualized.
  31783. */
  31784. update() {
  31785. this.light.updateWorldMatrix( true, false );
  31786. if ( this.color !== undefined ) {
  31787. this.material.color.set( this.color );
  31788. } else {
  31789. this.material.color.copy( this.light.color );
  31790. }
  31791. /*
  31792. const d = this.light.distance;
  31793. if ( d === 0.0 ) {
  31794. this.lightDistance.visible = false;
  31795. } else {
  31796. this.lightDistance.visible = true;
  31797. this.lightDistance.scale.set( d, d, d );
  31798. }
  31799. */
  31800. }
  31801. }
  31802. const _vector$1 = /*@__PURE__*/ new Vector3();
  31803. const _color1 = /*@__PURE__*/ new Color();
  31804. const _color2 = /*@__PURE__*/ new Color();
  31805. /**
  31806. * Creates a visual aid consisting of a spherical mesh for a
  31807. * given {@link HemisphereLight}.
  31808. *
  31809. * ```js
  31810. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  31811. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  31812. * scene.add( helper );
  31813. * ```
  31814. *
  31815. * @augments Object3D
  31816. */
  31817. class HemisphereLightHelper extends Object3D {
  31818. /**
  31819. * Constructs a new hemisphere light helper.
  31820. *
  31821. * @param {HemisphereLight} light - The light to be visualized.
  31822. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  31823. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  31824. * the color of the light.
  31825. */
  31826. constructor( light, size, color ) {
  31827. super();
  31828. /**
  31829. * The light being visualized.
  31830. *
  31831. * @type {HemisphereLight}
  31832. */
  31833. this.light = light;
  31834. this.matrix = light.matrixWorld;
  31835. this.matrixAutoUpdate = false;
  31836. /**
  31837. * The color parameter passed in the constructor.
  31838. * If not set, the helper will take the color of the light.
  31839. *
  31840. * @type {number|Color|string}
  31841. */
  31842. this.color = color;
  31843. this.type = 'HemisphereLightHelper';
  31844. const geometry = new OctahedronGeometry( size );
  31845. geometry.rotateY( Math.PI * 0.5 );
  31846. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  31847. if ( this.color === undefined ) this.material.vertexColors = true;
  31848. const position = geometry.getAttribute( 'position' );
  31849. const colors = new Float32Array( position.count * 3 );
  31850. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  31851. this.add( new Mesh( geometry, this.material ) );
  31852. this.update();
  31853. }
  31854. /**
  31855. * Frees the GPU-related resources allocated by this instance. Call this
  31856. * method whenever this instance is no longer used in your app.
  31857. */
  31858. dispose() {
  31859. this.children[ 0 ].geometry.dispose();
  31860. this.children[ 0 ].material.dispose();
  31861. }
  31862. /**
  31863. * Updates the helper to match the position and direction of the
  31864. * light being visualized.
  31865. */
  31866. update() {
  31867. const mesh = this.children[ 0 ];
  31868. if ( this.color !== undefined ) {
  31869. this.material.color.set( this.color );
  31870. } else {
  31871. const colors = mesh.geometry.getAttribute( 'color' );
  31872. _color1.copy( this.light.color );
  31873. _color2.copy( this.light.groundColor );
  31874. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  31875. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  31876. colors.setXYZ( i, color.r, color.g, color.b );
  31877. }
  31878. colors.needsUpdate = true;
  31879. }
  31880. this.light.updateWorldMatrix( true, false );
  31881. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  31882. }
  31883. }
  31884. /**
  31885. * The helper is an object to define grids. Grids are two-dimensional
  31886. * arrays of lines.
  31887. *
  31888. * ```js
  31889. * const size = 10;
  31890. * const divisions = 10;
  31891. *
  31892. * const gridHelper = new THREE.GridHelper( size, divisions );
  31893. * scene.add( gridHelper );
  31894. * ```
  31895. *
  31896. * @augments LineSegments
  31897. */
  31898. class GridHelper extends LineSegments {
  31899. /**
  31900. * Constructs a new grid helper.
  31901. *
  31902. * @param {number} [size=10] - The size of the grid.
  31903. * @param {number} [divisions=10] - The number of divisions across the grid.
  31904. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  31905. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  31906. */
  31907. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  31908. color1 = new Color( color1 );
  31909. color2 = new Color( color2 );
  31910. const center = divisions / 2;
  31911. const step = size / divisions;
  31912. const halfSize = size / 2;
  31913. const vertices = [], colors = [];
  31914. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  31915. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  31916. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  31917. const color = i === center ? color1 : color2;
  31918. color.toArray( colors, j ); j += 3;
  31919. color.toArray( colors, j ); j += 3;
  31920. color.toArray( colors, j ); j += 3;
  31921. color.toArray( colors, j ); j += 3;
  31922. }
  31923. const geometry = new BufferGeometry();
  31924. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31925. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31926. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31927. super( geometry, material );
  31928. this.type = 'GridHelper';
  31929. }
  31930. /**
  31931. * Frees the GPU-related resources allocated by this instance. Call this
  31932. * method whenever this instance is no longer used in your app.
  31933. */
  31934. dispose() {
  31935. this.geometry.dispose();
  31936. this.material.dispose();
  31937. }
  31938. }
  31939. /**
  31940. * This helper is an object to define polar grids. Grids are
  31941. * two-dimensional arrays of lines.
  31942. *
  31943. * ```js
  31944. * const radius = 10;
  31945. * const sectors = 16;
  31946. * const rings = 8;
  31947. * const divisions = 64;
  31948. *
  31949. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  31950. * scene.add( helper );
  31951. * ```
  31952. *
  31953. * @augments LineSegments
  31954. */
  31955. class PolarGridHelper extends LineSegments {
  31956. /**
  31957. * Constructs a new polar grid helper.
  31958. *
  31959. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  31960. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  31961. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  31962. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  31963. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  31964. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  31965. */
  31966. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  31967. color1 = new Color( color1 );
  31968. color2 = new Color( color2 );
  31969. const vertices = [];
  31970. const colors = [];
  31971. // create the sectors
  31972. if ( sectors > 1 ) {
  31973. for ( let i = 0; i < sectors; i ++ ) {
  31974. const v = ( i / sectors ) * ( Math.PI * 2 );
  31975. const x = Math.sin( v ) * radius;
  31976. const z = Math.cos( v ) * radius;
  31977. vertices.push( 0, 0, 0 );
  31978. vertices.push( x, 0, z );
  31979. const color = ( i & 1 ) ? color1 : color2;
  31980. colors.push( color.r, color.g, color.b );
  31981. colors.push( color.r, color.g, color.b );
  31982. }
  31983. }
  31984. // create the rings
  31985. for ( let i = 0; i < rings; i ++ ) {
  31986. const color = ( i & 1 ) ? color1 : color2;
  31987. const r = radius - ( radius / rings * i );
  31988. for ( let j = 0; j < divisions; j ++ ) {
  31989. // first vertex
  31990. let v = ( j / divisions ) * ( Math.PI * 2 );
  31991. let x = Math.sin( v ) * r;
  31992. let z = Math.cos( v ) * r;
  31993. vertices.push( x, 0, z );
  31994. colors.push( color.r, color.g, color.b );
  31995. // second vertex
  31996. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  31997. x = Math.sin( v ) * r;
  31998. z = Math.cos( v ) * r;
  31999. vertices.push( x, 0, z );
  32000. colors.push( color.r, color.g, color.b );
  32001. }
  32002. }
  32003. const geometry = new BufferGeometry();
  32004. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32005. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32006. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  32007. super( geometry, material );
  32008. this.type = 'PolarGridHelper';
  32009. }
  32010. /**
  32011. * Frees the GPU-related resources allocated by this instance. Call this
  32012. * method whenever this instance is no longer used in your app.
  32013. */
  32014. dispose() {
  32015. this.geometry.dispose();
  32016. this.material.dispose();
  32017. }
  32018. }
  32019. const _v1 = /*@__PURE__*/ new Vector3();
  32020. const _v2 = /*@__PURE__*/ new Vector3();
  32021. const _v3 = /*@__PURE__*/ new Vector3();
  32022. /**
  32023. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  32024. * effect on the scene. This consists of plane and a line representing the
  32025. * light's position and direction.
  32026. *
  32027. * ```js
  32028. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  32029. * scene.add( light );
  32030. *
  32031. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  32032. * scene.add( helper );
  32033. * ```
  32034. *
  32035. * @augments Object3D
  32036. */
  32037. class DirectionalLightHelper extends Object3D {
  32038. /**
  32039. * Constructs a new directional light helper.
  32040. *
  32041. * @param {DirectionalLight} light - The light to be visualized.
  32042. * @param {number} [size=1] - The dimensions of the plane.
  32043. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  32044. * the color of the light.
  32045. */
  32046. constructor( light, size, color ) {
  32047. super();
  32048. /**
  32049. * The light being visualized.
  32050. *
  32051. * @type {DirectionalLight}
  32052. */
  32053. this.light = light;
  32054. this.matrix = light.matrixWorld;
  32055. this.matrixAutoUpdate = false;
  32056. /**
  32057. * The color parameter passed in the constructor.
  32058. * If not set, the helper will take the color of the light.
  32059. *
  32060. * @type {number|Color|string}
  32061. */
  32062. this.color = color;
  32063. this.type = 'DirectionalLightHelper';
  32064. if ( size === undefined ) size = 1;
  32065. let geometry = new BufferGeometry();
  32066. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  32067. - size, size, 0,
  32068. size, size, 0,
  32069. size, - size, 0,
  32070. - size, - size, 0,
  32071. - size, size, 0
  32072. ], 3 ) );
  32073. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  32074. /**
  32075. * Contains the line showing the location of the directional light.
  32076. *
  32077. * @type {Line}
  32078. */
  32079. this.lightPlane = new Line( geometry, material );
  32080. this.add( this.lightPlane );
  32081. geometry = new BufferGeometry();
  32082. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  32083. /**
  32084. * Represents the target line of the directional light.
  32085. *
  32086. * @type {Line}
  32087. */
  32088. this.targetLine = new Line( geometry, material );
  32089. this.add( this.targetLine );
  32090. this.update();
  32091. }
  32092. /**
  32093. * Frees the GPU-related resources allocated by this instance. Call this
  32094. * method whenever this instance is no longer used in your app.
  32095. */
  32096. dispose() {
  32097. this.lightPlane.geometry.dispose();
  32098. this.lightPlane.material.dispose();
  32099. this.targetLine.geometry.dispose();
  32100. this.targetLine.material.dispose();
  32101. }
  32102. /**
  32103. * Updates the helper to match the position and direction of the
  32104. * light being visualized.
  32105. */
  32106. update() {
  32107. this.light.updateWorldMatrix( true, false );
  32108. this.light.target.updateWorldMatrix( true, false );
  32109. _v1.setFromMatrixPosition( this.light.matrixWorld );
  32110. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  32111. _v3.subVectors( _v2, _v1 );
  32112. this.lightPlane.lookAt( _v2 );
  32113. if ( this.color !== undefined ) {
  32114. this.lightPlane.material.color.set( this.color );
  32115. this.targetLine.material.color.set( this.color );
  32116. } else {
  32117. this.lightPlane.material.color.copy( this.light.color );
  32118. this.targetLine.material.color.copy( this.light.color );
  32119. }
  32120. this.targetLine.lookAt( _v2 );
  32121. this.targetLine.scale.z = _v3.length();
  32122. }
  32123. }
  32124. const _vector = /*@__PURE__*/ new Vector3();
  32125. const _camera = /*@__PURE__*/ new Camera();
  32126. /**
  32127. * This helps with visualizing what a camera contains in its frustum. It
  32128. * visualizes the frustum of a camera using a line segments.
  32129. *
  32130. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  32131. *
  32132. * `CameraHelper` must be a child of the scene.
  32133. *
  32134. * ```js
  32135. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  32136. * const helper = new THREE.CameraHelper( camera );
  32137. * scene.add( helper );
  32138. * ```
  32139. *
  32140. * @augments LineSegments
  32141. */
  32142. class CameraHelper extends LineSegments {
  32143. /**
  32144. * Constructs a new arrow helper.
  32145. *
  32146. * @param {Camera} camera - The camera to visualize.
  32147. */
  32148. constructor( camera ) {
  32149. const geometry = new BufferGeometry();
  32150. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  32151. const vertices = [];
  32152. const colors = [];
  32153. const pointMap = {};
  32154. // near
  32155. addLine( 'n1', 'n2' );
  32156. addLine( 'n2', 'n4' );
  32157. addLine( 'n4', 'n3' );
  32158. addLine( 'n3', 'n1' );
  32159. // far
  32160. addLine( 'f1', 'f2' );
  32161. addLine( 'f2', 'f4' );
  32162. addLine( 'f4', 'f3' );
  32163. addLine( 'f3', 'f1' );
  32164. // sides
  32165. addLine( 'n1', 'f1' );
  32166. addLine( 'n2', 'f2' );
  32167. addLine( 'n3', 'f3' );
  32168. addLine( 'n4', 'f4' );
  32169. // cone
  32170. addLine( 'p', 'n1' );
  32171. addLine( 'p', 'n2' );
  32172. addLine( 'p', 'n3' );
  32173. addLine( 'p', 'n4' );
  32174. // up
  32175. addLine( 'u1', 'u2' );
  32176. addLine( 'u2', 'u3' );
  32177. addLine( 'u3', 'u1' );
  32178. // target
  32179. addLine( 'c', 't' );
  32180. addLine( 'p', 'c' );
  32181. // cross
  32182. addLine( 'cn1', 'cn2' );
  32183. addLine( 'cn3', 'cn4' );
  32184. addLine( 'cf1', 'cf2' );
  32185. addLine( 'cf3', 'cf4' );
  32186. function addLine( a, b ) {
  32187. addPoint( a );
  32188. addPoint( b );
  32189. }
  32190. function addPoint( id ) {
  32191. vertices.push( 0, 0, 0 );
  32192. colors.push( 0, 0, 0 );
  32193. if ( pointMap[ id ] === undefined ) {
  32194. pointMap[ id ] = [];
  32195. }
  32196. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  32197. }
  32198. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32199. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32200. super( geometry, material );
  32201. this.type = 'CameraHelper';
  32202. /**
  32203. * The camera being visualized.
  32204. *
  32205. * @type {Camera}
  32206. */
  32207. this.camera = camera;
  32208. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  32209. this.matrix = camera.matrixWorld;
  32210. this.matrixAutoUpdate = false;
  32211. /**
  32212. * This contains the points used to visualize the camera.
  32213. *
  32214. * @type {Object<string,Array<number>>}
  32215. */
  32216. this.pointMap = pointMap;
  32217. this.update();
  32218. // colors
  32219. const colorFrustum = new Color( 0xffaa00 );
  32220. const colorCone = new Color( 0xff0000 );
  32221. const colorUp = new Color( 0x00aaff );
  32222. const colorTarget = new Color( 0xffffff );
  32223. const colorCross = new Color( 0x333333 );
  32224. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  32225. }
  32226. /**
  32227. * Defines the colors of the helper.
  32228. *
  32229. * @param {Color} frustum - The frustum line color.
  32230. * @param {Color} cone - The cone line color.
  32231. * @param {Color} up - The up line color.
  32232. * @param {Color} target - The target line color.
  32233. * @param {Color} cross - The cross line color.
  32234. */
  32235. setColors( frustum, cone, up, target, cross ) {
  32236. const geometry = this.geometry;
  32237. const colorAttribute = geometry.getAttribute( 'color' );
  32238. // near
  32239. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  32240. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  32241. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  32242. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  32243. // far
  32244. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  32245. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  32246. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  32247. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  32248. // sides
  32249. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  32250. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  32251. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  32252. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  32253. // cone
  32254. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  32255. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  32256. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  32257. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  32258. // up
  32259. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  32260. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  32261. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  32262. // target
  32263. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  32264. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  32265. // cross
  32266. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  32267. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  32268. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  32269. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  32270. colorAttribute.needsUpdate = true;
  32271. }
  32272. /**
  32273. * Updates the helper based on the projection matrix of the camera.
  32274. */
  32275. update() {
  32276. const geometry = this.geometry;
  32277. const pointMap = this.pointMap;
  32278. const w = 1, h = 1;
  32279. // we need just camera projection matrix inverse
  32280. // world matrix must be identity
  32281. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  32282. // Adjust z values based on coordinate system
  32283. const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0;
  32284. // center / target
  32285. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  32286. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  32287. // near
  32288. setPoint( 'n1', pointMap, geometry, _camera, -1, -1, nearZ );
  32289. setPoint( 'n2', pointMap, geometry, _camera, w, -1, nearZ );
  32290. setPoint( 'n3', pointMap, geometry, _camera, -1, h, nearZ );
  32291. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  32292. // far
  32293. setPoint( 'f1', pointMap, geometry, _camera, -1, -1, 1 );
  32294. setPoint( 'f2', pointMap, geometry, _camera, w, -1, 1 );
  32295. setPoint( 'f3', pointMap, geometry, _camera, -1, h, 1 );
  32296. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  32297. // up
  32298. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  32299. setPoint( 'u2', pointMap, geometry, _camera, -1 * 0.7, h * 1.1, nearZ );
  32300. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  32301. // cross
  32302. setPoint( 'cf1', pointMap, geometry, _camera, -1, 0, 1 );
  32303. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  32304. setPoint( 'cf3', pointMap, geometry, _camera, 0, -1, 1 );
  32305. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  32306. setPoint( 'cn1', pointMap, geometry, _camera, -1, 0, nearZ );
  32307. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  32308. setPoint( 'cn3', pointMap, geometry, _camera, 0, -1, nearZ );
  32309. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  32310. geometry.getAttribute( 'position' ).needsUpdate = true;
  32311. }
  32312. /**
  32313. * Frees the GPU-related resources allocated by this instance. Call this
  32314. * method whenever this instance is no longer used in your app.
  32315. */
  32316. dispose() {
  32317. this.geometry.dispose();
  32318. this.material.dispose();
  32319. }
  32320. }
  32321. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  32322. _vector.set( x, y, z ).unproject( camera );
  32323. const points = pointMap[ point ];
  32324. if ( points !== undefined ) {
  32325. const position = geometry.getAttribute( 'position' );
  32326. for ( let i = 0, l = points.length; i < l; i ++ ) {
  32327. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  32328. }
  32329. }
  32330. }
  32331. const _box = /*@__PURE__*/ new Box3();
  32332. /**
  32333. * Helper object to graphically show the world-axis-aligned bounding box
  32334. * around an object. The actual bounding box is handled with {@link Box3},
  32335. * this is just a visual helper for debugging. It can be automatically
  32336. * resized with {@link BoxHelper#update} when the object it's created from
  32337. * is transformed. Note that the object must have a geometry for this to work,
  32338. * so it won't work with sprites.
  32339. *
  32340. * ```js
  32341. * const sphere = new THREE.SphereGeometry();
  32342. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  32343. * const box = new THREE.BoxHelper( object, 0xffff00 );
  32344. * scene.add( box );
  32345. * ```
  32346. *
  32347. * @augments LineSegments
  32348. */
  32349. class BoxHelper extends LineSegments {
  32350. /**
  32351. * Constructs a new box helper.
  32352. *
  32353. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  32354. * @param {number|Color|string} [color=0xffff00] - The box's color.
  32355. */
  32356. constructor( object, color = 0xffff00 ) {
  32357. 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 ] );
  32358. const positions = new Float32Array( 8 * 3 );
  32359. const geometry = new BufferGeometry();
  32360. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32361. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  32362. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32363. /**
  32364. * The 3D object being visualized.
  32365. *
  32366. * @type {Object3D}
  32367. */
  32368. this.object = object;
  32369. this.type = 'BoxHelper';
  32370. this.matrixAutoUpdate = false;
  32371. this.update();
  32372. }
  32373. /**
  32374. * Updates the helper's geometry to match the dimensions of the object,
  32375. * including any children.
  32376. */
  32377. update() {
  32378. if ( this.object !== undefined ) {
  32379. _box.setFromObject( this.object );
  32380. }
  32381. if ( _box.isEmpty() ) return;
  32382. const min = _box.min;
  32383. const max = _box.max;
  32384. /*
  32385. 5____4
  32386. 1/___0/|
  32387. | 6__|_7
  32388. 2/___3/
  32389. 0: max.x, max.y, max.z
  32390. 1: min.x, max.y, max.z
  32391. 2: min.x, min.y, max.z
  32392. 3: max.x, min.y, max.z
  32393. 4: max.x, max.y, min.z
  32394. 5: min.x, max.y, min.z
  32395. 6: min.x, min.y, min.z
  32396. 7: max.x, min.y, min.z
  32397. */
  32398. const position = this.geometry.attributes.position;
  32399. const array = position.array;
  32400. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  32401. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  32402. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  32403. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  32404. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  32405. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  32406. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  32407. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  32408. position.needsUpdate = true;
  32409. this.geometry.computeBoundingSphere();
  32410. }
  32411. /**
  32412. * Updates the wireframe box for the passed object.
  32413. *
  32414. * @param {Object3D} object - The 3D object to create the helper for.
  32415. * @return {BoxHelper} A reference to this instance.
  32416. */
  32417. setFromObject( object ) {
  32418. this.object = object;
  32419. this.update();
  32420. return this;
  32421. }
  32422. copy( source, recursive ) {
  32423. super.copy( source, recursive );
  32424. this.object = source.object;
  32425. return this;
  32426. }
  32427. /**
  32428. * Frees the GPU-related resources allocated by this instance. Call this
  32429. * method whenever this instance is no longer used in your app.
  32430. */
  32431. dispose() {
  32432. this.geometry.dispose();
  32433. this.material.dispose();
  32434. }
  32435. }
  32436. /**
  32437. * A helper object to visualize an instance of {@link Box3}.
  32438. *
  32439. * ```js
  32440. * const box = new THREE.Box3();
  32441. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  32442. *
  32443. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  32444. * scene.add( helper )
  32445. * ```
  32446. *
  32447. * @augments LineSegments
  32448. */
  32449. class Box3Helper extends LineSegments {
  32450. /**
  32451. * Constructs a new box3 helper.
  32452. *
  32453. * @param {Box3} box - The box to visualize.
  32454. * @param {number|Color|string} [color=0xffff00] - The box's color.
  32455. */
  32456. constructor( box, color = 0xffff00 ) {
  32457. 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 ] );
  32458. 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 ];
  32459. const geometry = new BufferGeometry();
  32460. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  32461. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32462. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32463. /**
  32464. * The box being visualized.
  32465. *
  32466. * @type {Box3}
  32467. */
  32468. this.box = box;
  32469. this.type = 'Box3Helper';
  32470. this.geometry.computeBoundingSphere();
  32471. }
  32472. updateMatrixWorld( force ) {
  32473. const box = this.box;
  32474. if ( box.isEmpty() ) return;
  32475. box.getCenter( this.position );
  32476. box.getSize( this.scale );
  32477. this.scale.multiplyScalar( 0.5 );
  32478. super.updateMatrixWorld( force );
  32479. }
  32480. /**
  32481. * Frees the GPU-related resources allocated by this instance. Call this
  32482. * method whenever this instance is no longer used in your app.
  32483. */
  32484. dispose() {
  32485. this.geometry.dispose();
  32486. this.material.dispose();
  32487. }
  32488. }
  32489. /**
  32490. * A helper object to visualize an instance of {@link Plane}.
  32491. *
  32492. * ```js
  32493. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  32494. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  32495. * scene.add( helper );
  32496. * ```
  32497. *
  32498. * @augments Line
  32499. */
  32500. class PlaneHelper extends Line {
  32501. /**
  32502. * Constructs a new plane helper.
  32503. *
  32504. * @param {Plane} plane - The plane to be visualized.
  32505. * @param {number} [size=1] - The side length of plane helper.
  32506. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  32507. */
  32508. constructor( plane, size = 1, hex = 0xffff00 ) {
  32509. const color = hex;
  32510. 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 ];
  32511. const geometry = new BufferGeometry();
  32512. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  32513. geometry.computeBoundingSphere();
  32514. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32515. this.type = 'PlaneHelper';
  32516. /**
  32517. * The plane being visualized.
  32518. *
  32519. * @type {Plane}
  32520. */
  32521. this.plane = plane;
  32522. /**
  32523. * The side length of plane helper.
  32524. *
  32525. * @type {number}
  32526. * @default 1
  32527. */
  32528. this.size = size;
  32529. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  32530. const geometry2 = new BufferGeometry();
  32531. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  32532. geometry2.computeBoundingSphere();
  32533. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  32534. }
  32535. updateMatrixWorld( force ) {
  32536. this.position.set( 0, 0, 0 );
  32537. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  32538. this.lookAt( this.plane.normal );
  32539. this.translateZ( - this.plane.constant );
  32540. super.updateMatrixWorld( force );
  32541. }
  32542. /**
  32543. * Updates the helper to match the position and direction of the
  32544. * light being visualized.
  32545. */
  32546. dispose() {
  32547. this.geometry.dispose();
  32548. this.material.dispose();
  32549. this.children[ 0 ].geometry.dispose();
  32550. this.children[ 0 ].material.dispose();
  32551. }
  32552. }
  32553. const _axis = /*@__PURE__*/ new Vector3();
  32554. let _lineGeometry, _coneGeometry;
  32555. /**
  32556. * An 3D arrow object for visualizing directions.
  32557. *
  32558. * ```js
  32559. * const dir = new THREE.Vector3( 1, 2, 0 );
  32560. *
  32561. * //normalize the direction vector (convert to vector of length 1)
  32562. * dir.normalize();
  32563. *
  32564. * const origin = new THREE.Vector3( 0, 0, 0 );
  32565. * const length = 1;
  32566. * const hex = 0xffff00;
  32567. *
  32568. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  32569. * scene.add( arrowHelper );
  32570. * ```
  32571. *
  32572. * @augments Object3D
  32573. */
  32574. class ArrowHelper extends Object3D {
  32575. /**
  32576. * Constructs a new arrow helper.
  32577. *
  32578. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  32579. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  32580. * @param {number} [length=1] - Length of the arrow in world units.
  32581. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  32582. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  32583. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  32584. */
  32585. 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 ) {
  32586. super();
  32587. this.type = 'ArrowHelper';
  32588. if ( _lineGeometry === undefined ) {
  32589. _lineGeometry = new BufferGeometry();
  32590. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  32591. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  32592. _coneGeometry.translate( 0, -0.5, 0 );
  32593. }
  32594. this.position.copy( origin );
  32595. /**
  32596. * The line part of the arrow helper.
  32597. *
  32598. * @type {Line}
  32599. */
  32600. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  32601. this.line.matrixAutoUpdate = false;
  32602. this.add( this.line );
  32603. /**
  32604. * The cone part of the arrow helper.
  32605. *
  32606. * @type {Mesh}
  32607. */
  32608. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  32609. this.cone.matrixAutoUpdate = false;
  32610. this.add( this.cone );
  32611. this.setDirection( dir );
  32612. this.setLength( length, headLength, headWidth );
  32613. }
  32614. /**
  32615. * Sets the direction of the helper.
  32616. *
  32617. * @param {Vector3} dir - The normalized direction vector.
  32618. */
  32619. setDirection( dir ) {
  32620. // dir is assumed to be normalized
  32621. if ( dir.y > 0.99999 ) {
  32622. this.quaternion.set( 0, 0, 0, 1 );
  32623. } else if ( dir.y < -0.99999 ) {
  32624. this.quaternion.set( 1, 0, 0, 0 );
  32625. } else {
  32626. _axis.set( dir.z, 0, - dir.x ).normalize();
  32627. const radians = Math.acos( dir.y );
  32628. this.quaternion.setFromAxisAngle( _axis, radians );
  32629. }
  32630. }
  32631. /**
  32632. * Sets the length of the helper.
  32633. *
  32634. * @param {number} length - Length of the arrow in world units.
  32635. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  32636. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  32637. */
  32638. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  32639. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  32640. this.line.updateMatrix();
  32641. this.cone.scale.set( headWidth, headLength, headWidth );
  32642. this.cone.position.y = length;
  32643. this.cone.updateMatrix();
  32644. }
  32645. /**
  32646. * Sets the color of the helper.
  32647. *
  32648. * @param {number|Color|string} color - The color to set.
  32649. */
  32650. setColor( color ) {
  32651. this.line.material.color.set( color );
  32652. this.cone.material.color.set( color );
  32653. }
  32654. copy( source ) {
  32655. super.copy( source, false );
  32656. this.line.copy( source.line );
  32657. this.cone.copy( source.cone );
  32658. return this;
  32659. }
  32660. /**
  32661. * Frees the GPU-related resources allocated by this instance. Call this
  32662. * method whenever this instance is no longer used in your app.
  32663. */
  32664. dispose() {
  32665. this.line.geometry.dispose();
  32666. this.line.material.dispose();
  32667. this.cone.geometry.dispose();
  32668. this.cone.material.dispose();
  32669. }
  32670. }
  32671. /**
  32672. * An axis object to visualize the 3 axes in a simple way.
  32673. * The X axis is red. The Y axis is green. The Z axis is blue.
  32674. *
  32675. * ```js
  32676. * const axesHelper = new THREE.AxesHelper( 5 );
  32677. * scene.add( axesHelper );
  32678. * ```
  32679. *
  32680. * @augments LineSegments
  32681. */
  32682. class AxesHelper extends LineSegments {
  32683. /**
  32684. * Constructs a new axes helper.
  32685. *
  32686. * @param {number} [size=1] - Size of the lines representing the axes.
  32687. */
  32688. constructor( size = 1 ) {
  32689. const vertices = [
  32690. 0, 0, 0, size, 0, 0,
  32691. 0, 0, 0, 0, size, 0,
  32692. 0, 0, 0, 0, 0, size
  32693. ];
  32694. const colors = [
  32695. 1, 0, 0, 1, 0.6, 0,
  32696. 0, 1, 0, 0.6, 1, 0,
  32697. 0, 0, 1, 0, 0.6, 1
  32698. ];
  32699. const geometry = new BufferGeometry();
  32700. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  32701. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  32702. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  32703. super( geometry, material );
  32704. this.type = 'AxesHelper';
  32705. }
  32706. /**
  32707. * Defines the colors of the axes helper.
  32708. *
  32709. * @param {number|Color|string} xAxisColor - The color for the x axis.
  32710. * @param {number|Color|string} yAxisColor - The color for the y axis.
  32711. * @param {number|Color|string} zAxisColor - The color for the z axis.
  32712. * @return {AxesHelper} A reference to this axes helper.
  32713. */
  32714. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  32715. const color = new Color();
  32716. const array = this.geometry.attributes.color.array;
  32717. color.set( xAxisColor );
  32718. color.toArray( array, 0 );
  32719. color.toArray( array, 3 );
  32720. color.set( yAxisColor );
  32721. color.toArray( array, 6 );
  32722. color.toArray( array, 9 );
  32723. color.set( zAxisColor );
  32724. color.toArray( array, 12 );
  32725. color.toArray( array, 15 );
  32726. this.geometry.attributes.color.needsUpdate = true;
  32727. return this;
  32728. }
  32729. /**
  32730. * Frees the GPU-related resources allocated by this instance. Call this
  32731. * method whenever this instance is no longer used in your app.
  32732. */
  32733. dispose() {
  32734. this.geometry.dispose();
  32735. this.material.dispose();
  32736. }
  32737. }
  32738. /**
  32739. * This class is used to convert a series of paths to an array of
  32740. * shapes. It is specifically used in context of fonts and SVG.
  32741. */
  32742. class ShapePath {
  32743. /**
  32744. * Constructs a new shape path.
  32745. */
  32746. constructor() {
  32747. this.type = 'ShapePath';
  32748. /**
  32749. * The color of the shape.
  32750. *
  32751. * @type {Color}
  32752. */
  32753. this.color = new Color();
  32754. /**
  32755. * The paths that have been generated for this shape.
  32756. *
  32757. * @type {Array<Path>}
  32758. * @default null
  32759. */
  32760. this.subPaths = [];
  32761. /**
  32762. * The current path that is being generated.
  32763. *
  32764. * @type {?Path}
  32765. * @default null
  32766. */
  32767. this.currentPath = null;
  32768. }
  32769. /**
  32770. * Creates a new path and moves it current point to the given one.
  32771. *
  32772. * @param {number} x - The x coordinate.
  32773. * @param {number} y - The y coordinate.
  32774. * @return {ShapePath} A reference to this shape path.
  32775. */
  32776. moveTo( x, y ) {
  32777. this.currentPath = new Path();
  32778. this.subPaths.push( this.currentPath );
  32779. this.currentPath.moveTo( x, y );
  32780. return this;
  32781. }
  32782. /**
  32783. * Adds an instance of {@link LineCurve} to the path by connecting
  32784. * the current point with the given one.
  32785. *
  32786. * @param {number} x - The x coordinate of the end point.
  32787. * @param {number} y - The y coordinate of the end point.
  32788. * @return {ShapePath} A reference to this shape path.
  32789. */
  32790. lineTo( x, y ) {
  32791. this.currentPath.lineTo( x, y );
  32792. return this;
  32793. }
  32794. /**
  32795. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  32796. * the current point with the given one.
  32797. *
  32798. * @param {number} aCPx - The x coordinate of the control point.
  32799. * @param {number} aCPy - The y coordinate of the control point.
  32800. * @param {number} aX - The x coordinate of the end point.
  32801. * @param {number} aY - The y coordinate of the end point.
  32802. * @return {ShapePath} A reference to this shape path.
  32803. */
  32804. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  32805. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  32806. return this;
  32807. }
  32808. /**
  32809. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  32810. * the current point with the given one.
  32811. *
  32812. * @param {number} aCP1x - The x coordinate of the first control point.
  32813. * @param {number} aCP1y - The y coordinate of the first control point.
  32814. * @param {number} aCP2x - The x coordinate of the second control point.
  32815. * @param {number} aCP2y - The y coordinate of the second control point.
  32816. * @param {number} aX - The x coordinate of the end point.
  32817. * @param {number} aY - The y coordinate of the end point.
  32818. * @return {ShapePath} A reference to this shape path.
  32819. */
  32820. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  32821. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  32822. return this;
  32823. }
  32824. /**
  32825. * Adds an instance of {@link SplineCurve} to the path by connecting
  32826. * the current point with the given list of points.
  32827. *
  32828. * @param {Array<Vector2>} pts - An array of points in 2D space.
  32829. * @return {ShapePath} A reference to this shape path.
  32830. */
  32831. splineThru( pts ) {
  32832. this.currentPath.splineThru( pts );
  32833. return this;
  32834. }
  32835. /**
  32836. * Converts the paths into an array of shapes.
  32837. *
  32838. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  32839. * If this flag is set to `true`, then those are flipped.
  32840. * @return {Array<Shape>} An array of shapes.
  32841. */
  32842. toShapes( isCCW ) {
  32843. function toShapesNoHoles( inSubpaths ) {
  32844. const shapes = [];
  32845. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  32846. const tmpPath = inSubpaths[ i ];
  32847. const tmpShape = new Shape();
  32848. tmpShape.curves = tmpPath.curves;
  32849. shapes.push( tmpShape );
  32850. }
  32851. return shapes;
  32852. }
  32853. function isPointInsidePolygon( inPt, inPolygon ) {
  32854. const polyLen = inPolygon.length;
  32855. // inPt on polygon contour => immediate success or
  32856. // toggling of inside/outside at every single! intersection point of an edge
  32857. // with the horizontal line through inPt, left of inPt
  32858. // not counting lowerY endpoints of edges and whole edges on that line
  32859. let inside = false;
  32860. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  32861. let edgeLowPt = inPolygon[ p ];
  32862. let edgeHighPt = inPolygon[ q ];
  32863. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  32864. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  32865. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  32866. // not parallel
  32867. if ( edgeDy < 0 ) {
  32868. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  32869. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  32870. }
  32871. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  32872. if ( inPt.y === edgeLowPt.y ) {
  32873. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  32874. // continue; // no intersection or edgeLowPt => doesn't count !!!
  32875. } else {
  32876. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  32877. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  32878. if ( perpEdge < 0 ) continue;
  32879. inside = ! inside; // true intersection left of inPt
  32880. }
  32881. } else {
  32882. // parallel or collinear
  32883. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  32884. // edge lies on the same horizontal line as inPt
  32885. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  32886. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  32887. // continue;
  32888. }
  32889. }
  32890. return inside;
  32891. }
  32892. const isClockWise = ShapeUtils.isClockWise;
  32893. const subPaths = this.subPaths;
  32894. if ( subPaths.length === 0 ) return [];
  32895. let solid, tmpPath, tmpShape;
  32896. const shapes = [];
  32897. if ( subPaths.length === 1 ) {
  32898. tmpPath = subPaths[ 0 ];
  32899. tmpShape = new Shape();
  32900. tmpShape.curves = tmpPath.curves;
  32901. shapes.push( tmpShape );
  32902. return shapes;
  32903. }
  32904. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  32905. holesFirst = isCCW ? ! holesFirst : holesFirst;
  32906. // console.log("Holes first", holesFirst);
  32907. const betterShapeHoles = [];
  32908. const newShapes = [];
  32909. let newShapeHoles = [];
  32910. let mainIdx = 0;
  32911. let tmpPoints;
  32912. newShapes[ mainIdx ] = undefined;
  32913. newShapeHoles[ mainIdx ] = [];
  32914. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  32915. tmpPath = subPaths[ i ];
  32916. tmpPoints = tmpPath.getPoints();
  32917. solid = isClockWise( tmpPoints );
  32918. solid = isCCW ? ! solid : solid;
  32919. if ( solid ) {
  32920. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  32921. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  32922. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  32923. if ( holesFirst ) mainIdx ++;
  32924. newShapeHoles[ mainIdx ] = [];
  32925. //console.log('cw', i);
  32926. } else {
  32927. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  32928. //console.log('ccw', i);
  32929. }
  32930. }
  32931. // only Holes? -> probably all Shapes with wrong orientation
  32932. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  32933. if ( newShapes.length > 1 ) {
  32934. let ambiguous = false;
  32935. let toChange = 0;
  32936. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  32937. betterShapeHoles[ sIdx ] = [];
  32938. }
  32939. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  32940. const sho = newShapeHoles[ sIdx ];
  32941. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  32942. const ho = sho[ hIdx ];
  32943. let hole_unassigned = true;
  32944. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  32945. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  32946. if ( sIdx !== s2Idx ) toChange ++;
  32947. if ( hole_unassigned ) {
  32948. hole_unassigned = false;
  32949. betterShapeHoles[ s2Idx ].push( ho );
  32950. } else {
  32951. ambiguous = true;
  32952. }
  32953. }
  32954. }
  32955. if ( hole_unassigned ) {
  32956. betterShapeHoles[ sIdx ].push( ho );
  32957. }
  32958. }
  32959. }
  32960. if ( toChange > 0 && ambiguous === false ) {
  32961. newShapeHoles = betterShapeHoles;
  32962. }
  32963. }
  32964. let tmpHoles;
  32965. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  32966. tmpShape = newShapes[ i ].s;
  32967. shapes.push( tmpShape );
  32968. tmpHoles = newShapeHoles[ i ];
  32969. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  32970. tmpShape.holes.push( tmpHoles[ j ].h );
  32971. }
  32972. }
  32973. //console.log("shape", shapes);
  32974. return shapes;
  32975. }
  32976. }
  32977. /**
  32978. * Abstract base class for controls.
  32979. *
  32980. * @abstract
  32981. * @augments EventDispatcher
  32982. */
  32983. class Controls extends EventDispatcher {
  32984. /**
  32985. * Constructs a new controls instance.
  32986. *
  32987. * @param {Object3D} object - The object that is managed by the controls.
  32988. * @param {?HTMLDOMElement} domElement - The HTML element used for event listeners.
  32989. */
  32990. constructor( object, domElement = null ) {
  32991. super();
  32992. /**
  32993. * The object that is managed by the controls.
  32994. *
  32995. * @type {Object3D}
  32996. */
  32997. this.object = object;
  32998. /**
  32999. * The HTML element used for event listeners.
  33000. *
  33001. * @type {?HTMLDOMElement}
  33002. * @default null
  33003. */
  33004. this.domElement = domElement;
  33005. /**
  33006. * Whether the controls responds to user input or not.
  33007. *
  33008. * @type {boolean}
  33009. * @default true
  33010. */
  33011. this.enabled = true;
  33012. /**
  33013. * The internal state of the controls.
  33014. *
  33015. * @type {number}
  33016. * @default -1
  33017. */
  33018. this.state = -1;
  33019. /**
  33020. * This object defines the keyboard input of the controls.
  33021. *
  33022. * @type {Object}
  33023. */
  33024. this.keys = {};
  33025. /**
  33026. * This object defines what type of actions are assigned to the available mouse buttons.
  33027. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  33028. *
  33029. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  33030. */
  33031. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  33032. /**
  33033. * This object defines what type of actions are assigned to what kind of touch interaction.
  33034. * It depends on the control implementation what kind of touch interaction and actions are supported.
  33035. *
  33036. * @type {{ONE: ?number, TWO: ?number}}
  33037. */
  33038. this.touches = { ONE: null, TWO: null };
  33039. }
  33040. /**
  33041. * Connects the controls to the DOM. This method has so called "side effects" since
  33042. * it adds the module's event listeners to the DOM.
  33043. */
  33044. connect() {}
  33045. /**
  33046. * Disconnects the controls from the DOM.
  33047. */
  33048. disconnect() {}
  33049. /**
  33050. * Call this method if you no longer want use to the controls. It frees all internal
  33051. * resources and removes all event listeners.
  33052. */
  33053. dispose() {}
  33054. /**
  33055. * Controls should implement this method if they have to update their internal state
  33056. * per simulation step.
  33057. *
  33058. * @param {number} [delta] - The time delta in seconds.
  33059. */
  33060. update( /* delta */ ) {}
  33061. }
  33062. /**
  33063. * Scales the texture as large as possible within its surface without cropping
  33064. * or stretching the texture. The method preserves the original aspect ratio of
  33065. * the texture. Akin to CSS `object-fit: contain`
  33066. *
  33067. * @param {Texture} texture - The texture.
  33068. * @param {number} aspect - The texture's aspect ratio.
  33069. * @return {Texture} The updated texture.
  33070. */
  33071. function contain( texture, aspect ) {
  33072. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  33073. if ( imageAspect > aspect ) {
  33074. texture.repeat.x = 1;
  33075. texture.repeat.y = imageAspect / aspect;
  33076. texture.offset.x = 0;
  33077. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  33078. } else {
  33079. texture.repeat.x = aspect / imageAspect;
  33080. texture.repeat.y = 1;
  33081. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  33082. texture.offset.y = 0;
  33083. }
  33084. return texture;
  33085. }
  33086. /**
  33087. * Scales the texture to the smallest possible size to fill the surface, leaving
  33088. * no empty space. The method preserves the original aspect ratio of the texture.
  33089. * Akin to CSS `object-fit: cover`.
  33090. *
  33091. * @param {Texture} texture - The texture.
  33092. * @param {number} aspect - The texture's aspect ratio.
  33093. * @return {Texture} The updated texture.
  33094. */
  33095. function cover( texture, aspect ) {
  33096. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  33097. if ( imageAspect > aspect ) {
  33098. texture.repeat.x = aspect / imageAspect;
  33099. texture.repeat.y = 1;
  33100. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  33101. texture.offset.y = 0;
  33102. } else {
  33103. texture.repeat.x = 1;
  33104. texture.repeat.y = imageAspect / aspect;
  33105. texture.offset.x = 0;
  33106. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  33107. }
  33108. return texture;
  33109. }
  33110. /**
  33111. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  33112. *
  33113. * @param {Texture} texture - The texture.
  33114. * @return {Texture} The updated texture.
  33115. */
  33116. function fill( texture ) {
  33117. texture.repeat.x = 1;
  33118. texture.repeat.y = 1;
  33119. texture.offset.x = 0;
  33120. texture.offset.y = 0;
  33121. return texture;
  33122. }
  33123. /**
  33124. * Determines how many bytes must be used to represent the texture.
  33125. *
  33126. * @param {number} width - The width of the texture.
  33127. * @param {number} height - The height of the texture.
  33128. * @param {number} format - The texture's format.
  33129. * @param {number} type - The texture's type.
  33130. * @return {number} The byte length.
  33131. */
  33132. function getByteLength( width, height, format, type ) {
  33133. const typeByteLength = getTextureTypeByteLength( type );
  33134. switch ( format ) {
  33135. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  33136. case AlphaFormat:
  33137. return width * height;
  33138. case LuminanceFormat:
  33139. return width * height;
  33140. case LuminanceAlphaFormat:
  33141. return width * height * 2;
  33142. case RedFormat:
  33143. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  33144. case RedIntegerFormat:
  33145. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  33146. case RGFormat:
  33147. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33148. case RGIntegerFormat:
  33149. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33150. case RGBFormat:
  33151. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33152. case RGBAFormat:
  33153. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33154. case RGBAIntegerFormat:
  33155. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  33156. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  33157. case RGB_S3TC_DXT1_Format:
  33158. case RGBA_S3TC_DXT1_Format:
  33159. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  33160. case RGBA_S3TC_DXT3_Format:
  33161. case RGBA_S3TC_DXT5_Format:
  33162. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33163. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  33164. case RGB_PVRTC_2BPPV1_Format:
  33165. case RGBA_PVRTC_2BPPV1_Format:
  33166. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  33167. case RGB_PVRTC_4BPPV1_Format:
  33168. case RGBA_PVRTC_4BPPV1_Format:
  33169. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  33170. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  33171. case RGB_ETC1_Format:
  33172. case RGB_ETC2_Format:
  33173. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  33174. case RGBA_ETC2_EAC_Format:
  33175. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33176. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  33177. case RGBA_ASTC_4x4_Format:
  33178. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33179. case RGBA_ASTC_5x4_Format:
  33180. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  33181. case RGBA_ASTC_5x5_Format:
  33182. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33183. case RGBA_ASTC_6x5_Format:
  33184. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33185. case RGBA_ASTC_6x6_Format:
  33186. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  33187. case RGBA_ASTC_8x5_Format:
  33188. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33189. case RGBA_ASTC_8x6_Format:
  33190. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  33191. case RGBA_ASTC_8x8_Format:
  33192. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  33193. case RGBA_ASTC_10x5_Format:
  33194. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  33195. case RGBA_ASTC_10x6_Format:
  33196. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  33197. case RGBA_ASTC_10x8_Format:
  33198. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  33199. case RGBA_ASTC_10x10_Format:
  33200. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  33201. case RGBA_ASTC_12x10_Format:
  33202. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  33203. case RGBA_ASTC_12x12_Format:
  33204. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  33205. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  33206. case RGBA_BPTC_Format:
  33207. case RGB_BPTC_SIGNED_Format:
  33208. case RGB_BPTC_UNSIGNED_Format:
  33209. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  33210. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  33211. case RED_RGTC1_Format:
  33212. case SIGNED_RED_RGTC1_Format:
  33213. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  33214. case RED_GREEN_RGTC2_Format:
  33215. case SIGNED_RED_GREEN_RGTC2_Format:
  33216. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  33217. }
  33218. throw new Error(
  33219. `Unable to determine texture byte length for ${format} format.`,
  33220. );
  33221. }
  33222. function getTextureTypeByteLength( type ) {
  33223. switch ( type ) {
  33224. case UnsignedByteType:
  33225. case ByteType:
  33226. return { byteLength: 1, components: 1 };
  33227. case UnsignedShortType:
  33228. case ShortType:
  33229. case HalfFloatType:
  33230. return { byteLength: 2, components: 1 };
  33231. case UnsignedShort4444Type:
  33232. case UnsignedShort5551Type:
  33233. return { byteLength: 2, components: 4 };
  33234. case UnsignedIntType:
  33235. case IntType:
  33236. case FloatType:
  33237. return { byteLength: 4, components: 1 };
  33238. case UnsignedInt5999Type:
  33239. return { byteLength: 4, components: 3 };
  33240. }
  33241. throw new Error( `Unknown texture type ${type}.` );
  33242. }
  33243. /**
  33244. * A class containing utility functions for textures.
  33245. *
  33246. * @hideconstructor
  33247. */
  33248. class TextureUtils {
  33249. /**
  33250. * Scales the texture as large as possible within its surface without cropping
  33251. * or stretching the texture. The method preserves the original aspect ratio of
  33252. * the texture. Akin to CSS `object-fit: contain`
  33253. *
  33254. * @param {Texture} texture - The texture.
  33255. * @param {number} aspect - The texture's aspect ratio.
  33256. * @return {Texture} The updated texture.
  33257. */
  33258. static contain( texture, aspect ) {
  33259. return contain( texture, aspect );
  33260. }
  33261. /**
  33262. * Scales the texture to the smallest possible size to fill the surface, leaving
  33263. * no empty space. The method preserves the original aspect ratio of the texture.
  33264. * Akin to CSS `object-fit: cover`.
  33265. *
  33266. * @param {Texture} texture - The texture.
  33267. * @param {number} aspect - The texture's aspect ratio.
  33268. * @return {Texture} The updated texture.
  33269. */
  33270. static cover( texture, aspect ) {
  33271. return cover( texture, aspect );
  33272. }
  33273. /**
  33274. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  33275. *
  33276. * @param {Texture} texture - The texture.
  33277. * @return {Texture} The updated texture.
  33278. */
  33279. static fill( texture ) {
  33280. return fill( texture );
  33281. }
  33282. /**
  33283. * Determines how many bytes must be used to represent the texture.
  33284. *
  33285. * @param {number} width - The width of the texture.
  33286. * @param {number} height - The height of the texture.
  33287. * @param {number} format - The texture's format.
  33288. * @param {number} type - The texture's type.
  33289. * @return {number} The byte length.
  33290. */
  33291. static getByteLength( width, height, format, type ) {
  33292. return getByteLength( width, height, format, type );
  33293. }
  33294. }
  33295. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  33296. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  33297. revision: REVISION,
  33298. } } ) );
  33299. }
  33300. if ( typeof window !== 'undefined' ) {
  33301. if ( window.__THREE__ ) {
  33302. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  33303. } else {
  33304. window.__THREE__ = REVISION;
  33305. }
  33306. }
  33307. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RAD2DEG, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RenderTarget3D, RenderTargetArray, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLRenderTarget, WebGPUCoordinateSystem, WebXRController, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, arrayNeedsUint32, cloneUniforms, createCanvasElement, createElementNS, getByteLength, getUnlitUniformColorSpace, mergeUniforms, probeAsync, toNormalizedProjectionMatrix, toReversedProjectionMatrix, warnOnce };